Python While循环无限

问题描述

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

if ((value || '').trim()) {
 if(!this.fruits.includes(value.trim())) { 
this.fruits.push(value.trim()); 
}
 }

休息

解决方法

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

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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...