0% found this document useful (0 votes)
26 views6 pages

Pset2file - Jupyter Notebook

Uploaded by

flampoyantorange
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views6 pages

Pset2file - Jupyter Notebook

Uploaded by

flampoyantorange
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

11/1/22, 5:51 PM pset2file - Jupyter Notebook

localhost:8888/notebooks/Documents/ocw/pset2file.ipynb 1/6
11/1/22, 5:51 PM pset2file - Jupyter Notebook

In [*]: # Problem Set 2, hangman.py


# Name:
# Collaborators:
# Time spent:

# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string

WORDLIST_FILENAME = "words.txt"


def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.

Depending on the size of the word list, this function may


take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist



def choose_word(wordlist):
"""
wordlist (list): list of words (strings)

Returns a word from wordlist at random


"""
return random.choice(wordlist)

# end of helper code

# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = load_words()


def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the letters of secret_word are in letters_guessed;
False otherwise
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
for i in secret_word:
if i not in letters_guessed:
return False
# else:
# continue
return True

def get_guessed_word(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing
letters_guessed: list (of letters), which letters have been guessed so far
returns: string, comprised of letters, underscores (_), and spaces that represents
which letters in secret_word have been guessed so far.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
guessed_word = ''
for i in secret_word:
if i in letters_guessed:
guessed_word += i
else:
guessed_word += '_'
return guessed_word

localhost:8888/notebooks/Documents/ocw/pset2file.ipynb 2/6
11/1/22, 5:51 PM pset2file - Jupyter Notebook

def get_available_letters(letters_guessed):
'''
letters_guessed: list (of letters), which letters have been guessed so far
returns: string (of letters), comprised of letters that represents which letters have not
yet been guessed.
'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
alphabet = 'abcdefghijklmnopqrstuvwxyz'
not_guessed = ''
for i in alphabet:
if i not in letters_guessed:
not_guessed += i
return not_guessed


def hangman(secret_word):
'''
secret_word: string, the secret word to guess.

Starts up an interactive game of Hangman.

* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.

* The user should start with 6 guesses



* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.

* Ask the user to supply one guess per round. Remember to make
sure that the user puts in a letter!

* The user should receive feedback immediately after each guess


about whether their guess appears in the computer's word.

* After each guess, you should display to the user the
partially guessed word so far.

Follows the other limitations detailed in the problem write-up.


'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
print ("Welcome to the game Hangman!")
secret_word = choose_word(wordlist)
print ('I am thinking of a word that is' + ' ' + str(len(secret_word)) + ' ' + 'letters long')
letters_guessed = ''
guesses_remaining = 6
warnings_remaining = 3
vowels = 'aeiou'
good_guess = 0
unique = []

for i in secret_word[::]:
if i not in unique:
unique.append(i)

unique_letters_in_secret_word = len(unique)

print ('------------')
while guesses_remaining > 0 and warnings_remaining > 0:
print ('You have' + ' ' + str(guesses_remaining) + ' ' + 'guesses left.')
print ('Available letters: ' + get_available_letters(letters_guessed))
guess = input('Please guess a letter: ').lower()
guess_is_alpha = guess.isalpha()
if not guess_is_alpha:
warnings_remaining -= 1
print ("Oops! That isn't a letter. You have " + ' ' + str(warnings_remaining) + ' ' +'warnings le
continue #loops it back up to the start
elif guess in secret_word and guess not in letters_guessed:
letters_guessed += guess
good_guess += 1
print ('Good guess:' + get_guessed_word(secret_word, letters_guessed))
elif guess in letters_guessed:
warnings_remaining -= 1
print ("Oops! You've already guessed that letter. You have " + ' ' + str(warnings_remaining) + '
else:
letters_guessed += guess
print ('Oops! That letter is not in my word: ' + get_guessed_word(secret_word, letters_guessed))
if guess in vowels:
guesses_remaining -= 2
else:
guesses_remaining -=1
print ('------------')
if is_word_guessed(secret_word, letters_guessed):
print('Congratulations, you won!')
score = guesses_remaining * unique_letters_in_secret_word
print('Your total score for this game is: ' + str(score))
localhost:8888/notebooks/Documents/ocw/pset2file.ipynb 3/6
11/1/22, 5:51 PM pset2file - Jupyter Notebook
break
if warnings_remaining == 0:
print ('Sorry, you ran out of warnings. The word was ' + secret_word + '.')
if guesses_remaining == 0:
print ('Sorry, you ran out of guesses. The word was ' + secret_word + '.')

# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)


# -----------------------------------



def match_with_gaps(my_word: str, other_word: str) -> bool:
'''
my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special symbol
_ , and my_word and other_word are of the same length;
False otherwise:
'''
if len(my_word) != len(other_word):
return False
else:
import re
strs = my_word
other_word_clone = other_word
underscore_positions = [x.start() for x in re.finditer('\_', strs)]
for i in underscore_positions:
other_word_clone = other_word_clone[0:i] + '_' + other_word_clone[i + 1:]
if other_word_clone == my_word:
return True
return False
# my_word_stripped = my_word.replace(" ", "")
# same_char = []
# blank_stripped = []
# if len(my_word_stripped) != len(other_word):
# return False
# for index, letter in enumerate(my_word_stripped):
# if letter in string.ascii_lowercase:
# same_char.append(index)
# else:
# blank_stripped.append(index)

# mws = ''
# ow = ''
# for index_same in same_char:
# for index_dif in blank_stripped:
# if other_word[index_dif] == other_word[index_same]:
# return False
# mws += my_word_stripped[index_same]
# ow += other_word[index_same]

# return mws == ow



def show_possible_matches(my_word):
'''
my_word: string with _ characters, current guess of secret word
returns: nothing, but should print out every word in wordlist that matches my_word
Keep in mind that in hangman when a letter is guessed, all the positions
at which that letter occurs in the secret word are revealed.
Therefore, the hidden letter(_ ) cannot be one of the letters in the word
that has already been revealed.
'''
# possible_matches = list()
# for i in wordlist:
# if match_with_gaps(my_word, i):
# possible_matches.append(i)

# spm = ' '.join(possible_matches)

# return spm
possible_matches = [i for i in wordlist if match_with_gaps(my_word, i)]
return ' '.join(possible_matches)



def hangman_with_hints(secret_word):
'''
secret_word: string, the secret word to guess.

Starts up an interactive game of Hangman.


localhost:8888/notebooks/Documents/ocw/pset2file.ipynb 4/6
11/1/22, 5:51 PM pset2file - Jupyter Notebook

* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.

* The user should start with 6 guesses

* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.

* Ask the user to supply one guess per round. Make sure to check that the user guesses a letter

* The user should receive feedback immediately after each guess


about whether their guess appears in the computer's word.

* After each guess, you should display to the user the
partially guessed word so far.

* If the guess is the symbol *, print out all words in wordlist that
matches the current guessed word.

Follows the other limitations detailed in the problem write-up.


'''
# FILL IN YOUR CODE HERE AND DELETE "pass"
print ("Welcome to the game Hangman!")
secret_word = choose_word(wordlist)
print ('I am thinking of a word that is' + ' ' + str(len(secret_word)) + ' ' + 'letters long')
letters_guessed = ''
guesses_remaining = 6
warnings_remaining = 3
vowels = 'aeiou'
good_guess = 0
unique = []

for i in secret_word[::]:
if i not in unique:
unique.append(i)

unique_letters_in_secret_word = len(unique)

print ('------------')
while guesses_remaining > 0 and warnings_remaining > 0:
print ('You have' + ' ' + str(guesses_remaining) + ' ' + 'guesses left.')
print ('Available letters: ' + get_available_letters(letters_guessed))
guess = input('Please guess a letter: ').lower()
guess_is_alpha = guess.isalpha()
if guess == '*':
print("Possible matches are:", show_possible_matches(get_guessed_word(secret_word, letters_guesse
elif not guess_is_alpha:
warnings_remaining -= 1
print ("Oops! That isn't a letter. You have " + ' ' + str(warnings_remaining) + ' ' +'warnings le
continue #loops it back up to the start
elif guess in secret_word and guess not in letters_guessed:
letters_guessed += guess
good_guess += 1
print ('Good guess:' + get_guessed_word(secret_word, letters_guessed))
elif guess in letters_guessed:
warnings_remaining -= 1
print ("Oops! You've already guessed that letter. You have " + ' ' + str(warnings_remaining) + '
else:
letters_guessed += guess
print ('Oops! That letter is not in my word: ' + get_guessed_word(secret_word, letters_guessed))
if guess in vowels:
guesses_remaining -= 2
else:
guesses_remaining -=1
print ('------------')
if is_word_guessed(secret_word, letters_guessed):
print('Congratulations, you won!')
score = guesses_remaining * unique_letters_in_secret_word
print('Your total score for this game is: ' + str(score))
break
if warnings_remaining == 0:
print ('Sorry, you ran out of warnings. The word was ' + secret_word + '.')
if guesses_remaining == 0:
print ('Sorry, you ran out of guesses. The word was ' + secret_word + '.')



# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.


if __name__ == "__main__":
# pass

# To test part 2, comment out the pass line above and
localhost:8888/notebooks/Documents/ocw/pset2file.ipynb 5/6
11/1/22, 5:51 PM pset2file - Jupyter Notebook
# uncomment the following two lines.

# secret_word = choose_word(wordlist)
# hangman(secret_word)

###############

# To test part 3 re-comment out the above lines and


# uncomment the following two lines.

secret_word = choose_word(wordlist)
hangman_with_hints(secret_word)

Loading word list from file...


55900 words loaded.
Welcome to the game Hangman!
I am thinking of a word that is 10 letters long
------------
You have 6 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz

Please guess a letter:

In [ ]: ​

In [ ]: ​

localhost:8888/notebooks/Documents/ocw/pset2file.ipynb 6/6

You might also like