我正在研究一个使用.txt文件wordlist的hangman的Python版本。出于某种原因,在初始游戏之后的游戏中,脚本不会显示某些字母。其他一切都以我想要的方式运作,或多或少。
我的代码:
import random
wordlist = open("wordlist.txt").read().split()
word = random.choice(wordlist)
strikes = 0
hidden_letters = []
alphabet = "abcdefghijklmnopqrstuvwxyz"
guesses = []
def new_word():
global word
global guesses
word = random.choice(wordlist)
for letter in set(word):
if letter in alphabet:
hidden_letters.append(letter)
guesses = []
def current_progress():
for letter in word:
if letter in hidden_letters:
print '_',
elif letter == ' ':
print ' ',
else:
print letter,
print "\n"
def play_again():
global strikes
print "Would you like to play again?"
answer = raw_input("y/n: ")
if answer == "y":
strikes = 0
main()
elif answer == "n": exit(0)
else:
print "That's not a valid answer."
play_again()
def letter_in_word(x):
global strikes
global hidden_letters
if x in word:
hidden_letters.remove(x)
print "That letter is in the word."
current_progress()
if hidden_letters == []:
print "You win!"
play_again()
else:
print "You have %d strike(s)." % strikes
elif not x in word:
print "That letter is not in the word."
current_progress()
strikes = strikes + 1
print "You have %d strike(s)." % strikes
def main():
new_word()
current_progress()
global strikes
while strikes < 6 and not hidden_letters == []:
print "Guess a letter. \n Letters that have been already guessed are:", guesses
guess = raw_input("> ")
if guess in alphabet and len(guess) == 1:
if not guess in guesses:
guesses.append(guess)
letter_in_word(guess)
else:
print "You've already guessed that letter. Pick another."
current_progress()
print "You have %d strikes." % strikes
else:
print "Sorry, that's not a valid guess."
current_progress()
print "You have %d strikes." % strikes
if strikes == 6:
print "Oop! You lose."
print "The answer was:", word
play_again()
print "Welcome to Hangman!"
print "Six strikes and you lose."
print "----------"
main()
答案 0 :(得分:2)
你的问题:当玩家猜到当前单词和前一个单词中存在的一个字母,但在前一个单词中没有猜到(该玩家输掉了那个游戏)时,该字母仍然在{{1} } list因为hidden_letters
只删除该字母的第一个实例。换句话说,在某些执行过程中,您的列表包含两个相同的字母,这违反了代码的隐含要求。您可以在添加新单词的字母之前在remove(x)
函数中添加hidden_letters = []
来解决此问题。
来自Python tutorial(强调我的):
new_word()
从值为 x 的列表中删除第一项。这是一个错误 如果没有这样的项目。
答案 1 :(得分:2)
或者,我认为你可以添加声明
del hidden_letters[:]
在new_word()
的开头。它会清除hidden_letters
列表。