【发布时间】:2021-02-01 21:22:58
【问题描述】:
我想创建hangman python 游戏,所以我创建了一个更简单的游戏。游戏的想法是猜测随机生成的单词中的字母。这是我到目前为止所拥有的。我在底部列出了我遇到的问题。
import random
words = ['holiday', 'american', 'restaurant', 'computer', 'highschool', 'programming']
random_word = random.choice(words)
count = 0
while True: #repeatedly asks you to guess the letter in a random word
guess = str(input("Guess a letter: "))
guess = guess.lower()
if guess in random_word: #checks if the letter you input is in the random generated word
print("Yay, its in the word")
else:
count += 1
print("Not in the word, attempts: %d" % count)
if count > 5:
print("You have reached max attempts")
print("Sorry, but hangman died! You lose")
break
else:
continue
我遇到的问题:当用户猜一个字母时,他们可以无限次再猜。我怎样才能让用户不能重复猜同一个字母?
有没有办法确保用户猜不出同一个字母?当有几个相同的字母时,这在实际的刽子手游戏中可能是一个问题。任何帮助/反馈表示赞赏,谢谢!
【问题讨论】:
-
那么你要么需要一个猜测的字母列表,要么创建当前单词的副本并从该副本中删除每个猜测的字母。
-
当你在纸上现场演奏时,你会怎么做?就此而言:当一个真正的刽子手游戏中的某人正确猜出一个字母时,你会做什么(你如何标记纸)你的程序还没有做什么?想想需要做的记录。你永远不能期望编写任何你不能首先用你的母语简单清楚地描述的东西。
-
正如 Martheen 所提到的,您可以有一个像下面这样的列表,并将每个猜测附加到它上面以跟踪已经输入的单词并检查猜测的单词是否已经在该列表中。
guessed_words = [] guessed_words.append(guess)对于每个猜测,您可以检查猜测是否在guessed_words 列表中或不像下面的(在while 循环中):if guess in guessed_words: continue else: print('You already guessed this word.') -
同意@KarlKnechtel。想一想这个问题,并且非常精确。然后考虑解决方案,然后考虑代码。从这个意义上说,这个问题与python有关,就像这句话与英语有关。
标签: python if-statement while-loop counter