我有一个问题:我如何将新游戏放入代码或PlayAgain(y)或(n) 这是我的学校项目。我一直试图找到一个解决方案,但它只会重复“再次播放”或错误的问题。
import random
player1 = input("Enter your real name: ")
player2 = "Computer"
state = random.randint(12,15)
print("The number of sticks is " , state)
while(True):
print(player1)
while(True):
move = int(input("Enter your move: "))
if move in (1,2,3) and move <= state:
break
print("Illegal move")
state = state - move
print("The number of sticks is now " , state)
if state == 0:
print(player1 , "wins")
break
print(player2)
move = random.randint(1,3)
if state in (1,2,3):
move = state
print("My move is " , move)
state = state - move
print("The number of sticks is now " , state)
if state == 0:
print("Computer wins")
break
答案 0 :(得分:0)
您的循环条件始终为True
。这是需要调整的。相反,您只想在用户想要继续时循环
choice = 'y' # so that we run at least once
while choice == 'y':
...
choice = input("Play again? (y/n):")
每次开始新游戏时,您都必须确保重置状态。
由于您的游戏可以结束多个点,因此您需要重构代码或替换break
。例如
if state == 0:
print(player1 , "wins")
choice = input("Play again? (y/n):")
continue
或者更容易将游戏置于内循环中
choice = 'y'
while choice == 'y':
while True:
...
if state == 0:
print(player1, "wins")
break
...
choice = input("Play again? (y/n):")
在那时,如果我是你,我会开始将事情分解为函数