我制作了一个带有for-in loop
的简单骰子滚轴,该骰子滚子需要两张input
,骰子数量和骰子侧面数。卷成卷后,结果将打印到屏幕上。
在完成初始滚动后,我希望代码以新的inputs
重新开始,而不会生成exit code 0
。
##Original design obviously does not loop
from random import randint
import time
dice = int(input("\nHow many dice?\n "))
sides = int(input("How many sides?\n "))
def roll():
for quantity in range(dice):
time.sleep(.5)
print(randint(1, sides))
roll()
我将input
变量从global scope
移到了local scope
,因此每次重复都可以更新它们。通过调用function
结束function
时,我取得了一些成功。我能够无休止地loop
进行该过程而不会生成exit code 0
,但是似乎没有注册1
以外的任何骰子。这样我一次只能掷一个骰子。
##Design 2 does not generate any exit codes and continues to loop
##endlessly but will not register more than 1 dice
from random import randint
import time
def roll():
dice = int(input("\nHow many dice?\n "))
sides = int(input("How many sides?\n "))
for quantity in range(dice):
time.sleep(.5)
print(randint(1, sides))
roll()
roll()
我更改了function
,以使其不会以calling
本身结尾。相反,我创建了一个新函数,只调用第一个函数。我将冗余功能放在第一个之后,并且已经能够成功实现我的目标,可以任意滚动任意数量的侧面骰子...两次。经过两次迭代/循环后,会生成一个exit code 0
##Current design will register all input data correctly
##but only loops 2 times before generating an `exit code 0`
from random import randint
import time
def roll():
dice = int(input("\nHow many dice?\n "))
sides = int(input("How many sides?\n "))
for quantity in range(dice):
time.sleep(.5)
print(randint(1, sides))
def roll_again():
roll()
roll()
roll_again()
有人知道我在做什么错吗?
答案 0 :(得分:2)
您需要将游戏逻辑放在while循环内;完成游戏后,输入零骰子退出。
from random import randint
import time
def roll():
for quantity in range(dice):
time.sleep(.5)
print(randint(1, sides))
while True:
dice = int(input("\nHow many dice? (zero to stop)\n "))
if dice == 0:
break
sides = int(input("How many sides?\n "))
roll()
答案 1 :(得分:0)
您可以使用while
循环
from random import randint
import time
def roll():
dice = int(input("\nHow many dice?\n "))
sides = int(input("How many sides?\n "))
for quantity in range(dice):
time.sleep(.5)
print(randint(1, sides))
while True:
roll()
这将永远运行脚本,所有滚动后都会重新输入。
要退出,请按Ctrl+C
背景:while
循环将在开始时检查条件,并在满足条件时运行(True
)。在这种情况下,条件始终设置为True
,因此它会永远得到满足;-)