← Pixel Dreamer Studio

Play random sounds and events without obvious repeats

Shuffle the list, play through it, and reshuffle when it runs out, never starting with the last one played.

Picking with randi() % size every time is fair over the long run, but with 4 clips the same one comes twice in a row about a quarter of the time, and players notice. In our Godot 4.7 test it repeated back to back 239 times in 1,000 plays, and one clip went 31 plays without being heard. A shuffle bag plays every clip once per round: 0 repeats, and never more than 6 plays between the same clip.

The code

Fill items with your AudioStreams, flicker patterns or event names and call next() whenever you need one. Seed rng to get the same order every run. Use one bag per kind of thing, so scare sounds and ambient sounds do not share a bag.

extends Node
## Random picks that never repeat back to back and use every item before any comes again:
## scare sounds, light flicker patterns, ambient events. Call next() each time you need one.

var items: Array = []
var rng := RandomNumberGenerator.new()
var _bag: Array = []
var _last = null


func next() -> Variant:
	if items.is_empty():
		return null
	if _bag.is_empty():
		_bag = items.duplicate()
		for i in range(_bag.size() - 1, 0, -1):  # shuffle with our own rng, so a seed repeats the order
			var j := rng.randi_range(0, i)
			var t = _bag[i]
			_bag[i] = _bag[j]
			_bag[j] = t
		if _bag.size() > 1 and _bag.back() == _last:  # the new bag must not start with the last one played
			var first = _bag[0]
			_bag[0] = _bag[-1]
			_bag[-1] = first
	_last = _bag.pop_back()
	return _last

What we measured

4 clips, 1,000 plays, with a fixed seed. Two runs with the same numbers.

Why it happens

Each randi() pick does not know what came before, so with 4 clips a repeat has a 1 in 4 chance every time. A shuffle bag deals out every item once before reshuffling, and the swap at the start of a new round stops the last clip of one round from opening the next.

What to change

Weighted chances: weighted random with rand_weighted(). Fog that works on every renderer: dark horror fog.

Ready-made horror effects: Horror Atmosphere VFX for Godot 4 has 45 presets in Modern and Retro PSX looks, including Ground Fog, Creeping Mist, flickering and dying bulbs, a dying flashlight, glowing eyes and ghosts.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Horror Atmosphere VFX for Godot 4 has 45 ready-made horror effects in Modern and Retro PSX looks, including flickering and dying bulbs, a dying flashlight, Ground Fog, glowing eyes and ghosts.

More how-tos for Horror Atmosphere VFX for Godot 4: Dark horror fog that works in Compatibility · A scare that plays once, and only for the player

More how-tos: Game systems