MIT6_0001F16_Pset2
完成Hangman Game的编写,就是一个猜词游戏
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 = open(WORDLIST_FILENAME, 'r')
line = inFile.readline()
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)
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
'''
for each1 in secret_word:
if each1 not in letters_guessed:
return False
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.
'''
result=''
for each in secret_word:
if each in letters_guessed:
result+=each
else:
result+='_ '
return result
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.
'''
start=string.ascii_lowercase
result=''
for each in start:
if each in letters_guessed:
continue
else:
result+=each
return result
vowels=['a','e','i','o']
def unique_letters(words):
help_string=''
for each in words:
if each not in help_string:
help_string+=each
else:
continue
return len(help_string)
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.
'''
print("Welcome to the game Hangman!")
print("I am thinking of a word that is %d letters long."%(len(secret_word)))
print('You have 3 warnings left.')
all_lowercase=string.ascii_lowercase
print("-------------")
available_letters= get_available_letters('')
guess_chance=6
warnings_chance=3
guessed=[]
success=False
while guess_chance>0 :
print("You have %d guesses left."%(guess_chance))
print("Available letters: %s"%(available_letters),end="")
my_guess=input("Please guess a letter:")
my_guess=my_guess.lower()
if my_guess not in all_lowercase or len(my_guess)!=1:
warnings_chance-=1
if warnings_chance<0:
guess_chance-=1
print("Oops! That is not a valid letter. You have no warnings left.")
print("so you lose one guess: %s"%(get_guessed_word(secret_word,guessed)))
print('------------')
else:
print("Oops! That is not a valid letter. You have %d warnings left:%s"%(warnings_chance,get_guessed_word(secret_word,guessed)))
print('------------')
continue
if my_guess not in available_letters:
warnings_chance-=1
if warnings_chance<0:
guess_chance-=1
print("Oops! You've already guessed that letter.You have no warnings left.")
print('so you lose one guess: %s'%(get_guessed_word(secret_word,guessed)))
print('------------')
continue
else:
print("Oops! You've already guessed that letter. You have %d warnings left: %s"%(warnings_chance,get_guessed_word(secret_word,guessed)))
print('------------')
continue
else:
if my_guess not in secret_word:
if guess_chance==1:
guess_chance=0
elif my_guess in vowels:
guess_chance-=2
else:
guess_chance-=1
print("Oops! That letter is not in my word:",(get_guessed_word(secret_word,guessed)))
guessed.append(my_guess)
available_letters= get_available_letters(guessed)
print('------------')
else:
guessed.append(my_guess)
available_letters=get_available_letters(guessed)
print("Good guess: ",get_guessed_word(secret_word,guessed))
print("------------")
if is_word_guessed(secret_word, guessed):
success=True
break
if success==True:
print("Congratulations, you won!")
print('Your total score for this game is: ',(guess_chance*unique_letters(secret_word)))
else:
print('Sorry, you ran out of guesses. The word was',secret_word)
def match_with_gaps(my_word, other_word):
'''
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:
'''
my_word = ''.join(my_word.split())
if len(my_word)!=len(other_word):
return False
else:
i=0
result=''
for each in my_word:
if each!='_':
result+=each
while i<len(my_word):
if my_word[i]!='_' and my_word[i]!=other_word[i]:
return False
if my_word[i]=='_' and other_word[i] in result:
return False
i+=1
return True
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.
'''
flag=False
for each in wordlist:
if match_with_gaps(my_word,each):
flag=True
print(each,' ',end='')
if flag==False:
print("No matches found")
else:
print("")
def hangman_with_hints(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. 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.
'''
print("Welcome to the game Hangman!")
print("I am thinking of a word that is %d letters long."%(len(secret_word)))
print("-------------")
available_letters= get_available_letters('')
guess_chance=6
warnings_chance=3
guessed=[]
success=False
while guess_chance>0 :
print("You have %d guesses left."%(guess_chance))
print("Available letters: %s"%(available_letters),end="")
my_guess=input("Please guess a letter:")
my_guess=my_guess.lower()
all_lowercase=string.ascii_lowercase
if my_guess=='*':
print('Possible word matches are:')
show_possible_matches(get_guessed_word(secret_word,guessed))
continue
elif my_guess not in all_lowercase or len(my_guess)!=1:
warnings_chance-=1
if warnings_chance<0:
guess_chance-=1
print("Oops! That is not a valid letter. You have no warnings left.")
print("so you lose one guess: %s"%(get_guessed_word(secret_word,guessed)))
print('------------')
else:
print("Oops! That is not a valid letter. You have %d warnings left:%s"%(warnings_chance,get_guessed_word(secret_word,guessed)))
print('------------')
continue
if my_guess not in available_letters:
warnings_chance-=1
if warnings_chance<0:
guess_chance-=1
print("Oops! You've already guessed that letter.You have no warnings left.")
print('so you lose one guess: %s'%(get_guessed_word(secret_word,guessed)))
print('------------')
continue
else:
print("Oops! You've already guessed that letter. You have %d warnings left: %s"%(warnings_chance,get_guessed_word(secret_word,guessed)))
print('------------')
continue
else:
if my_guess not in secret_word:
if guess_chance==1:
guess_chance=0
elif my_guess in vowels:
guess_chance-=2
else:
guess_chance-=1
print("Oops! That letter is not in my word:",(get_guessed_word(secret_word,guessed)))
guessed.append(my_guess)
available_letters= get_available_letters(guessed)
print('------------')
else:
guessed.append(my_guess)
available_letters=get_available_letters(guessed)
print("Good guess: ",get_guessed_word(secret_word,guessed))
print("------------")
if is_word_guessed(secret_word, guessed):
success=True
break
if success==True:
print("Congratulations, you won!")
print('Your total score for this game is: ',(guess_chance*unique_letters(secret_word)))
else:
print('Sorry, you ran out of guesses. The word was',secret_word)
if __name__ == "__main__":
secret_word = choose_word(wordlist)
hangman(secret_word)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)