[英]Python simple madlibs generator random.randint in while loops
[英]Python random.randint stops randomizing after a few loops
我正在运行一个 python 脚本,它将在板上显示消息。 我创建的其中一个子程序应该从一个小文本文件中随机抓取一行,并显示该行。 它主要工作,除了循环几次后,它卡在同一个数字上,只是一遍又一遍地显示相同的东西。
我在 Raspbian 的 Raspberry Pi 上的 Python 2.7 中运行它。 我正在使用这个 github 作为项目的基础,并在其中添加了我自己的行: https://github.com/CalebKussmaul/Stranger-Things-Integrated这是万圣节展示的一部分,它将是 Stranger Things-themed ,因此预加载的消息对节目有参考。 前几天我注意到了这个问题,并且一直在互联网上倾注试图找出问题所在。 我尝试过使用不同的方法来选择随机数,包括本网站上一些类似(但不同)线程中的一些方法。 它们都产生完全相同的问题。
下面是我创建的子程序:
def preloaded_messages():
print "Preloaded Messages thread is loaded."
global displaying
while True:
if not displaying:
with open('preloaded_messages.txt') as f:
lines = len(f.readlines())
rgn = random.randint(1,lines)
msg = linecache.getline('preloaded_messages.txt', rgn)
print "rng: ", rgn
print "total lines: ", lines
print "line: ", msg
print "displaying from preloaded_messages.txt: ", msg
display(msg)
time.sleep(10)
这是我的 preloaded_messages.txt 文件:
help me
im trapped in the upside down
leggo my eggo
friends dont lie
run /!
hopper is alive
rip barb
demogorgon is coming /!
mouthbreather
当我运行它时,我的 output 是这样的:
rng: 6
total lines: 9
line: hopper is alive
rng: 2
total lines: 9
line: im trapped in the upside down
rng: 9
total lines: 9
line: mouthbreather
...
rng: 9
total lines: 9
line: mouthbreather
前几次总是随机的(它成功随机化的次数各不相同),但是当它到达 9 时,只要我让它运行,它就会一直呆在那里。 我不知道为什么它在前几次有效,但一旦达到 9 次就不行了。
编辑:有趣的是,当我一直在写这篇文章时,我还尝试在最后添加一个空行,虽然它看起来会再次被卡住,因为它连续三次这样做,然后它终于移动了给别人。 我不确定这会如何改变事情。 理想情况下,我宁愿没有空白行,因为它会占用时间,什么都不显示。 所以解决这个问题会很好。 有人有想法么?
这似乎对我有用。 请注意,我正在播种 RNG。
import time
import random
from datetime import datetime
def preloaded_messages():
print("Preloaded Messages thread is loaded.")
displaying = False
while True:
if not displaying:
with open('preloaded_messages.txt') as f:
random.seed(datetime.utcnow())
text = f.read().splitlines()
msg = random.choice(text)
print("line: ", msg)
# print("displaying from preloaded_messages.txt: ", msg)
time.sleep(10)
if __name__ == "__main__":
preloaded_messages()
它正在重新播种随机生成器。 参见https://github.com/CalebKussmaul/Stranger-Things-Integrated中的第 49 行陌生人.py: random.seed(i)
。
color_of
的color_应该写成:
def color_of(i):
"""
This function generates a color based on the index of an LED. This will always return the same color for a given
index. This allows the lights to function more like normal christmas lights where the color of one bulb wont change.
:param i: index of LED to get color of
:return: a pseudorandom color based on the index of the light
"""
_random = random.Random(i)
rgb = colorsys.hsv_to_rgb(_random.random(), 1, 1)
return int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)
使用给定的种子创建自己的Random
实例,而不是在random
模块中重新播种作为 singleton 的Random
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.