print("Welcome to hangman. Are you ready to have some fun?")
def play():
import random
List = ["random", "words", "list"]
word = str(random.choice(List))
mistake = 7
alreadySaid = set()
board = "_" * len(word)
print(" ".join(board))
while mistake > 0:
while True:
guess = input("Please guess a letter: ")
if len(guess) <= 1:
break
else:
print("Too long. Enter only one letter.")
if guess in word:
alreadySaid.add(guess)
print("Correct!",guess, " was in the word!")
board = "".join([guess if guess in word else "_" for str in word])
if board == word:
print("Congratulations! You´re correct!!!")
elif guess not in word:
mistake -= 1
print("Wrong!", mistake," mistakes remaining.")
if mistake <= 0:
print("Game Over")
print(" ".join(board))
play()
我试图用python 3制作刽子手,但每当我输入一个正确的字母时,它就会出现一个字母。例如,当我输入r时随机输出r r r r r r当我想要r _ _ _ _ _时。你觉得怎么了?我还有其他问题吗?
答案 0 :(得分:1)
我建议您退后一步,尝试一种不同的,更清洁的方法吗?除此之外,我建议你将隐藏的单词作为一个列表,因为字符串是不可变的,不支持项目分配,这意味着如果用户的猜测是正确的,你就无法揭示该字符(当你的时候可以join()
需要它以字符串形式显示给用户):
import random
word_list = [
'spam',
'eggs',
'foo',
'bar'
]
word = random.choice(word_list)
guess = ['_'] * len(word)
chances = 7
while '_' in guess and chances > 0:
print(' '.join(guess))
char = input('Enter char: ')
if len(char) > 1:
print('Please enter only one char.')
continue
if char not in word:
chances -= 1
if chances == 0:
print('Game over!')
break
else:
print('You have', chances, 'chances left.')
else:
for i, x in enumerate(word):
if x == char:
guess[i] = char
else:
print(''.join(guess))
print('Congratulations!')