我是 Python 的初学者,我想制作一个 Hangman 游戏来掌握这门语言。
print('You have 5 turns to guess the word.')
turn = int(5)
word = str('secret')
i = int(0)
time.sleep(1)
for i in range(len(word)):
print('_', end='')
time.sleep(0.3)
print()
time.sleep(1)
current = list()
while turn != 0:
if turn > 1:
print('You have', turn, 'guesses.')
else:
print('You have', turn, 'guess.')
guess = input('Enter your guess.')
for i in range(len(word)):
if guess == word[i]:
print(guess, end='')
current[i] = guess
else:
print('_', end='')
current[i] = '_'
print(current)
turn -= 1
在上面的代码中,我在 for 循环中收到“列表索引超出范围”错误。我认为问题是列表长度在开始时没有定义。所以,我添加了这个:
len(current) = len(word)
但是,这没有帮助。然后我尝试在第一回合追加:
if j == 0:
if guess == word[i]:
print(guess, end='')
current.append(guess)
else:
print('_', end='')
current.append('_')
j=1
else:
if guess != word[i]:
print(current[i], end='')
elif current[i] != '_':
print(guess, end='')
current[i] = word[i]
else:
print(guess, end='')
current[i] = '_'
即使这不起作用,现在我迷路了。
您可能未定义current
为空列表,因为您无法在特定索引处分配某些字母,因为它们不存在,请执行
current = ['_'] * len(word)
那么你if/else
是错的,因为它只分配current
了你刚刚给出的字母,所以你不断地把_
之前找到的三个字母放回去。
您可能只有一个if
好字母,要更改下划线,只需current
在for
循环后打印,不需要执行两次(在循环内)
current = ['_'] * len(word)
while turn != 0:
if turn > 1:
print('You have', turn, 'guesses left.')
else:
print('You have', turn, 'guess left.')
guess = input('Enter your guess: ')
for i in range(len(word)):
if guess == word[i]:
current[i] = guess
print("".join(current))
turn -= 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句