【发布时间】:2026-01-30 14:05:01
【问题描述】:
我一周前开始学习 Python,我正在努力专注于非常基础的项目。我被困在“刽子手游戏”中
https://www.codementor.io/@ilyaas97/6-python-projects-for-beginners-yn3va03fs
刽子手
这可能是这 6 个小程序中最难的一个 项目。这将类似于猜测数字,除了我们是 猜测这个词。用户需要猜字母,给用户没有 超过 6 次尝试猜错字母。这将意味着你 必须有一个柜台。
到目前为止,我已经编写了这段代码:
import random
name = input("Please enter your name to play Hangman! ")
print("Welcome "+name+" !. Lets play Hangman.")
wrong_attempt = int(input("How many incorrect attempts do you want ? "))
f = open('words.csv',"r")
secret_word = f.readline()
#print(secret_word)
guesses = ''
while wrong_attempt > 0 :
c = 0
letter = input("\nGuess a word : ")
for char in secret_word :
if char == letter :
print(char,end = '')
else :
print('*',end = '')
c += 1
if c == len(secret_word) :
wrong_attempt -= 1
print("Bad Luck. You have ",wrong_attempt," attempts left.")
print("The secret word is ",secret_word)
if wrong_attempt == 0 :
print("You LOSE.")
我现在得到的输出:
Please enter your name to play Hangman! ss Welcome ss !. Lets play Hangman. How many incorrect attempts do you want ? 2
Guess a word : c c******** Guess a word : o
*o******* Guess a word : m
**m****** Guess a word : z
*********Bad Luck. You have 1 attempts left.
Guess a word : d
*********Bad Luck. You have 0 attempts left. You LOSE. The secret word is computer
预期输出:
Please enter your name to play Hangman! ss Welcome ss !. Lets play Hangman. How many incorrect attempts do you want ? 2
Guess a word : c c******** Guess a word : o co******* Guess a word : m com****** Guess a word : z
*********Bad Luck. You have 1 attempts left.
Guess a word : d
*********Bad Luck. You have 0 attempts left. You LOSE. The secret word is computer
在发布问题时,我也是 * 的新手。任何建议将不胜感激。
【问题讨论】:
-
你不想要的输出有什么不同?
-
在您的代码中,您没有考虑到目前为止已正确猜到的字母,只考虑在这一轮中猜到的字母。我建议您创建一个字符串,用
******初始化(具有正确的长度),然后根据猜测来实现。这也可以让你知道玩家是否赢得了比赛。我还建议在attempt_left中重命名你的变量``wrong_attempt`,它的名字是误导性的。
标签: python python-3.x