模拟掷骰子游戏

Sna*_*rre 3 python while-loop python-3.x

我正在尝试实现一个craps()不带参数的函数,模拟一个掷骰子游戏,1如果玩家赢了以及0玩家输了则返回.

游戏规则:游戏开始时玩家投掷一对骰子.如果玩家总共掷出7或11,则玩家获胜.如果玩家总共掷出2,3或12,则玩家输了.对于所有其他掷骰价值,游戏继续进行,直到玩家滚动初始值agaian(在这种情况下玩家获胜)或7(玩家输掉).

我想我越来越近了,但我还没有,我不认为我的while循环工作正常.这是我到目前为止的代码:

def craps():
    dice = random.randrange(1,7) + random.randrange(1,7)
    if dice in (7,11):
        return 1
    if dice in (2,3,12):
        return 0
    newRoll = craps()
    while newRoll not in (7,dice):
        if newRoll == dice:
            return 1
        if newRoll == 7:
            return  0
Run Code Online (Sandbox Code Playgroud)

如何修复while循环?我真的找不到它的问题,但我知道这是错误的或不完整的.

ecl*_*ne6 5

你永远不会因为这一行而进入while循环:

newRoll = craps()   
Run Code Online (Sandbox Code Playgroud)

就这一点而言.因此它只会执行craps()函数的顶部.您需要使用之前的相同滚动码.我想你想要的东西:

newRoll = random.randrange(1,7) + random.randrange(1,7)
while newRoll not in (7,dice):
    newRoll = random.randrange(1,7) + random.randrange(1,7)        

if newRoll == dice:
    return 1
if newRoll == 7:
    return  0
Run Code Online (Sandbox Code Playgroud)