2016-09-19 62 views
-1

我写了下面的python脚本来实现我的版本的游戏NIMS /石的Python脚本循环

def nims_stones(pile, max_stones): 

    while pile != 0: 

     move = 0 

     while move < 1 or move > max_stones: 
      move = int(raw_input("Player 1 How Many Stones")) 
     pile -= move 

     if pile == 0: 
      print "Player 1 wins" 

     else: 
      print "There are %s stones left." %(pile) 



     move = 0 

     while move < 1 or move > max_stones: 
      move = int(raw_input("Player 2 How Many Stones")) 
     pile -= move 

     if pile == 0: 
      print "Player 2 wins" 

     else: 
      print "There are %s stones left." %(pile) 

    print "Game Over" 

当我调用该函数nims_stones(10,5)这似乎工作,但球员的一个或播放后两个胜,它不退出循环它不打印“游戏结束”它只是要求下一步

我不知道为什么它不会在玩家获胜后退出循环。任何帮助将不胜感激。

+0

我对玩家2不知道,但是在打印玩家1获胜后,你不断地改变'堆'。当任何一个玩家获胜时,只要“休息”,并使你的条件成为“真正的”。它会更清晰。 –

+0

我试过它没有工作,它只是跳转到游戏结束 – user2919794

回答

2

当玩家1清空桩时,您应该停止循环。由于您对第二个玩家的代码几乎相同,因此请考虑重新使用代码。然后,你还必须空堆检查在循环的末尾:

def nims_stones(pile, max_stones): 
    player = 2 
    while pile != 0: 
     player = 3 - player 
     move = 0 
     while move < 1 or move > max_stones or move > pile: 
      move = int(raw_input("Player %i. How Many Stones" % (player))) 
     pile -= move 
     print ("There are %s stones left." %(pile)) 
    print ("Player %i wins" % (player)) 
    print ("Game Over") 

NB /我还添加了状态move > pile避免玩家花费比更多的可用。

0

每个玩家获胜后添加一个break语句将解决您的问题。您应该考虑在桩到达负值时添加逻辑。

while pile != 0: 

    move = 0 

    while move < 1 or move > max_stones: 
     move = int(raw_input("Player 1 How Many Stones")) 
    pile -= move 

    if pile == 0: 
     print "Player 1 wins" 
     break 
    else: 
     print "There are %s stones left." %(pile) 



    move = 0 

    while move < 1 or move > max_stones: 
     move = int(raw_input("Player 2 How Many Stones")) 
    pile -= move 

    if pile == 0: 
     print "Player 2 wins" 
     break 
    else: 
     print "There are %s stones left." %(pile) 

print "Game Over"