【发布时间】:2015-07-22 15:43:45
【问题描述】:
我正在尝试使用 Python 创建一个简单的 Hangman 游戏。我遇到了一个我无法解决的问题,希望能收到你们的一些建议。
好的,我将为您提供我的代码示例,在它下面,我将解释我的问题是什么:
# Here is my list of words
words = ['eight', 'nine', 'seven'...]
# Choosing a random word from the list
word = random.choice(words)
# Creating an empty list to store the result
secret_word = []
# Creating a count variable which I will use later to determinate if the player wins
count = 1
for letter in word:
secret_word.append('_')
secret_word[0] = word[0]
user_guess = input("Enter a letter: ")
# Here if the user guesses a letter
# We will place that letter on it's spot in our secret_word
while user_guess:
if user_guess in word:
print("Correct letter.")
# adding 1 to count for every guessed letter
count += 1
# replacing the '_' with the letter
for letter in range(len(word)):
if user_guess == word[letter]:
secret_word[letter] = word[letter]
# here I am checking if the user has won
if count == len(word):
print("You Win!")
我只给了你程序的一部分,因为我认为不需要整个代码。
我的问题在于计数变量。正如你所看到的,每次当用户猜出正确的字母时,我都会在变量中添加 + 1,因此当 count 变量 = len(word) 时,我的小程序就会知道用户赢了。
无论如何,当一个字母在单词中出现两次时,例如单词 SEVEN 的字母 E 是我的计数变量的两倍,因此在这种情况下用户无法获胜。我完全不知道如何解决这个问题,很乐意收到一些提示。
谢谢,请原谅我糟糕的英语和编码技巧
【问题讨论】:
标签: python python-3.x