我正在尝试使用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,所以当计数变量= len(word)时,我的小程序就会知道用户已经赢了。
无论如何,当一个字母在单词中出现两次时,例如,单词7有字母E的两次,我的计数变量仍然只上升了1,所以在这种情况下,用户无法获胜。我完全不知道如何解决这个问题,我很乐意得到一些提示。
谢谢,请原谅我的英语和编码能力不好。
发布于 2015-07-22 15:46:37
只要用正确的字母替换下划线,就可以增加count。这样,count将等于到目前为止单词中正确的字母数。
更清楚的是,当用实际字母替换下划线时,将count += 1移动到if语句中。
我看到的一个问题是,你给了播放器第一个字母,并将count初始化为1。我不知道你为什么要这么做,但是如果第一个字母不止出现一次,它就不会在单词中得到反映,玩家无论如何也要猜测那个字母。
发布于 2015-07-22 15:57:22
将计数移到要替换字母的位置。
while user_guess:
if user_guess in word:
print("Correct letter.")
# replacing the '_' with the letter
for letter in range(len(word)):
if user_guess == word[letter]:
# adding 1 to count for every guessed letter
count += 1
secret_word[letter] = word[letter]
# here I am checking if the user has won
if count == len(word):
print("You Win!")https://stackoverflow.com/questions/31567911
复制相似问题