A slot machine is three random numbers in a costume. The numbers take one line of GDScript. The costume is this whole tutorial.
By the end you will have the machine in the GIF above: three reels that spin, stop one after another with a little clunk, check a payline, pay out in coins and light up when you win. It is two scripts and a scene with one node. No art to draw and no addons. Everything is shapes and labels, so you can swap in your own symbols later.
Every code block below is copied from the files that ran in Godot 4.3, and the GIF is a recording of that run.
The machine is called Shy Seven, because the 7 only appears once per reel and acts like it. You will see why in step 5.
0. Set up
Make a new Godot 4.3 project. The Compatibility renderer is fine. You need three things:
-
reel.gd, one reel. It draws itself and knows how to spin. -
slot_machine.gd, the machine. It owns the reels, the random numbers, the coins and the button. -
main.tscn, a scene with a single Control node set to Full Rect, withslot_machine.gdattached. Make it the main scene.
The layout uses fixed positions for a 1280x720 window, which is the default, so leave the window size alone for now.
1. A reel is a number with a drawing attached
# reel.gd: one reel. It draws a looping strip of symbols and spins to a stop. class_name Reel extends Control signal stopped const SYMBOL_H := 110.0 # height of one symbol cell, in pixels var strip: Array[int] = [] # symbol ids, wraps around var names: PackedStringArray = [] # text for each symbol id var colors: PackedColorArray = [] # cell color for each symbol id # Which strip index sits on the middle row. Fractional while spinning. var position_on_strip := 0.0: set(value): position_on_strip = value queue_redraw() func _ready() -> void: custom_minimum_size = Vector2(150, SYMBOL_H * 3) clip_contents = true The whole reel is one float, position_on_strip. It says which spot on the strip sits on the middle row. When it is 4.0, symbol 4 is dead center. When it is 4.5, the reel is halfway between symbols 4 and 5. Spinning is just making that number go up.
The setter calls queue_redraw() every time the number changes, so a tween can animate it and the reel redraws itself without you doing anything. clip_contents hides whatever scrolls past the top and bottom edges, which is what makes it look like a window into a drum.
2. Draw the strip
func _draw() -> void: var font := ThemeDB.fallback_font var base := floori(position_on_strip) var frac := position_on_strip - base draw_rect(Rect2(Vector2.ZERO, size), Color("1d1626")) # Draw two extra rows so nothing pops in at the edges. for k in range(-2, 3): var id := strip[posmod(base - k, strip.size())] var top := size.y / 2.0 + (k + frac - 0.5) * SYMBOL_H var cell := Rect2(10, top + 6, size.x - 20, SYMBOL_H - 12) draw_rect(cell, colors[id]) var baseline := Vector2(cell.position.x, cell.get_center().y + 10) draw_string(font, baseline, names[id], HORIZONTAL_ALIGNMENT_CENTER, cell.size.x, 28, Color("14101a")) base is the whole part of the position, frac the leftover. Each row is drawn at (k + frac) cells from the middle, so as frac grows the symbols slide down, and when it reaches 1.0 the next symbol has taken the middle spot. posmod wraps the index so the strip loops forever instead of running off the end of the array.
It draws five rows for a three row window. The extra two sit just outside the clip, so a new symbol slides in from the top instead of appearing out of nowhere.
3. Ask a reel what it is showing
# The symbol on a row: -1 is the top row, 0 the middle, 1 the bottom. func symbol_at(row: int) -> int: return strip[posmod(roundi(position_on_strip) - row, strip.size())] Row 0 is the payline. roundi is cheap insurance. After a spin the position should be a whole number, and floats love landing on 6.9999999 anyway.
4. Spin, stop, clunk
func spin_to(stop: int, duration: float) -> void: var n := strip.size() # Always roll forward: finish this lap, do two more, then land on stop. var target := floorf(position_on_strip / n) * n + n * 3 + stop var tween := create_tween() # Wind up: a small tug the wrong way, like someone pulled a lever. tween.tween_property(self, "position_on_strip", position_on_strip - 0.3, 0.15).set_trans(Tween.TRANS_SINE) # The spin: fast at first, slowing down, sailing a little past the stop. tween.tween_property(self, "position_on_strip", target + 0.25, duration).set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT) # The clunk: settle back onto the stop with a tiny bounce. tween.tween_property(self, "position_on_strip", target, 0.25).set_trans(Tween.TRANS_BACK).set_ease(Tween.EASE_OUT) tween.tween_callback(_on_landed) func _on_landed() -> void: position_on_strip = fposmod(position_on_strip, strip.size()) stopped.emit() This is the part that makes it feel like a machine and not a spreadsheet. One tween, three steps in a row:
- Wind up. The reel tugs back 0.3 of a symbol in 0.15 seconds. Your eye reads it as a lever being pulled.
- Spin. It rolls forward a few full laps and slightly past the target.
TRANS_CUBICwithEASE_OUTstarts fast and slows down, which is how a heavy drum behaves. - Clunk. It settles back onto the target in 0.25 seconds.
TRANS_BACKwithEASE_OUTadds a tiny bounce, like a detent clicking into place.
target always lands a few laps ahead, so the reel never spins backwards to reach a symbol that happens to be above it. When it lands, _on_landed wraps the position back into the strip's range, so the number does not grow forever, and emits stopped.
5. The strip is where the odds live
Now the machine. It starts with the symbols, the strip and the pay table:
# slot_machine.gd: three reels, one payline, a coin counter and a Spin button. extends Control enum { CHERRY, LEMON, BELL, BAR, SEVEN } const NAMES := ["CHERRY", "LEMON", "BELL", "BAR", "7"] const COLORS := [Color("e5484d"), Color("f5d90a"), Color("f59e0b"), Color("9ca3af"), Color("3dd6f5")] # The reel strip. Common symbols appear more often, so they land more often. # 12 stops: 4 cherries, 3 lemons, 2 bells, 2 bars and one lonely 7. const STRIP: Array[int] = [CHERRY, LEMON, BELL, CHERRY, BAR, LEMON, CHERRY, SEVEN, BELL, LEMON, CHERRY, BAR] # Three of a kind on the payline pays this many coins. const PAYS := {CHERRY: 5, LEMON: 10, BELL: 20, BAR: 40, SEVEN: 100} const BET := 1 Real reels are a loop of printed symbols. Common symbols are printed several times, rare ones once. This strip does the same: 12 stops, 4 of them cherries and 1 of them a 7. Picking a random stop is fair, and the strip does the weighting for you.
So a cherry lands on the payline 4 times in 12, and the 7 lands 1 time in 12. Three 7s in a row is 1 in 1,728. That is the Shy Seven. It pays 100 coins because it almost never shows up.
6. A seeded random number generator
@export var rng_seed := 0 # 0 means a new random game every launch var rng := RandomNumberGenerator.new() var coins := 50 var spinning := false var reels: Array[Reel] = [] var coin_label := Label.new() var message := Label.new() var spin_button := Button.new() var win_frame := Panel.new() var win_tween: Tween func _ready() -> void: if rng_seed == 0: rng.randomize() else: rng.seed = rng_seed _build_ui() for reel in reels: reel.position_on_strip = rng.randi_range(0, STRIP.size() - 1) _update_coins() The machine has its own RandomNumberGenerator instead of using the global one. Leave rng_seed at 0 and every launch is a different game. Set it to any other number in the Inspector and you get the same game every time: the same start, the same spins, the same results. That is how the GIF at the top was recorded, with seed 226. Use it for testing, bug reports and recording trailers. Turn it back to 0 before you ship.
7. Build the cabinet
This part is long but not clever. It makes the background, the cabinet, the title, the three reels, the payline frame, the labels and the button:
func _build_ui() -> void: var bg := ColorRect.new() bg.color = Color("2a1f3d") bg.set_anchors_preset(Control.PRESET_FULL_RECT) add_child(bg) # The cabinet: a rounded panel behind everything, and a name on top. var body_style := StyleBoxFlat.new() body_style.bg_color = Color("3d2b5c") body_style.border_color = Color("ffd34d") body_style.set_border_width_all(4) body_style.set_corner_radius_all(24) var body := Panel.new() body.add_theme_stylebox_override("panel", body_style) body.position = Vector2(360, 20) body.size = Vector2(560, 640) add_child(body) var title := Label.new() title.text = "SHY SEVEN" title.position = Vector2(400, 30) title.size = Vector2(480, 60) title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER title.add_theme_font_size_override("font_size", 44) title.add_theme_color_override("font_color", Color("ffd34d")) add_child(title) var row := HBoxContainer.new() row.position = Vector2(400, 150) row.add_theme_constant_override("separation", 15) add_child(row) for i in 3: var reel := Reel.new() reel.strip = STRIP reel.names = PackedStringArray(NAMES) reel.colors = PackedColorArray(COLORS) row.add_child(reel) reels.append(reel) # The payline frame sits over the middle row and lights up on a win. var frame_style := StyleBoxFlat.new() frame_style.bg_color = Color(1, 0.85, 0.3, 0.12) frame_style.border_color = Color("ffd34d") frame_style.set_border_width_all(5) frame_style.set_corner_radius_all(8) win_frame.add_theme_stylebox_override("panel", frame_style) win_frame.position = Vector2(392, 150 + Reel.SYMBOL_H - 4) win_frame.size = Vector2(3 * 150 + 2 * 15 + 16, Reel.SYMBOL_H + 8) win_frame.modulate.a = 0.0 add_child(win_frame) coin_label.position = Vector2(400, 98) coin_label.add_theme_font_size_override("font_size", 28) add_child(coin_label) message.position = Vector2(400, 492) message.size = Vector2(480, 50) message.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER message.add_theme_font_size_override("font_size", 32) add_child(message) spin_button.text = "SPIN" spin_button.position = Vector2(560, 560) spin_button.custom_minimum_size = Vector2(160, 60) spin_button.add_theme_font_size_override("font_size", 28) spin_button.pressed.connect(spin) add_child(spin_button) The win frame is a Panel with a gold border, laid over the middle row and fully transparent until someone wins. All three reels share the same STRIP.
8. Spin
func spin() -> void: if spinning or coins < BET: return spinning = true coins -= BET _update_coins() _hide_win() message.text = "" # Decide the result first. The animation only has to agree with it. var stops: Array[int] = [] for reel in reels: stops.append(rng.randi_range(0, STRIP.size() - 1)) for i in reels.size(): # Each reel spins a bit longer than the one to its left. reels[i].spin_to(stops[i], 1.0 + 0.45 * i) await reels[-1].stopped _pay_out(stops) spinning = false The most important line is the comment: the result is decided before anything moves. Three random stops are picked, and then each reel is told where to land. The animation is decoration. It never decides anything, so a dropped frame or a slow computer can never change a result.
The durations are 1.0, 1.45 and 1.9 seconds, so the reels stop left to right. With the wind up and the clunk added, they stopped 1.40, 1.83 and 2.27 seconds after the press in the recorded run. await reels[-1].stopped waits for the last reel, which is also the slowest. If you ever change the durations so a different reel finishes last, wait for that one instead.
The spinning flag stops people from mashing the button mid spin. They will try.
9. Check the payline and pay out
# What the payline pays, given the stop index of each reel. func payout_for(stops: Array[int]) -> int: var a := STRIP[stops[0]] var b := STRIP[stops[1]] var c := STRIP[stops[2]] if a == b and b == c: return PAYS[a] # Two cherries on the left still pay something. Cherries are nice like that. if a == CHERRY and b == CHERRY: return 2 return 0 Three of a kind on the middle row pays from the table. Two cherries on the first two reels pay 2, because cherries are nice like that. Everything else pays nothing.
func _pay_out(stops: Array[int]) -> void: var win := payout_for(stops) if win == 0: message.text = "No luck. The 7 is shy." return message.text = "WIN %d" % win # Count the coins up instead of jumping, so the win lasts a moment. var tween := create_tween() tween.tween_method(_set_coins, coins, coins + win, 0.8) _show_win() func _set_coins(value: int) -> void: coins = value _update_coins() func _update_coins() -> void: coin_label.text = "COINS %d" % coins func _show_win() -> void: # Pulse the payline frame until the next spin. win_tween = create_tween().set_loops() win_tween.tween_property(win_frame, "modulate:a", 1.0, 0.25) win_tween.tween_property(win_frame, "modulate:a", 0.35, 0.35) func _hide_win() -> void: if win_tween: win_tween.kill() win_frame.modulate.a = 0.0 When the player wins, three things happen. The message says how much. The coin counter counts up over 0.8 seconds with tween_method instead of jumping, so the win lasts long enough to enjoy. The payline frame pulses on a looping tween until the next spin, which kills it. When the player loses, the message blames the 7. It is always the 7.
Here is what that looks like next to the version with no animation, where the reels jump straight to the result. Same seed, same BAR BAR BAR, very different amount of fun:


