【问题标题】:While loop looping forever PythonWhile循环永远循环Python
【发布时间】:2014-05-30 10:38:52
【问题描述】:

所以,我正在研究一个掷骰子程序模拟器,通过浏览网络,并从这个论坛上的用户那里获得一些帮助。我能够完成大部分工作。至少,我认为我的游戏逻辑是正确的。

上次我使用它时它正在运行,但我一定是在没有意识到的情况下更改了一些东西,或者因为现在 while 循环一直在运行。在程序中,骰子在没有用户干预的情况下永远滚动。

有人可以看看代码是否有问题?我已经为此工作了好几个小时,却一无所获。

我再也不赌博了! :/

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()

【问题讨论】:

  • 在你的脚本末尾有doubleDiceRoll = input("Roll Again?"),但它不在while doubleDiceRoll == '' 中。没有什么能改变条件,它始终为真

标签: python loops while-loop forever


【解决方案1】:

这个区块:

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

【讨论】:

  • iirc doubleDiceRoll 应该是对用户的提示“你想再玩一次吗?”我必须回头看看他以前的帖子(我已经接受了答案)才能确定。编辑:是的,在他原来的while 循环的末尾是doubleDiceRoll = raw_input ("Roll Again?") 行。看起来整个东西都应该在 while 块内。
  • 好的,无论哪种方式doubleDiceRoll 都需要更新。我更新了我的答案。
  • 感谢比尔和 mhelster。我试图解决这个问题,但是如果我通过将 while 语句更改为 false 来破坏它,代码就会停止......有什么想法吗?
  • @user3462223 你是如何“打破 while 语句”的?
  • 谢谢大家!!!正如你们都指出的那样,我不得不将该语句移到 While 块中。我不知道为什么我昨晚没有抓住它:/
【解决方案2】:

我认为你搞砸了你的缩进:

##Beginning of conditional blocks##

这一行以下的所有内容都在 while 循环之外,但可能应该在其中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多