我怎么能得到它所以当我运行它时,它会继续滚动骰子,当我进入“滚动”时,它会显示最新的骰子数量。
我是python btw的新手
import random
picked6 = 0
picked5 = 0
picked4 = 0
picked3 = 0
picked2 = 0
picked1 = 0
while 1 == 1:
ra = (random.randint(1, 6))
if ra == 6:
picked6 += 1
if ra == 5:
picked5 += 1
if ra == 4:
picked4 += 1
if ra == 3:
picked3 += 1
if ra == 2:
picked2 += 1
if ra == 1:
picked1 += 1
reroll = input ("Input 'roll' to roll the dice.")
if reroll == "roll":
print ("The Dice has been rolled", (picked6)+(picked5)+(picked4)+(picked3)+(picked2)+(picked1), ("times."))
print ("You rolled 6,", (picked6), "times")
print ("You rolled 5,", (picked5), "times")
print ("You rolled 4,", (picked4), "times")
print ("You rolled 3,", (picked3), "times")
print ("You rolled 2,", (picked2), "times")
print ("You rolled 1,", (picked1), "times")
答案 0 :(得分:1)
如果你想在后台继续工作,即使你在等待输入,最简单的方法就是用线程。
threading
模块有一些很棒的文档,但我不确定这些示例对于之前从未听说过线程的人来说已经足够了,所以让我们简单一点示例
首先,你想把你的滚动循环包装成一个函数:
def roll_dice_forever():
while 1 == 1:
# all the rest of your code up to picked1 += 1
但是,由于picked1
等都是全局变量,pickle1 += 1
除了你首先将它添加到函数的顶部之外,它才能在函数内部起作用:
global picked1, picked2, picked3, picked4, picked5, picked6
现在,要启动在后台运行的该功能,您只需将该功能传递给Thread
对象并start
即可。
但你怎么能戒掉?您需要某种方式来通知工作线程停止工作。或者,更简单地说,您需要能够放弃工作线程,因此操作系统将在主线程退出时将其终止。这在许多情况下都不起作用,但它恰好在这里起作用。您可以使用daemon
属性执行此操作。
还有一个问题。如果主线程试图在后台线程尝试picked1
的同时打印picked1 += 1
怎么办?事实证明,CPython(你几乎可以肯定使用的Python实现)保证这是安全的,但如果你不明白为什么,你就不应该依赖它。相反,您希望使用锁定,以确保一次只能触摸一个线程。
所以,把它们放在一起:
import threading
# everything before while 1 == 1
lock = threading.Lock()
def roll_dice_forever():
global picked1, picked2, picked3, picked4, picked5, picked6
while 1 == 1:
with lock:
# all the rest of your code up to picked1 += 1
worker = threading.Thread(target=roll_dice_forever)
worker.daemon = True
worker.start()
while True:
reroll = input ("Input 'roll' to roll the dice.")
with lock:
# the whole rest of the program
作为旁注,使用列表和循环而不是一堆单独的变量和复制粘贴的代码可以使事情变得更加简单。例如,这取代了您的整个功能:
picked = [0, 0, 0, 0, 0, 0, 0]
def roll_dice_forever():
global picked
while True:
ra = random.randint(1, 6)
with lock:
picked[ra] += 1
这取代了整个输出循环:
while True:
reroll = input("Input 'roll' to roll the dice.")
if reroll == "roll":
print("The Dice has been rolled", sum(picked), "times.")
for i in range(7, 1, -1):
print ("You rolled", i, picked[i], "times")