Flapping bird

We will make a clone of a popular game with raylib: a bird flies through holes in walls, and Space makes it flap.

If raylib is new for you, read A window with raylib first.

The finished game with a background, a bird and pipes

A window

Start with an empty window. Save this as flappy.mox:

import "std.mox";
const rl := import "vendor/raylib.mox";

const SCREEN_WIDTH := 800;
const SCREEN_HEIGHT := 600;

#linkc fn main(): i32 {
    rl.InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "flapping bird");
    defer rl.CloseWindow();

    while (!rl.WindowShouldClose()) {
        rl.BeginDrawing();
        defer rl.EndDrawing();

        rl.ClearBackground(.{ 24, 24, 24, 255 });
    }

    return 0;
}

Build and run:

mox ./flappy.mox
./flappy.mox.exe

const rl := import ... puts raylib behind the name rl, so its functions are rl.InitWindow, rl.ClearBackground and so on.

The while loop runs once per frame. Everything we add from now on goes into main: variables before the loop, and the game itself inside the loop.

The bird

The bird only moves up and down, so one number is enough for it. Add a variable before the loop:

pos_y : f32 = 100;

And draw a circle after ClearBackground:

rl.DrawCircleV(.{ SCREEN_WIDTH / 2, pos_y }, 10.0f, rl.COLOR_YELLOW);

A yellow circle hangs near the top of the window. It is not a bird yet, but it is the right size and in the right place. That is all we need to make the rules of the game.

A yellow circle on a dark background

Gravity

The bird must fall. Add the fall speed before the loop, in pixels per second:

gravity : f32 = 500;

And move the bird at the start of the loop:

dt := rl.GetFrameTime();

pos_y += gravity * dt;

dt is the time of the last frame in seconds. Multiply every speed by it, and the game runs the same on a fast and on a slow computer.

y grows down on the screen, so adding to pos_y moves the bird down. Now the circle falls out of the window in about a second.

Flapping

Space must push the bird up. The push should be strong at first and then fade, so the bird goes up, slows down and falls again.

For this we keep one more speed, jump_velocity. It works against gravity. Add before the loop:

jump_acc : f32 = 400;
jump_decc : f32 = 400;
max_jump_velocity := jump_acc * 2.0f;

jump_velocity : f32 = 0;

And replace pos_y += gravity * dt; with:

velocity := gravity - jump_velocity;
jump_velocity = clamp(jump_velocity - jump_decc * dt, 0.0f, max_jump_velocity);
if (rl.IsKeyPressed(rl.KEY_SPACE)) {
    jump_velocity += jump_acc;
}

pos_y += velocity * dt;

One press only slows the fall. Two fast presses lift the bird. This makes the player tap all the time, and that is the whole game.

Flying forward

On the screen the bird stays in the middle, and it looks like the world moves to the left. In the code it is the other way: the walls stand still, the bird flies to the right, and a camera follows it.

Both ways work, but moving one camera is easier than moving every wall.

Add two variables before the loop:

game_speed : f32 = 100;
pos_x : f32 = 0;

Move the bird forward where pos_y changes:

pos_x += game_speed * dt;

And replace the DrawCircleV line. The bird is now drawn at its world position, inside a camera:

rl.BeginMode2D(.{
    offset = .{ SCREEN_WIDTH / 2, 0 },
    target = .{ pos_x, 0 },
    rotation = 0,
    zoom = 1,
});

bird_center := vec2f.{ pos_x, pos_y };
rl.DrawCircleV(bird_center, 10.0f, rl.COLOR_YELLOW);

rl.EndMode2D();

Everything between BeginMode2D and EndMode2D is drawn in world coordinates. The camera has two points:

The camera: target is a point in the world, offset is the point on the screen where it is drawn

So the bird’s x is always in the middle of the screen. The camera does not follow y, so up and down stay the same.

It looks the same as before, because there is nothing else in the world yet.

A wall

A wall is a column with a hole in it. Three numbers describe it. Add this above main:

const WALL_WIDTH := 32;

struct Wall {
    pos: f32;
    hole_y: f32;
    hole_size: f32;
}

pos is the left side of the wall in the world. hole_y is the top of the hole, and hole_size is its height.

A wall: two rectangles with a hole between them

Each wall must be different, or the game is boring. So the hole is random. Import the random module at the top of the file:

import "std/random.mox";

And add a function that makes a wall at a given place:

fn make_wall(pos_x: f32): Wall {
    hole_size := random_in_range(200.0f, 300.0f);

    return .{
        pos = pos_x;
        hole_y = random_in_range(0.0f, SCREEN_HEIGHT - hole_size);
        hole_size = hole_size;
    };
}

The hole always fits on the screen, because hole_y is never bigger than SCREEN_HEIGHT - hole_size.

The random numbers are the same on each run until you set a seed. Do it once in main, before the loop:

prng_reset_default(time_unix_ms().cast(u64));

See Random numbers for more.

Many walls

There is more than one wall on the screen, and later we add and remove them all the time. So they live in a DynArr, an array that can grow.

Add a function that makes the first two walls, above main:

const WALL_SPACING := 400;

fn spawn_initial_walls(walls: *DynArr(Wall)) {
    push(walls, make_wall(WALL_SPACING));
    push(walls, make_wall(WALL_SPACING * 2));
}

The walls stand WALL_SPACING pixels apart. The bird starts at 0, so it has some free space before the first one.

Make the array in main, before the loop:

walls: DynArr(Wall) = 0;
dynarr_init(walls.^);
defer dynarr_free(walls.^);
spawn_initial_walls(walls.^);

Now draw them. Each wall is two rectangles, one above the hole and one below it. Put this after the bird, before EndMode2D:

for (wall : iterate(walls.items)) {
    top := rl.Rectangle.{ wall.pos, 0, WALL_WIDTH, wall.hole_y };
    bottom := rl.Rectangle.{ wall.pos, wall.hole_y + wall.hole_size, WALL_WIDTH, SCREEN_HEIGHT };

    rl.DrawRectangleRec(top, rl.COLOR_GREEN);
    rl.DrawRectangleRec(bottom, rl.COLOR_GREEN);
}

A Rectangle is x, y, width, height. The bottom one is taller than it needs to be. The extra part is below the screen, so nobody sees it.

Two green walls come from the right. The bird flies right through them, and after the second wall the world is empty. We fix both next.

The bird between two green walls

Collisions

The bird is a circle and the walls are rectangles, so raylib can check if they touch. We need to remember the result. Add a flag before the loop:

is_dead := false;

And check both rectangles in the wall loop, right after drawing them:

if (rl.CheckCollisionCircleRec(bird_center, 10.0f, top) || rl.CheckCollisionCircleRec(bird_center, 10.0f, bottom)) {
    is_dead = true;
}

This is why we started with plain shapes. The circle on the screen is exactly the circle in the check. If the bird dies when it should not, you see why.

Game over

The flag does nothing yet. A dead bird must stop, so put the movement code under if (!is_dead). Move it after EndMode2D too, we draw on top of the world in a moment:

if (!is_dead) {
    velocity := gravity - jump_velocity;
    jump_velocity = clamp(jump_velocity - jump_decc * dt, 0.0f, max_jump_velocity);
    if (rl.IsKeyPressed(rl.KEY_SPACE)) {
        jump_velocity += jump_acc;
    }

    pos_y += velocity * dt;
    pos_x += game_speed * dt;
}

Now the game freezes when the bird hits a wall. The player should see that it is over. Add an else that makes the screen dark and shows a text:

else {
    rl.DrawRectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, .{ 0, 0, 0, 180 });
    rl.DrawText("PRESS SPACE", 200, 200, 24, rl.COLOR_YELLOW);
}

This is drawn after EndMode2D, so it uses screen coordinates and does not move with the world.

The bird touches a wall, the screen is dark and says PRESS SPACE

The text asks for Space, so Space must start a new game. Add this at the end of the else block:

if (rl.IsKeyPressed(rl.KEY_SPACE)) {
    is_dead = false;
    pos_x = 0;
    pos_y = 100;
    game_speed = 100;
    jump_velocity = 200;

    dynarr_reset(walls.^);
    spawn_initial_walls(walls.^);
}

All variables go back to their start values and the walls are made again. dynarr_reset removes the items but keeps the memory. jump_velocity = 200 gives the bird a small push, so it does not drop like a stone on the first frame.

Score

The player wants to know how far they got. The walls stand WALL_SPACING apart, so the number of passed walls is the bird’s x divided by WALL_SPACING.

Add a variable before the loop:

score : f32 = 0;

And update it at the start of the loop, after dt:

new_score := floor(pos_x / WALL_SPACING);
if (new_score > score) {
    score = new_score;
}

The if is true once for each wall, at the moment the bird reaches it. We use this moment for more things below.

Show the score at the end of the if (!is_dead) block:

text := #format_temp("SCORE: {}\0", .{ score.cast(u32) }, nullptr(Alloc));
rl.DrawText(text.ptr, 10, 10, 24, rl.COLOR_YELLOW);

#format_temp makes a text that lives for a short time, which is enough to draw it. raylib wants a C string, so the text ends with \0. The last argument is not needed here, with it you pass conflict allocator.

Show it on the game over screen too. Replace the DrawText line there with:

text := #format_temp("FINAL SCORE: {}\nPRESS SPACE\0", .{ score.cast(u32) }, nullptr(Alloc));
rl.DrawText(text.ptr, 200, 200, 24, rl.COLOR_YELLOW);

And add one line to the restart code:

score = 0;

New walls

After the second wall the world is still empty. The score code already knows when the bird reaches a wall. That is a good moment to add a new one. Put this inside if (new_score > score):

push(walls.^, make_wall(pos_x + WALL_SPACING * 2));

The new wall appears two steps ahead. That is outside the screen, so the player does not see it pop up.

Now the game never ends, but the array grows forever. Walls that are behind the screen are not needed. Add this after the push:

if (walls.items[0].pos + WALL_WIDTH < pos_x - SCREEN_WIDTH / 2) {
    remove_at(walls.^, 0);
}

The walls are stored from left to right. So only the first one can be behind the left side of the screen, and one check is enough. The array never has more than a few walls, no matter how long you play.

Last thing: the game should get harder. Make it a bit faster with each wall, in the same if:

game_speed += 20.0f;

This is a whole game now. It only looks plain.

The game with shapes and a score in the corner

Textures

The game uses three images from the Flappy Bird Assets pack by Megacrash. The pack is free to use in any project (CC0), see its credits. Download the three files:

Put them into an assets folder next to your flappy.mox. The full pack has more birds, backgrounds and pipes.

Import build.mox at the top of the file:

import "build.mox";

And load the images in main before the loop. This must be after InitWindow, raylib can not make textures without a window.

tex_bg := build_resolve_path("./assets/Background2.png") |> #temp_c_string() |> rl.LoadTexture();
tex_bird := build_resolve_path("./assets/Bird2-1.png") |> #temp_c_string() |> rl.LoadTexture();
tex_pipes := build_resolve_path("./assets/PipeStyle1.png") |> #temp_c_string() |> rl.LoadTexture();

build_resolve_path makes a path relative to the source file. This works when the code runs at compile time, or when you build with -g. In a normal build the program does not know where its source file was, and the path stays assets/.... Then it is relative to the folder you start the game from, so start it from the folder with assets.

#temp_c_string turns a Mox string into a C string for raylib.

|> is the pipe operator. It passes the value on the left as the first argument of the call on the right. So the line reads from left to right, in the order things happen: make the path, turn it into a C string, load the texture. Without it the same line is rl.LoadTexture(#temp_c_string(build_resolve_path(...))).

All three are drawn with rl.DrawTexturePro. It takes a part of the texture (the source rectangle) and draws it into a rectangle on the screen (the destination). If the sizes differ, the image is stretched.

Background

Draw it right after ClearBackground, before the camera:

rl.DrawTexturePro(
    tex_bg,
    // texture source rect
    .{ pos_x * 0.1f, 0, tex_bg.width.cast(f32), tex_bg.height.cast(f32) },
    // screen draw rect
    .{ 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT },
    // origin
    .{ 0, 0 },
    // rotation
    0.0f,
    // color tint
    .{ 240, 240, 240, 255 }
);

The source rectangle moves to the right with the bird, but ten times slower. Things that move slower look far away. This is called parallax. When the source goes past the edge of the texture, the texture repeats.

Bird

The bird image has four frames in a row, each 16x16 pixels. Replace DrawCircleV with:

bird_frame := floor(jump_velocity / max_jump_velocity * 4.0f);
rl.DrawTexturePro(
    tex_bird,
    .{ bird_frame * 16, 0, 16, 16 }, // source rect
    .{ pos_x, pos_y, 50, 50 },       // draw rect
    .{ 25, 25 },                     // origin
    clamp(gravity - jump_velocity, -180, 180) / 5, // rotation
    rl.COLOR_WHITE
);

The collision check still uses the circle with radius 10. It is smaller than the picture, and that is good. Players get angry when they die without touching anything.

Pipes

The pipe image has a few pipes of different colors. Each is 32 pixels wide and made of slices 20 pixels high: a cap, the body, the body again, a cap. We use the first pipe.

A wall can have any height, so we can not stretch the whole pipe. Instead we stretch only the body and draw the cap at its normal size.

The pipe texture cut into four slices, and a wall made from them

First a function that draws one slice. src_y picks the slice, dest is where it goes. Add it above main:

const PIPE_CAP := 20;

fn draw_pipe_part(tex: rl.Texture2D, src_y: f32, dest: rl.Rectangle) {
    rl.DrawTexturePro(
        tex,
        .{ 0, src_y, WALL_WIDTH, PIPE_CAP }, // source rect
        dest,                                // draw rect
        .{ 0, 0 },                           // origin
        0.0f,                                // rotation
        rl.COLOR_WHITE
    );
}

Then a function that draws a whole wall with it. Each pipe is two calls: a stretched body and a cap on the side of the hole.

fn draw_wall(tex: rl.Texture2D, top: rl.Rectangle, bottom: rl.Rectangle) {
    // top pipe: body, then the cap facing the hole
    draw_pipe_part(tex, PIPE_CAP,     .{ top.x, top.y, top.width, top.height - PIPE_CAP });
    draw_pipe_part(tex, PIPE_CAP * 3, .{ top.x, top.y + top.height - PIPE_CAP, top.width, PIPE_CAP });
    // bottom pipe: the cap facing the hole, then body
    draw_pipe_part(tex, 0,            .{ bottom.x, bottom.y, bottom.width, PIPE_CAP });
    draw_pipe_part(tex, PIPE_CAP,     .{ bottom.x, bottom.y + PIPE_CAP, bottom.width, bottom.height - PIPE_CAP });
}

In the wall loop replace the two DrawRectangleRec calls with:

draw_wall(tex_pipes, top, bottom);

The top and bottom rectangles are the same ones the collision check uses. The picture changed, the rules did not.

The finished game with a background, a bird and pipes

What to try next

Advanced: images inside the exe

Right now the game reads the three images from disk when it starts. If you give the game to a friend, you must send the assets folder too, and the game must be started from the folder it is in.

Mox can run code while compiling, see Running code at compile time. So we can read the files during the build and keep their bytes inside the exe.

Add three global variables above main:

bg_png : []u8 = #run fs_read_file_full(build_resolve_path("./assets/Background2.png"));
bird_png : []u8 = #run fs_read_file_full(build_resolve_path("./assets/Bird2-1.png"));
pipes_png : []u8 = #run fs_read_file_full(build_resolve_path("./assets/PipeStyle1.png"));

#run runs fs_read_file_full while compiling. Here build_resolve_path always finds the files next to the source file, because the compiler knows where it is. The result, all bytes of the file, is written into the program. When the game runs, bg_png is already filled and nothing is read from disk.

We still need to load the textures in raylib, now from memory. Add this function above main:

fn texture_from_memory(bytes: []u8): rl.Texture2D {
    image := rl.LoadImageFromMemory(".png", bytes.ptr, bytes.len.cast(i32));
    defer rl.UnloadImage(image);
    return rl.LoadTextureFromImage(image);
}

Then replace the three LoadTexture lines in main:

tex_bg := bg_png |> texture_from_memory();
tex_bird := bird_png |> texture_from_memory();
tex_pipes := pipes_png |> texture_from_memory();

Build the game again. Now the assets folder is only needed for the build. To share the game, send the exe and the raylib library file that the compiler put next to it.

Full code

The whole game in one file, with the images inside the exe: flappy.mox. You still need the assets folder next to it to build.