Lua:随机:百分比

jar*_*rgl 3 lua

我正在创造一个游戏,目前必须处理一些问题math.random.

因为我在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
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何继续,我完全厌恶算法

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

Mar*_*off 7

如果没有参数,该math.random函数将返回[0,1]范围内的数字.

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

因此,只需将您的"机会"转换为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
Run Code Online (Sandbox Code Playgroud)

或者将结果乘以random100,以与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
Run Code Online (Sandbox Code Playgroud)

另一种方法是将上限和下限传递给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
Run Code Online (Sandbox Code Playgroud)


Nor*_*sey 6

我不会在这里弄乱浮点数; 我将使用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
Run Code Online (Sandbox Code Playgroud)