32 lines
744 B
GDScript
32 lines
744 B
GDScript
class_name ShuffleBag
|
|
|
|
var _max_size: int
|
|
var _indices: PackedInt32Array = []
|
|
var _prev_bag_index: int
|
|
|
|
|
|
## Clears and fills the shuffle bag with integers from 0 to [code]size - 1[/code]
|
|
func fill(size: int) -> void:
|
|
_max_size = size
|
|
_indices.clear()
|
|
_indices.resize(_max_size)
|
|
for i in _max_size:
|
|
_indices[i] = i
|
|
|
|
|
|
## Removes a random number from the shuffle bag and returns it.[br]
|
|
## If the bag becomes empty, it gets refilled.
|
|
func take() -> int:
|
|
var bag_index := randi_range(0, _indices.size() - 1)
|
|
if bag_index == _prev_bag_index:
|
|
bag_index = (bag_index + 1) % _indices.size()
|
|
|
|
var index := _indices[bag_index]
|
|
_indices.remove_at(bag_index)
|
|
if _indices.size() == 0:
|
|
fill(_max_size)
|
|
|
|
_prev_bag_index = index
|
|
|
|
return index
|