[英]Python NIM game: how do i add new game (y) or (n)
I have a question: How do i put New Game in code or PlayAgain (y) or (n) This is for my school project. 我有一个问题:如何将新游戏放入代码或PlayAgain(y)或(n),这是针对我的学校项目的。 I have been trying to find myself a solution but it will only repeat question "play again" or error.
我一直在寻找一种解决方案,但只会重复“再次播放”或错误的问题。
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
Your loop condition is always True
. 您的循环条件始终为
True
。 This is what needs adjusting. 这是需要调整的。 Instead you only want to loop while the user wants to continue
相反,您只想在用户想要继续时循环播放
choice = 'y' # so that we run at least once
while choice == 'y':
...
choice = input("Play again? (y/n):")
You will have to make sure to reset the state each time you begin a new game. 每次开始新游戏时,您都必须确保重置状态。
Since you have multiple points at which your game can end, you'll need to either refactor your code, or replace the break
s. 由于您可以在多个点结束游戏,因此您需要重构代码或替换
break
。 For example 例如
if state == 0:
print(player1 , "wins")
choice = input("Play again? (y/n):")
continue
Or what may be easier is to put the game into an inner loop 或者更简单的方法是将游戏置于内部循环中
choice = 'y'
while choice == 'y':
while True:
...
if state == 0:
print(player1, "wins")
break
...
choice = input("Play again? (y/n):")
At that point I'd start factoring things into functions if I were you 到那时,如果我是你,我将开始将事情分解为函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.