godot-start/zfoo/util/RandomUtils.gd

44 lines
1.2 KiB
GDScript
Raw Normal View History

2021-09-13 15:31:35 +00:00
extends Object
2021-10-03 09:23:08 +00:00
const NumberUtils = preload("res://zfoo/util/NumberUtils.gd")
const StringUtils = preload("res://zfoo/util/StringUtils.gd")
2021-09-13 15:31:35 +00:00
const random = [false, null]
2021-09-13 15:31:35 +00:00
# 单例模式
static func getRandom() -> RandomNumberGenerator:
if random[0]:
return random[1]
var randomGenerator = RandomNumberGenerator.new()
randomGenerator.randomize()
random[1] = randomGenerator
return randomGenerator
static func randomBoolean() -> bool:
return 1 == getRandom().randi_range(0, 2)
# 获得随机数[-2^32, 2^32)
static func randomInt() -> int:
return randomIntRange(NumberUtils.MIN_INT, NumberUtils.MAX_INT)
# 获得指定范围内的随机数 [0,limit)
static func randomIntLimit(limit: int) -> int:
return randomIntRange(0, limit)
# 获得随机数[-2^32, 2^32)
static func randomIntRange(from: int, to: int) -> int:
if from < NumberUtils.MIN_INT:
push_error(StringUtils.format("from [{}] shoud be >= [{}]", [from, NumberUtils.MIN_INT]))
return 0
if to > NumberUtils.MAX_INT:
push_error(StringUtils.format("to [{}] should be <= [{}]", [from, NumberUtils.MAX_INT]))
return 0
2021-09-13 15:31:35 +00:00
return getRandom().randi_range(from, to - 1)
2021-10-03 01:02:45 +00:00
static func randomEle(array: Array):
return array[randomIntLimit(array.size())]