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。你觉得哪里不对?还有其他问题吗?
请您参考如下方法:
我是否可以建议您退后一步,尝试一种不同的、更简洁的方法?除此之外,我建议您将隐藏的单词保留为一个列表,因为字符串是不可变的并且不支持项目分配,这意味着如果用户的猜测是正确的,您将无法显示字符(然后您可以 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!')
