我认为问题出在我的第二个while循环中。按Enter键运行游戏后,它会一直打印_。我不确定如何不满足条件或在哪里添加休息时间。我已经尝试更改我的其他缩进:当我执行循环时根本不会运行。
import random
#make a list of words
words = [
'apple',
'banana',
'orange',
'coconut',
'strawberry',
'lime',
'grapefruit',
'lemon',
'kiwi',
'blueberry',
'melon'
]
while True:
start = input("Press enter/return to start, or Q to quit")
if start.lower() == 'q':
break
#pick rand word
secret_word = random.choice(words)
bad_guesses = []
good_guesses = []
while len(bad_guesses) < 7 and len(good_guesses) != len(list(secret_word)):
#draw guessed letters, spaces, and strikes
for letter in secret_word:
if letter in good_guesses:
print(letter, end='')
else:
print('_', end='')
print('')
print('Strikes: {}/7'.format(len(bad_guesses)))
print('')
#take guess
guess = input("Guess a letter: ").lower()
if len(guess) != 1:
print("You can only guess a single letter!")
continue
elif guess in bad_guesses or guess in good_guesses:
print("You already guessed that letter!")
continue
elif not guess.isalpha():
print("You can only guess letters!")
continue
if guess in secret_word:
good_guesses.append(guess)
if len(good_guesses) == len(list(secret_word)):
print("You Win! The word was {}".format(secret_word))
break
else:
bad_guesses.append(guess)
else:
print("You didn't get it! My secret word was {}".format(secret_word))
答案 0 :(得分:1)
在具有此条件的区块中:
while len(bad_guesses) < 7 and len(good_guesses) != len(list(secret_word)):
bad_guesses
,good_guesses
或secret_word
变量没有任何变化。这意味着你将永远重试它。
在这种情况下,您可能想要if
而不是while
。
答案 1 :(得分:1)
这是您的代码的工作版本。刚刚纠正了必要的部分,但毫无疑问你应该考虑编写一个更干净,更好的缩进代码。
import random
# make a list of words
words = [
'apple',
'banana',
'orange',
'coconut',
'strawberry',
'lime',
'grapefruit',
'lemon',
'kiwi',
'blueberry',
'melon'
]
while True:
start = input("Press enter/return to start, or Q to quit")
if start.lower() == 'q':
break
bad_guesses = []
good_guesses = []
# pick rand word
secret_word = random.choice(words)
while len(bad_guesses) < 7 and len(good_guesses) != len(list(secret_word)):
# draw guessed letters, spaces, and strikes
for letter in secret_word:
if letter in good_guesses:
print(letter, end='')
else:
print('_', end='')
print('\Bad guesses: {}/7\n'.format(len(bad_guesses)))
# take guess
guess = input("Guess a letter: ").lower()
if len(guess) != 1:
print("You can only guess a single letter!")
continue
elif guess in bad_guesses or guess in good_guesses:
print("You already guessed that letter!")
continue
elif not guess.isalpha():
print("You can only guess letters!")
continue
if guess in secret_word:
good_guesses.append(guess)
else:
bad_guesses.append(guess)
if len(good_guesses) == len(set(secret_word)):
print("You Win! The word was {}".format(secret_word))
break
print("You didn't get it! My secret word was {}".format(secret_word))