我正在设置一个基本的子手游戏,并试图让该程序在游戏结束时循环回到开头。
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
print("Play again? (y/n)")
答案 0 :(得分:3)
将您的游戏包装到一个函数中,并将其放入while循环中。 玩游戏功能后,将要求他们再次玩。如果他们回答“ y”以外的任何内容,则循环会中断。
while True:
# play_game()
if input("Play again?") != 'y':
break
print("Thanks for playing!")
答案 1 :(得分:0)
您可以使用用户输入和while循环
play_again = "Y"
while play_again == "Y" or play_again == "y":
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
play_again = input("Play again? (Y/N)")
或者简而言之,只是放入一个函数中:
play_again = "Y"
while play_again == "Y" or play_again == "y":
game()
play_again = input("Play again? (Y/N)")
答案 2 :(得分:0)
您可以将所有内容放到一个函数中,然后像这样循环返回:
def start():
replay = True
while (replay):
game_started()
inp = input("Play again? Y/n ")
if inp == 'n' or inp == 'N':
replay = False
def game_started():
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
break
start()
编辑:
您检查信件是否为猜测也有缺陷:
如果您猜到“ abcdefghijklmnopqrstuvwxyz”,那么您总会赢。
我建议在将输入追加到guesses
之前检查输入的长度。
另外,要将它们全部打印到一行,可以使用“ print(char,end ='')”(和分别使用“ print('_',end ='')”)。只需确保在循环之后打印换行符即可结束该行。
答案 3 :(得分:-1)
嘿,这是我想出的朋友,希望对您有所帮助!可以使用设置为布尔值的“运行”变量来代替使用轮流来控制while循环,您可以将输入语句用于重播功能来控制何时要退出(False)或继续执行循环(真正)。
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
running = True
while running:
failed = 0
for char in word:
if char in guesses:
print(char),
else:
print("_"),
failed += 1
if failed <= 0:
print("You won")
x = input("Play Again? (y/n) \n")
if x == "y":
turns = 10
else:
running = False
guess = input("Guess a character: \n")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
z = input("Play Again? (y/n) \n")
if z == "y":
turns = 10
else:
running = False