使用while循环和定义的函数播放bunco

时间:2018-10-09 01:05:55

标签: python function

目前,我目前正在为Bunco编写代码,并定义和调用函数take_turn(playernum)。这应该做的是检查当前玩家的得分掷骰子并将新值返回给玩家。我也在while循环中使用它。问题是每当我执行程序时,外壳上就会显示一个无限循环,我该如何解决?这是我目前的进展。

from random import randint

roundnum=1
player1=0
player2=0
dice1=randint(1,6)
dice2=randint(1,6)
dice3=randint(1,6)
def take_turn(playernumber):
    print (dice1,dice2,dice3)
    while dice1!=6 or dice2!=6 or dice3!=6:
        if dice1==6 or dice2==6 or dice3==6:
            playernumber+=1
        elif dice1==6 and dice2==6:
            playernumber+=5
        elif dice1==6 and dice3==6:
            playernumber+=5
        elif dice2==6 and dice3==6:
            playernumber+=5
        elif dice1==6 and dice2==6 and dice3==6:
            playernumber+=21
        if roundnum==dice1 or roundnum==dice2 or roundnum==dice3:
            playernumber+= roundnum
        if dice1==dice2==dice3:
            continue
        else:
            print (playernumber)
            return 
while player1<=20 and player2<=20:
    take_turn(player1)
    take_turn(player2)
    roundnum+=1
    print ("It is now round", roundnum)
    if player1>=21:
        print("Player1 wins")
    if player2>=21:
        print("Player2 wins")

2 个答案:

答案 0 :(得分:1)

take_turn函数中,

    else:
        print (playernumber)
        return playernumber    # return the value back to the caller

在下面的while循环中,

while player1<=20 and player2<=20:
    player1 = take_turn(player1)    # update the value at each turn
    player2 = take_turn(player2)

对于您来说,player1player2的值永远不会改变,因此while循环永远不会结束。

修改

我猜到了您的逻辑并修改了功能:

def take_turn(playernumber):
    dice1=randint(1,6)
    dice2=randint(1,6)
    dice3=randint(1,6)
    print (dice1,dice2,dice3)
    while dice1==dice2==dice3:
        if dice1==6:
            playernumber += 21
        dice1=randint(1,6)
        dice2=randint(1,6)
        dice3=randint(1,6)

    if dice1==6 and dice2==6:
        playernumber+=5
    elif dice1==6 and dice3==6:
        playernumber+=5
    elif dice2==6 and dice3==6:
        playernumber+=5
    elif dice1==6 or dice2==6 or dice3==6:
        playernumber+=1
    if roundnum==dice1 or roundnum==dice2 or roundnum==dice3:
        playernumber+= roundnum
    print (playernumber)
    return playernumber

答案 1 :(得分:1)

playernumber函数内更改take_turn的值时,这只是在函数作用域中定义的变量名。您必须将新分数返回到调用范围。

在调用范围中,必须将返回值分配给变量名。

def take_turn(playernumber):
    ...
    return playernumber

player1 = take_turn(player1)
player2 = take_turn(player2)