python - 使用 while 和 if-else 循环的简单刽子手游戏无法正确迭代
问题描述
我正在尝试使用简单的 while 循环和 if else 语句来设计一个刽子手游戏。
游戏规则:
1.从单词列表中选择随机单词
2.当单词被选中并要求用户提供他/她的第一个猜测时,会通知用户
3.如果用户猜对了,字母是console,告诉用户还剩多少字母
用户将只能获得 5 条生命来玩游戏。
1.import random 2.import string 3.def hungman(): 4.words = ["dog", "monkey", "key", "money", "honey"] 5.used_letters = [] 6.word = words[random.randrange(len(words))] 7.lives=5 8.while len(word) > 0 and lives > 0: 9.guess = input("Please guess the letter: ") 10.if 'guess' in word: 11.print(guess, " is a correct guess") 12.used_letters.appened(guess) 13.if used_letters.len == word.len: 14.print("Congratulation, You have guessed the correct letter: ",word) 15.else: 16.remaining_letters = word.len - used_letters.len 17.print("You have", remaining_letters, "left") 18.else: 19.lives = lives - 1 20.if lives == 0: 21.print("Sorry! you don't have more lives to continue the game") 22.print("Correct word is: ", word) 23.break 24.else: 25.print("You have", lives , " left") 26.hungman()
程序应该要求用户输入将存储在guess
变量中。如果用户给出的字母是单词字符串的字母之一,则代码提示给定的输入是正确的,并将该字母附加到 used_letters 列表中。否则它会显示错误用户输入的剩余字母的长度。此外,如果用户未能正确猜出字母,他或她也将失去 1 条生命。
但是,根据我在第 8 行的 while 循环之后的代码,控制转到第 8 行。18 虽然我提供了正确的字母作为用户输入。第 10 到 17 行完全被丢弃。我找不到这种性质的原因。
请在这方面帮助我。
谢谢
解决方案
您的代码中有几个问题。你提到的那个是因为第10行的引号。应该是
if guess in word:
在第 12 行你有一个错字
used_letters.append(guess)
要获取列表的长度,您应该使用函数len(),例如
if len(used_letters) == len(word)
最后,如果答案正确,您会遇到退出循环的问题。你应该使用
while len(word) > len(used_letters) and lives > 0:
推荐阅读
- amazon-web-services - 从加拿大区域 (ca-central-1) 发送 AWS SNS 推送通知
- php - 如何将数组数组转换为包含键和值的分组数组?
- python-3.x - 在 python 中填充除美元以外的货币符号的问题
- android - 在活动方法中知道哪个片段正在调用该方法的最佳方法是什么
- scala - 使用 SBT 编译 scala 项目的问题
- python - 新学习者 - 在 python 中使用嵌套 json 时需要帮助
- javascript - 如何禁用软删除用户的登录?
- java - java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory 问题
- jestjs - 是什么导致此 Stencil.js Jest 测试中的“assignedElements 不是函数”?
- google-apps-script - 使用动态定义的表格进行 Google 电子表格查询