2017-05-08 34 views
0

代码有时只运行完美。查看球员总数是否为20的检查似乎有时不运行。我可以运行这个并获得一个胜利者,然后再次运行,它只会持续增加20以上。这是什么原因造成的?有没有更好的方法来考虑建立一个功能?游戏仅有时会检查赢家

这里是我的代码:

from random import randint 

#Setting starting space to 0, getting user names and printing 
#welcome message. 
current_space1 = 0 
current_space2 = 0 
player_1 = raw_input('Enter player 1 name: ') 
player_2 = raw_input('Enter player 2 name: ') 
print('\nWelcome ' + player_1 + ' and ' + player_2) 
print('\nLet\'s Play!\n') 


#making a function to roll dice, update current_space, check 
#to see if current_space == end of game and if not move onto 
#player_2 roll 
def roll_1(): 
    global current_space1 
    print(current_space1) 
    if current_space1 == 20: 
     print('You are the winner ' + player_1 + '!') 
    elif current_space1 != 20: 
     roll_dice = raw_input(player_1 + ' roll dice? y or n: ') 
     if roll_dice == 'y': 
      rolled_dice = (randint(1,6)) 
      print(player_1 + ' ' + 'rolled ' + str(rolled_dice)) 
      current_space1 += rolled_dice 
      print(current_space1) 
      if current_space1 == 20: 
       print('You are the winner ' + player_1 + '!') 
      elif current_space1 != 20: 
       roll_2()     


def roll_2(): 
    global current_space2 
    print(current_space2) 
    if current_space2 == 20: 
     print('You are the winner ' + player_2 + '!') 
    elif current_space2 != 20: 
     roll_dice = raw_input(player_2 + ' roll dice? y or n: ') 
     if roll_dice == 'y': 
      rolled_dice = (randint(1,6)) 
      print(player_2 + ' ' + 'rolled ' + str(rolled_dice)) 
      current_space2 += rolled_dice 
      print(current_space2) 
      if current_space2 == 20: 
       print('You are the winner ' + player_2 + '!') 
      elif current_space2 != 20: 
       roll_1() 


roll_1() 

回答

1

你只检查是否current_space等于20,在那里,因为其中可能情况下它可能是大于20(比如,当用户在19和下辊为6)

更换if current_space1 == 20,与if current_space1 >= 20

执行相同的current_space2

+0

哇做我觉得很愚蠢。大声笑。非常感谢你! – Josh