游戏有时只会检查获胜者

时间:2017-05-08 05:24:29

标签: python

代码有时只运行完美。检查玩家总数是否= 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 个答案:

答案 0 :(得分:1)

您只是检查if current_space1 == 20是否等于20,其中可能存在大于20的情况(比如,当用户为19且下一次滚动为6时)

if current_space1 >= 20替换为current_space2

save!

执行相同的操作