【问题标题】:Lua: Random: PercentageLua:随机:百分比
【发布时间】:2021-01-05 11:03:46
【问题描述】:

我正在创建一个游戏,目前必须处理一些math.randomness。

由于我在 Lua 中没有那么强,你怎么看

  • 您能否制定一个算法,使用math.random 并以给定的百分比?

我的意思是这样的函数:

function randomChance( chance )
         -- Magic happens here
         -- Return either 0 or 1 based on the results of math.random
end
randomChance( 50 ) -- Like a 50-50 chance of "winning", should result in something like math.random( 1, 2 ) == 1 (?)
randomChance(20) -- 20% chance to result in a 1
randomChance(0) -- Result always is 0

但是我不知道如何继续,我完全不擅长算法

我希望你能理解我对我想要完成的事情的错误解释

【问题讨论】:

    标签: lua


    【解决方案1】:

    没有参数,math.random 函数返回一个范围为 [0,1) 的数字。

    Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
    > =math.random()
    0.13153778814317
    > =math.random()
    0.75560532219503
    

    因此,只需将您的“机会”转换为 0 到 1 之间的数字:即,

    > function maybe(x) if math.random() < x then print("yes") else print("no") end end
    > maybe(0.5)
    yes
    > maybe(0.5)
    no
    

    或者将 random 的结果乘以 100,以与 0-100 范围内的 int 进行比较:

    > function maybe(x) if 100 * math.random() < x then print(1) else print(0) end  end                                                                             
    > maybe(50)
    0
    > maybe(10)
    0
    > maybe(99)
    1
    

    另一种选择是将上限和下限传递给math.random

    > function maybe(x) if math.random(0,100) < x then print(1) else print(0) end end
    > maybe(0)
    0
    > maybe(100)
    1
    

    【讨论】:

    • 请记住,math.random(0,100) 将返回一个介于 0 到 100 之间的数字,因此 101 个可能的数字中有 1 个,因此您的也许函数中的 x 不再是百分比,而是 101 中的 1机会。
    【解决方案2】:

    我不会在这里乱用浮点数;我会使用带有整数参数和整数结果的math.random。如果您选择 1 到 100 范围内的 100 个数字,您应该得到您想要的百分比:

    function randomChange (percent) -- returns true a given percentage of calls
      assert(percent >= 0 and percent <= 100) -- sanity check
      return percent >= math.random(1, 100)   -- 1 succeeds 1%, 50 succeeds 50%,
                                              -- 100 always succeeds, 0 always fails
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-24
      • 2021-06-22
      • 2021-01-19
      • 2021-12-20
      • 1970-01-01
      • 2018-01-31
      • 2016-02-26
      • 2012-06-24
      相关资源
      最近更新 更多