A hand-written shuffle that swaps every card with any position in the deck is not fair: some orders come up more often than others. In our Godot 4.7 test, 270,000 shuffles of a 3-card deck dealt ACB, BAC and BCA 18.4% of the time and ABC and CAB 14.9%, when each should be 16.7%. The built-in Array.shuffle() was fair, 16.6 to 16.7%. The script, a Fisher-Yates shuffle with its own RandomNumberGenerator, was fair too, 16.6 to 16.8%, and the same seed dealt the same 52-card deck again.
The code
If you only need a fair random order, deck.shuffle() already is one. Use the script when you also want to replay a deal: save it as fair_shuffle.gd and call preload("res://fair_shuffle.gd").shuffle(deck, seed_value) with the same seed for a daily challenge, a replay or a bug report, or without a seed for a new order each time. Array.shuffle() uses the global random generator, so anything else that calls randi() or randf() changes which order you get.
extends RefCounted
## Shuffles a deck so every order is equally likely, with its own seed,
## so a daily run or a replay deals the same cards again.
## var deck := ["A", "K", "Q", "J"]
## FairShuffle.shuffle(deck) # random every time
## FairShuffle.shuffle(deck, 20261128) # same seed, same order
static func shuffle(deck: Array, seed_value: int = -1) -> Array:
var rng := RandomNumberGenerator.new()
if seed_value >= 0:
rng.seed = seed_value
else:
rng.randomize()
for i in range(deck.size() - 1, 0, -1):
var j := rng.randi_range(0, i) # only from the cards not placed yet
var tmp = deck[i]
deck[i] = deck[j]
deck[j] = tmp
return deck
What we measured
A 3-card deck, A B C, shuffled 270,000 times with each method, counting how often each of the 6 orders came out. Two runs gave the same numbers.
- Swap every card with any position (randi_range(0, size - 1)): ACB, BAC and BCA 18.4% each, ABC and CAB 14.9%, CBA 15.0%.
Array.shuffle(): 16.6 to 16.7% for every order.- The script: 16.6 to 16.8% for every order. A 52-card deck shuffled twice with seed 20261128 came out the same both times, and differently with 20261129.
Why it happens
Swapping each of 3 cards with any of 3 positions makes 3 × 3 × 3 = 27 equally likely paths, but there are only 6 orders, and 27 does not divide by 6, so some orders get 5 paths and others 4: 18.5% and 14.8%. Fisher-Yates swaps each card only with itself or the cards before it that are not placed yet: 3 × 2 × 1 = 6 paths, one per order. Bigger decks have the same problem, because n × n × ... × n paths do not divide evenly by the number of orders.
What to change
- A draw that should not repeat the same card or sound twice in a row: a shuffle bag. Runs that should replay exactly: same seed, same results.
- Laying the dealt hand out on screen: a hand that fits and stays centered.
What the cards look like when they are played: Card Game VFX & Shaders for Godot 4 has 16 2D particle effects for card games, including Hit Flash, plus shaders for Sprite2D such as Glow Outline and Burn Dissolve.
Tested in Godot 4.7 with the Compatibility renderer.
Ready-made: Card Game VFX & Shaders for Godot 4 has 16 2D particle effects for card games, including Hit Flash, plus shaders for Sprite2D such as Glow Outline and Burn Dissolve.
More how-tos for Card Game VFX & Shaders for Godot 4: Hit flash shader for 2D sprites · 2D outline shader that is not cut off
More how-tos: Game systems
- Hover a 3D object inside a SubViewport
- A turned building that covers the cells it stands on
- An inventory that never loses an item and never overfills a stack
- A JSON save that loads back exactly what you saved
- Fire that spreads one cell per step, in every direction
- A pooled enemy that comes back as fresh as a new one
- An enemy that stops at the dead player and finds the respawned one
- Poison, burn and bleed that keep ticking when applied again
- XP, qi and gold that keep growing without going negative
- Count slot line wins with wilds in front
- Random directions spread evenly over a sphere or a cone
- Count a lap only when the car really went round
- Make a seed repeat: daily runs, replays and roguelike seeds
- Offline progress that counts the time the game was closed
- A chance roll without the long bad-luck streaks
- Check crafting recipes in any order, with the right counts
- Make HP and mana regen the same at any frame rate
- Damage over time with the right number of ticks
- Spawn enemies where the camera cannot see them
- Keep a chasing horde from stacking into one enemy
- Make the fish bite after the same wait at any frame rate
- Snap buildings to the right grid cell on both sides of the origin
- Make a cooking timer fire once, on time
- Pick from a weighted loot table with the right chances
- Level up as many times as the XP covers
- Walk a patrol guard to each point without overshooting
- Remove items from an Array while checking them, without skipping any
- Scatter spikes, roots or trees in a circle without overlaps
- Count and take crafting items from every stack
- Play random sounds and events without obvious repeats
- Pick the growth image so the ripe one shows exactly when the crop can be picked
- Turn a day counter into season, day and year without a day 0
- An enemy that dies once, however many hits land
- A ghost that drives the lap at real speed
- A vision cone that does not flicker at the edge
- Move a group of units without a pile-up
- A sprinkler that waters a round patch
- A slot reel that always lands forward on the result
- A crowd of NPCs that never emote or bob in step
- A song position that moves on every frame
- Nodes your editor tool adds that stay in the scene