gpt4 book ai didi

random - Lua随机数?

转载 作者:行者123 更新时间:2023-12-03 09:25:42 26 4
gpt4 key购买 nike

如何生成每次运行脚本时都不同的随机整数?我目前正在做一个“不可能的测验”,它使用随机数从表格中选择一个问题。每次我运行脚本时,问题的顺序都是相同的。我还使用 table.remove() 在提出问题后从表中删除问题。然而,一旦被删除,它就会继续问同样的问题,因为它没有选择一个新的随机数(我正在使用 math.random(1, #Questions) 从“问题”表中选择一个随机问题.)

    local lives = 3

Questions = {
{"What is the magic word?", "lotion"},
{"Does anyone love you?", "no"},
{"How many fingers do you have?", "10"},
{"What is 1 + 1?", "window"}
}

function lookForAnswer(ans)
table.remove(Questions[number])
local input = io.read() tostring(input)
if input:lower() == ans then
return true
end
lives = lives - 1
if lives <= 0 then
exit()
end
return false
end

for i = 1, #Questions do
number = math.random(1, #Questions)
local q = Questions[number][1]
local a = Questions[number][2]
print(q)
if lookForAnswer(a) then
print("Correct!\n")
else
print("WRONG! Lives: " .. lives .. "\n")
end
end

io.read()

最佳答案

您需要在调用 math.random() 之前调用 math.randomseed() 来为随机数生成器提供种子。使用 os.time() 作为种子值 (math.randomseed(os.time())) 是很常见的。

需要注意的是,math.random() 是确定性的,因此熵必须来自种子值。如果将相同的值传递给种子,您将获得相同的值 math.random()。由于 os.time() 的分辨率只有秒,这意味着如果您在给定的秒内多次调用该命令,您将得到相同的值。如果您愿意,您可以尝试使用更多熵源进行播种 (/dev/random)。

澄清一下,如果它是真正随机的,您不能保证每次值都会不同。您所能做的就是确保获得相同值的概率足够低。

关于random - Lua随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21806787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com