Lua:随机:百分比

前端之家收集整理的这篇文章主要介绍了Lua:随机:百分比前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在创建一个游戏,目前必须处理一些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

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

我希望你能理解我对我要完成的事情的不良解释

@R_404_323@

如果没有参数,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

或者将随机结果乘以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

猜你在找的Lua相关文章