如何解决Python字母猜测游戏
我想创建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
我遇到的问题:用户猜字母时,他们可以无限次地猜字母。我该如何做,以使用户无法反复猜测相同的字母?
有没有一种方法可以确保用户不会猜到相同的字母?当有几个字母相同时,这在实际的子手游戏中可能是个问题。任何帮助/反馈表示赞赏,谢谢!
解决方法
这是一种方法。
import random
words = ['holiday','american','restaurant','computer','highschool','programming']
random_word = random.choice(words)
count = 0
guess_list = []
while True: #repeatedly asks you to guess the letter in a random word
guess = str(input("Guess a letter: "))
guess = guess.lower()
if guess not in guess_list:
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:
print("You have already guessed {}. Try again".format(guess))
print(set(guess_list))
guess_list.append(guess)
示例输出(单词是计算机)
Guess a letter: c
Yay,its in the word
Guess a letter: e
Yay,its in the word
Guess a letter: e
You have already guessed e. Try again
{'e','c'}
Guess a letter: e
You have already guessed e. Try again
{'e','c'}
Guess a letter: w
Not in the word,attempts: 1
Guess a letter: m
Yay,its in the word
Guess a letter: m
You have already guessed m. Try again
{'w','m','e','c'}
Guess a letter:
注意:
- 创建了一个guess_list,其中记录了所有猜测。
- 每次猜测后,字母都会添加到列表中。
- 当用户重复猜测时,将警告他们。我们使用一个集合,以便仅显示猜测列表中的唯一元素。
可以进一步完善代码,但必须完成工作。
,根据单词的不同,如果字母出现多次,您可能需要进行多次猜测。 (这可能不是您的要求。对游戏不熟悉。)
方法
您需要的是一家商店,该商店可以跟踪单词中每个字母的出现次数。
类似的东西:
letterCounts = Counter("hello") # word: 'hello' => {'h': 1,'e': 1,'l': 2,'o': 1}
我在这里使用counter集合。
然后您可以减少猜出的字母的计数
if guesses_letter in list(letterCounts.elements()):
if (letterCounts[guessed_letter] > 0):
letterCounts[guessed_letter] -= 1
else:
# the letter can't be repeated now. do the needful here.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。