2016-09-30 140 views
0

我有一个问题:如何将新游戏放入代码或PlayAgain(y)或(n) 这是用于我的学校项目。我一直在努力寻找自己的解决方案,但它只会重复问题“再次玩”或错误。Python NIM游戏:如何添加新游戏(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

您的环路条件始终为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):") 

在这一点上,如果我是你

+0

你能我开始融通东西进入功能请在第一个例子中,我必须将丢失的代码 –

+0

放在哪里,'......'将成为您的整个游戏。在第二个例子中,你必须自己解决,我们不在这里为你做功课。 –

+0

好的,谢谢 –