一周前,我开始学习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
而且,当涉及到发帖问题时,我对堆叠溢出很陌生。如有任何建议,将不胜感激。
发布于 2019-12-19 03:08:39
我想这就是你的意思:
本质上,我所做的就是创建一个列表,然后用astriks填充项目,然后在char检查时,我弹出n个astriks,并将其替换为字母。
import random
import sys
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 = ''
word = []
for i in secret_word.strip("\n"):
word.append("*")
while wrong_attempt > 0 :
word_str = ''.join([str(elem) for elem in word])
#print(word_str)
c = 0
letter = input("\nGuess a word : ")
for char in secret_word :
if char == letter :
word.pop(c)
word.insert(c,char)
c += 1
else :
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)
c=0
word_str = ''.join([str(elem) for elem in word])
print(word_str)
if word_str == secret_word.strip("\n"):
print("Yeee, you won")
sys.exit()
if wrong_attempt == 0 :
print("You LOSE.")
发布于 2019-12-19 02:47:39
我唯一能看出的区别是预期代码中的这一行:
猜一个词:c*猜一个词:o co*猜测一个词:m*猜一个词:z
而你的是:
猜一个词:c*猜一个词:o
*o*猜一个词:m**m*猜一个词:z
所以,试着在末尾做一个选项卡\t,而不是在这一行中做\n:
letter = input("\nGuess a word : ")
https://stackoverflow.com/questions/59407721
复制