【问题标题】:Python While Loop infinitePython While循环无限
【发布时间】:2020-11-30 08:44:01
【问题描述】:

我正在做一个游戏,用户在掷骰子后会得到一个随机数,然后他们玩机器人。游戏应该在 4 轮后退出,但它会继续进行。如果有人知道如何阻止它一遍又一遍地循环,我将不胜感激。

import sys
import random
import time

rounds=0

def user1bot(rounds):
    print("")
    input("Enter A to roll the Dice!")
    userscore=random.randint(1,6)
    print("You Scored: "+str(userscore))
    rounds=rounds+1
    print(rounds)
    userbot(rounds)

def userbot(rounds):
    print("Bot is rolling a dice...")
    time.sleep(3)
    userscorebot=random.randint(1,6)
    print("Bot Scored: "+str(userscorebot))
    rounds=rounds+1
    print(rounds)
    user1bot(rounds)

while rounds<5:
    user1bot(rounds)
    continue
else:
    sys.exit()
    

休息

【问题讨论】:

  • 你的问题是 userbot1 调用了 userbot ,甚至认为你在循环中递增
  • 您正在使用间接递归。您不需要 while 循环。只需在函数中使用 if else 来确定是继续播放还是停止。谁开始比赛?机器人还是用户?
  • @Onyambu 这将是一个优雅的解决方案!我认为这可能是一个有用的答案。

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


【解决方案1】:

正如 Adi 评论的那样,问题在于,一旦您调用 user1bot(),您就永远不会真正返回到您的 while 循环,因此永远不会检查 while 循环的条件,因此您的代码将永远运行。这是我测试过的代码的修改版本 - 它运行六“轮”,但如果您真的希望它在 5 个“轮”后停止,您可以稍微修改一下。

import sys
import random
import time

rounds=0

def user1bot(rounds):
    print("")
    input("Enter A to roll the Dice!")
    userscore=random.randint(1,6)
    print("You Scored: "+str(userscore))
    #rounds=rounds+1
    #print(rounds)
    #userbot(rounds)

def userbot(rounds):
    print("Bot is rolling a dice...")
    time.sleep(3)
    userscorebot=random.randint(1,6)
    print("Bot Scored: "+str(userscorebot))
    #rounds=rounds+1
    #print(rounds)
    #user1bot(rounds)

while rounds<5:
    user1bot(rounds)
    rounds += 1
    print(rounds)
    userbot(rounds)
    rounds += 1
    print(rounds)
    #continue this is unnecessary
else:
    sys.exit()

我这样写是为了符合您在原始代码中增加轮数的方式。但是,我认为每次用户和机器人都完成滚动时将一轮计为更有意义。要以这种方式实现它,我会像这样更改 while 循环:

while rounds<5:
    user1bot(rounds)
    userbot(rounds)
    rounds += 1
    print(rounds)

【讨论】:

    【解决方案2】:

    使用您编写的递归,在尝试减少代码重复的同时,您可以执行以下操作:

    import sys
    import random
    import time
    
    rounds = 0
    
    def score(user):
        userscore = random.randint(1,6)
        print(f"{user} Scored: {userscore}")
        global rounds
        rounds += 1
        print(rounds)
    
    def user1bot():
        if rounds >= 5: 
            return None
        input("Enter A to roll the Dice! ")
        score('You')
        userbot()
    
    def userbot():
        print("Bot is rolling a dice...")
        time.sleep(3)
        score('Bot')
        user1bot()
    
    user1bot()
    

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 2015-05-22
      • 2020-08-18
      • 2012-08-28
      • 2015-06-25
      • 2018-08-30
      • 1970-01-01
      • 2014-03-29
      • 2016-08-27
      相关资源
      最近更新 更多