Skip to content

Instantly share code, notes, and snippets.

@noidexe
Created December 28, 2017 14:08
Show Gist options
  • Save noidexe/5da59d57c89984b45c90b4e4ccb671b3 to your computer and use it in GitHub Desktop.
Save noidexe/5da59d57c89984b45c90b4e4ccb671b3 to your computer and use it in GitHub Desktop.
ShuffleBag implementation in gdscript
#You can add this to any singleton where you have helper classes and functions
class ShuffleBag:
var _shuffled_list
var _current_pos = -1
func _init(array_from):
var _unshuffled = array_from.duplicate()
var _shuffled = []
var _current_pos
# Pick a random element from the unshuffled list
# Add it to the shuffled list
# Repeat until the unshuffled list is empty
while _unshuffled.size() > 0:
_current_pos = randi() % _unshuffled.size()
_shuffled.append(_unshuffled[_current_pos])
_unshuffled.remove(_current_pos)
_shuffled_list = _shuffled
func next():
# If we haven't finished traversing the list
if _current_pos >= 0:
# Pick a random item we haven't picked before
var random_pos = randi() % (_current_pos + 1)
var value = _shuffled_list[random_pos]
# Swap it with the value in our current position
_shuffled_list[random_pos] = _shuffled_list[_current_pos]
_shuffled_list[_current_pos] = value
# Decrement the counter
_current_pos -= 1
# Return the random item we picked
return value
else:
# we've finished traversing the list
# so we reset _currentPos, but we
# still need to return a value so
# we call ourselves.
_current_pos = _shuffled_list.size() - 1
return next()
func size():
return _shuffled_list.size()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment