模拟掷骰子游戏

时间:2013-05-22 19:16:35

标签: python python-3.x while-loop

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

游戏规则: 游戏开始时玩家投掷一对骰子。如果玩家总共掷出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

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

3 个答案:

答案 0 :(得分:5)

由于这一行,你永远不会进入while循环:

newRoll = craps()   

就这一点而言。因此它只会执行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

答案 1 :(得分:3)

  

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

def rollDice(): # define a function to generate new roll
    return random.randrange(1,7) + random.randrange(1,7)

def craps():
    firstRoll= rollDice()
    if firstRoll in (7,11): 
        return 1 # initial winning condition
    if firstRoll in (2,3,12):
        return 0 #initial losing condition

    while True:
        newRoll = rollDice()
        if newRoll == firstRoll: 
            return 1 #secondary winning condition
        if newRoll == 7: 
            return 0 #secondary losing condition

然后你可以在想要播放一些掷骰子时调用craps(),如果它赢了或输了,它的输出将是1或0。

答案 2 :(得分:1)

你以递归方式调用craps,但由于函数返回1或0,因此无效。您需要将实际骰子添加到while循环中。

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
else:
    return  0
相关问题