繁体   English   中英

Python While 循环无限

[英]Python While Loop infinite

我正在做一个游戏,用户在掷骰子后会得到一个随机数,然后他们玩机器人。 游戏应该在 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()
    

休息

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

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

正如 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM