Games with ruby2d
In lesson 87 the page ran Chunky's Snake with show_game, a helper that only exists here. Real Ruby games on a computer are written with a gem, and one of the friendliest is ruby2d: it opens a window, draws shapes, text and pictures in it, and tells your program about every key and every click. Under the hood it uses SDL, a C library that many commercial games are built on too.
A C library cannot run in this browser. So the page brings a stand-in: ruby2d's own Ruby code, unchanged, with a small piece written in Ruby where the gem would call SDL. The point of it: every program in this lesson runs just the same with the real gem on your computer. Here is a complete ruby2d program. Run it, and a window appears below the cell:
require "ruby2d"
set title: "Hello, Chunky!", background: "navy"
Square.new(x: 270, y: 190, size: 100, color: "orange")
show
Line by line: require "ruby2d" loads the gem, and from then on set, Square, show and friends are simply there. set changes the window: its title, its background, and also its size with width: and height: – without them it is 640 × 480 pixels. Square.new makes a square and puts it into the window straight away. show finally opens the window.
Positions are counted as in Processing (lesson 82): x from the left edge, y from the top edge, in pixels. The square starts at 270, 190 and is 100 pixels wide, so it sits in the middle. Besides Square there are Rectangle (width:, height:), Circle (x: and y: are its centre, plus radius:), Triangle (three corners x1: … y3:), Line and Text. A colour is a name such as "orange" or "navy", a hex code like "#d35400", or "random", which picks one by chance:
require "ruby2d"
set background: "#87ceeb" # sky blue
# a meadow
Rectangle.new(x: 0, y: 360, width: 640, height: 120, color: "green")
# a cloud: written before the sun, but drawn in front of it (z: 1)
Circle.new(x: 530, y: 100, radius: 35, color: "white", opacity: 0.8, z: 1)
Circle.new(x: 560, y: 80, radius: 40, color: "yellow") # the sun
# Chunky's head: two ears, the face, two eyes and a nose
Triangle.new(x1: 250, y1: 120, x2: 300, y2: 200, x3: 230, y3: 210,
color: "#d35400")
Triangle.new(x1: 390, y1: 120, x2: 410, y2: 210, x3: 340, y3: 200,
color: "#d35400")
Triangle.new(x1: 220, y1: 190, x2: 420, y2: 190, x3: 320, y3: 330,
color: "orange")
Circle.new(x: 285, y: 230, radius: 9, color: "black")
Circle.new(x: 355, y: 230, radius: 9, color: "black")
Circle.new(x: 320, y: 310, radius: 8, color: "black")
Text.new("Chunky", x: 265, y: 380, size: 36, color: "white")
show
Shapes are drawn in the order they were made – later ones on top. z: changes that: a shape with a higher z lies in front, which is why the cloud covers the sun although it was written first. opacity: goes from 0 (invisible) to 1 (solid); at 0.8 the sun shines through the cloud a little.
Now for movement. A game draws a new picture again and again, about 60 times a second – each one is a frame. Before each frame ruby2d calls the block you give to update. In it you change your shapes, and the next frame shows them in their new place:
require "ruby2d"
set background: "navy"
bacon = Rectangle.new(x: 0, y: 220, width: 90, height: 30, color: "#e74c3c")
speed = 4
counter = Text.new("Frame 0", x: 10, y: 10, size: 20)
update do
bacon.x += speed
if bacon.x + bacon.width >= Window.width || bacon.x <= 0
speed = -speed # turn round at the edge
end
counter.content = "Frame #{Window.frames}"
end
show
Click the window to start it; Esc pauses it, Tab or a click elsewhere leaves it – just like the Snake. bacon.x += speed moves the bacon a few pixels per frame; a shape's x, y, color, width or radius can be changed at any time. Window.width is the window's width, Window.frames counts the frames drawn so far, and counter.content = … gives a Text new words. The update block remembers speed from the line above it, as the every blocks did in the Snake: it is a closure.
Keys arrive with on. on :key_down calls its block once when a key goes down, on :key_up when it comes up again, and on :key_held in every frame while it stays down – just right for walking. The block gets an event: event.key is the key's name as a String – "left", "up", "space", "return", "a" – and event.key?(:left) asks for one:
require "ruby2d"
set background: "navy"
chunky = Square.new(x: 300, y: 220, size: 40, color: "orange")
Text.new("Arrow keys: walk Space: new colour", x: 10, y: 10, size: 18)
# every frame while a key is down
on :key_held do |event|
chunky.x -= 4 if event.key?(:left)
chunky.x += 4 if event.key?(:right)
chunky.y -= 4 if event.key?(:up)
chunky.y += 4 if event.key?(:down)
end
# once per press
on :key_down do |event|
chunky.color = "random" if event.key == "space"
end
show
The mouse works the same way: on :mouse_down (and :mouse_up, :mouse_move) gives an event with event.x and event.y, the place in the window, and event.button, :left or :right. Every shape can answer contains?(x, y): is this point on me? That is all a click game needs:
require "ruby2d"
set background: "white"
target = Circle.new(x: 320, y: 240, radius: 40, color: "red")
hits = 0
label = Text.new("Hits: 0", x: 10, y: 10, size: 24, color: "black")
on :mouse_down do |event|
if target.contains?(event.x, event.y)
hits += 1
label.content = "Hits: #{hits}"
target.x = rand(40..600)
target.y = rand(40..440)
target.radius = [target.radius - 3, 10].max # smaller with every hit
end
end
show
With that you can build a small game. Chunky waits at the bottom of the window and runs left and right; bacon falls from the sky. If he catches it, it counts, and the next piece falls a little faster. Three pieces missed and the game is over:
require "ruby2d"
set title: "Catch the bacon", background: "#1d2b53"
chunky = Rectangle.new(x: 280, y: 440, width: 80, height: 24,
color: "orange")
bacon = Rectangle.new(x: rand(0..600), y: 0, width: 40, height: 14,
color: "#e74c3c")
board = Text.new("Bacon: 0 Missed: 0", x: 10, y: 10, size: 20)
caught = 0
missed = 0
on :key_held do |event|
chunky.x -= 7 if event.key?(:left)
chunky.x += 7 if event.key?(:right)
end
update do
# game over: nothing moves any more
next if missed >= 3
bacon.y += 3 + caught * 0.5 # faster with every catch
if chunky.contains?(bacon.x + bacon.width / 2, bacon.y + bacon.height)
caught += 1
bacon.y = 0
bacon.x = rand(0..600)
elsif bacon.y > Window.height
missed += 1
bacon.y = 0
bacon.x = rand(0..600)
end
board.content = "Bacon: #{caught} Missed: #{missed}"
board.content = "Game over! #{caught} bacon" if missed >= 3
end
show
Everything happens in update, frame after frame: the bacon falls by a few pixels, and then two questions are asked. Is the middle of its lower edge on Chunky (contains?)? Then it is caught and starts again at the top, somewhere new. Has it fallen out of the window (bacon.y > Window.height)? Then it was missed. next ends a frame's block early – after three misses it ends straight away, and nothing moves any more.
A few things are different on this page. On a computer, show runs the window until you close it, and only then does the program carry on after show; here the page runs the frames, and show returns at once. What you print with puts appears below the window. If a frame raises an error, the window stops and shows it with the line number, and an endless loop in a frame is stopped after a second. close closes the window; ▶ starts the cell again. And the stand-in draws shapes and text only: pictures (Image, Sprite), sound (Audio) and gamepads need the real gem.
Install the gem with gem install ruby2d. On a Mac with Apple silicon and on Windows (RubyInstaller) it brings SDL along. On Linux, and on older Macs, install SDL 3 first – for example sudo apt install libsdl3-dev libsdl3-image-dev libsdl3-mixer-dev libsdl3-ttf-dev (Debian, Ubuntu) or brew install sdl3 sdl3_image sdl3_mixer sdl3_ttf – and then run gem pristine ruby2d; ruby2d setup can also build SDL for you. Save one of the programs above as game.rb and start it with ruby game.rb: the very same code opens a real window. There you can also use pictures and sounds, for instance Image.new("chunky.png", x: 10, y: 10). And ruby2d.com/try runs ruby2d in the browser as well, with the real C library compiled for the web.
x stays at 0, and at the right edge his right side stays at Window.width. One tool for it: clamp keeps a number between two limits – 12.clamp(0, 10) is 10, -3.clamp(0, 10) is 0.# Chunky walks out of the window. Keep him inside:
# at the left and at the right edge he stops.
require "ruby2d"
set title: "Chunky stays", width: 400, height: 300
fox = Rectangle.new(x: 170, y: 240, width: 60, height: 40,
color: "orange")
on :key_held do |event|
fox.x -= 5 if event.key?(:left)
fox.x += 5 if event.key?(:right)
end
show