move shuffle bag to utils
This commit is contained in:
31
scripts/utils/shuffle_bag.gd
Normal file
31
scripts/utils/shuffle_bag.gd
Normal file
@@ -0,0 +1,31 @@
|
||||
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
|
||||
1
scripts/utils/shuffle_bag.gd.uid
Normal file
1
scripts/utils/shuffle_bag.gd.uid
Normal file
@@ -0,0 +1 @@
|
||||
uid://dfg3r3ken1xyd
|
||||
Reference in New Issue
Block a user