Python中的while循环无限循环

0 投票
2 回答
786 浏览
提问于 2025-04-18 02:52

我在网上找资料,结合论坛上的一些用户帮助,正在做一个掷骰子游戏的模拟程序。大部分功能我都完成了。至少,我觉得我对游戏的逻辑理解是正确的。

上次用的时候程序是可以运行的,但我可能不小心改了什么,导致现在这个循环一直在运行。程序里的骰子一直在转,完全不需要用户操作。

有没有人能帮我看看代码,看看是不是哪里出问题了?我已经花了好几个小时,但一点进展都没有。

我再也不想赌博了! :/

from Dice import PairOfDice
print("Now Let's play with two dice!")
#
def MainDouble():
    bdice = PairOfDice()
    doubleDiceRoll = ''
    global myPoint #declare global variable
    input("Press Enter to Roll the Dice once")

    while doubleDiceRoll == '': #Roll the dice (both die objects)
        bdice.toss()
        print ('The first die reads.. ' + str(bdice.getValue1()) + '\n')
        print ('The second die reads.. ' + str(bdice.getValue2()) + '\n')

        Val = bdice.getTotal()

##Beginning of conditional blocks##
    if Val == 7 or Val == 11:
        gamestatus = "WON"


    elif Val == 2 or Val == 3 or Val == 12:
        gamestatus = "LOST"

    if Val != 7 and bdice.getTotal() != 11 and Val != 2 and Val != 3 and Val != 12:
        gamestatus = "CONTINUE"
            #
        myPoint = Val
        print("The Point is now " + myPoint + "/n") #display the user's point value
        global pSum 
        pSum = 0


    #The point

    while gamestatus == "CONTINUE": #Checking the point
            global point   
            point = myPoint   
            pSum = MainDouble()

            if pSum == myPoint:
             gamestatus == "WON"
            elif pSum == 7:
             gamestatus = "LOST"
            if gamestatus == "WON":
             print("Winner!")
            else:
             print("Sorry, Seven out!")
            print ("Roll Again?")

    doubleDiceRoll = input("Roll Again?")  

MainDouble()

2 个回答

2

我觉得你在这行之后的缩进搞错了:

##条件块的开始##

这行下面的所有内容都在 while 循环之外,但其实应该放在里面。

5

这个代码块:

while doubleDiceRoll == '': #Roll the dice (both die objects)
    bdice.toss()
    print ('The first die reads.. ' + str(bdice.getValue1()) + '\n')
    print ('The second die reads.. ' + str(bdice.getValue2()) + '\n')

    Val = bdice.getTotal()

doubleDiceRoll 这个变量从来没有被改变过,所以这个循环会一直运行下去,永远不会停止。在这个代码块的最后(但仍然在里面!),你应该做一些类似于下面的事情:

    doubleDiceRoll = raw_input("Roll Again?") #Edit thanks to @Adam Smith

撰写回答