← ziglang.inraylib-zigGitHub

random sequence

★☆☆☆by Dalton Overmyer (@REDl3east)

There is no browser build of this example yet.

Is it the same as C?

//! raylib [core] example - random sequence
//!
//! Zig-API translation of examples/core/core_random_sequence.c (raylib 6.2).
//! Example contributed by Dalton Overmyer (@REDl3east) and reviewed by Ramon Santamaria (@raysan5)
//! Example licensed under an unmodified zlib/libpng license.
//! Copyright (c) 2023-2025 Dalton Overmyer (@REDl3east)

const std = @import("std");
const rl = @import("raylib");

const ColorRect = struct {
    color: rl.Color,
    rect: rl.Rectangle,
};

const screen_width = 800;
const screen_height = 450;

pub fn main(init: std.process.Init) !void {
    const gpa = init.gpa;

    // Initialization
    rl.initWindow(screen_width, screen_height, "raylib [core] example - random sequence");
    defer rl.closeWindow(); // Close window and OpenGL context

    var rect_count: usize = 20;
    var rectangles = try generateRandomColorRectSequence(gpa, rect_count);
    defer gpa.free(rectangles);

    rl.setTargetFPS(60);

    // Main game loop
    while (!rl.windowShouldClose()) { // Detect window close button or ESC key
        // Update
        if (rl.isKeyPressed(.space)) try shuffleColorRectSequence(rectangles);

        if (rl.isKeyPressed(.up)) {
            rect_count += 1;

            // Re-generate random sequence with new count
            gpa.free(rectangles);
            rectangles = try generateRandomColorRectSequence(gpa, rect_count);
        }

        if (rl.isKeyPressed(.down)) {
            if (rect_count >= 4) {
                rect_count -= 1;

                // Re-generate random sequence with new count
                gpa.free(rectangles);
                rectangles = try generateRandomColorRectSequence(gpa, rect_count);
            }
        }

        // Draw
        rl.beginDrawing();
        defer rl.endDrawing();

        rl.clearBackground(.ray_white);

        for (rectangles) |rectangle| {
            rl.drawRectangleRec(rectangle.rect, rectangle.color);

            rl.drawText("Press SPACE to shuffle the current sequence", 10, screen_height - 96, 20, .black);
            rl.drawText("Press UP to add a rectangle and generate a new sequence", 10, screen_height - 64, 20, .black);
            rl.drawText("Press DOWN to remove a rectangle and generate a new sequence", 10, screen_height - 32, 20, .black);
        }

        rl.drawText(rl.textFormat("Count: {d} rectangles", .{rect_count}), 10, 10, 20, .maroon);

        rl.drawFPS(screen_width - 80, 10);
    }
}

fn generateRandomColor() rl.Color {
    return .{
        .r = @intCast(rl.getRandomValue(0, 255)),
        .g = @intCast(rl.getRandomValue(0, 255)),
        .b = @intCast(rl.getRandomValue(0, 255)),
        .a = 255,
    };
}

/// Bars of random heights (a shuffled 0..count-1 ramp) spanning the screen width.
fn generateRandomColorRectSequence(gpa: std.mem.Allocator, count: usize) ![]ColorRect {
    const rect_count: f32 = @floatFromInt(count);
    const rect_width = @as(f32, screen_width) / rect_count;
    const height = 0.75 * @as(f32, screen_height);

    const rectangles = try gpa.alloc(ColorRect, count);
    errdefer gpa.free(rectangles);

    const seq = try rl.loadRandomSequence(@intCast(count), 0, @intCast(count - 1));
    defer rl.unloadRandomSequence(seq);

    const rect_seq_width = rect_count * rect_width;
    const start_x = (screen_width - rect_seq_width) * 0.5;

    for (rectangles, seq, 0..) |*rectangle, value, i| {
        const rect_height: i32 = @intFromFloat(rl.math.remap(@floatFromInt(value), 0, rect_count - 1, 0, height));
        const rect_h: f32 = @floatFromInt(rect_height);

        rectangle.color = generateRandomColor();
        rectangle.rect = .{
            .x = start_x + @as(f32, @floatFromInt(i)) * rect_width,
            .y = height - rect_h,
            .width = rect_width,
            .height = rect_h,
        };
    }

    return rectangles;
}

/// Shuffle the bars: swap only the color and height.
fn shuffleColorRectSequence(rectangles: []ColorRect) !void {
    const seq = try rl.loadRandomSequence(@intCast(rectangles.len), 0, @intCast(rectangles.len - 1));
    defer rl.unloadRandomSequence(seq);

    for (rectangles, seq) |*r1, index| {
        const r2 = &rectangles[@intCast(index)];

        const tmp = r1.*;
        r1.color = r2.color;
        r1.rect.height = r2.rect.height;
        r1.rect.y = r2.rect.y;
        r2.color = tmp.color;
        r2.rect.height = tmp.rect.height;
        r2.rect.y = tmp.rect.y;
    }
}
/*******************************************************************************************
*
*   raylib [core] example - random sequence
*
*   Example complexity rating: [★☆☆☆] 1/4
*
*   Example originally created with raylib 5.0, last time updated with raylib 5.0
*
*   Example contributed by Dalton Overmyer (@REDl3east) and reviewed by Ramon Santamaria (@raysan5)
*
*   Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
*   BSD-like license that allows static linking with closed source software
*
*   Copyright (c) 2023-2025 Dalton Overmyer (@REDl3east)
*
********************************************************************************************/

#include "raylib.h"

#include "raymath.h"

#include <stdlib.h>     // Required for: malloc(), free()

//----------------------------------------------------------------------------------
// Types and Structures Definition
//----------------------------------------------------------------------------------
typedef struct ColorRect {
    Color color;
    Rectangle rect;
} ColorRect;

//------------------------------------------------------------------------------------
// Module Functions Declaration
//------------------------------------------------------------------------------------
static Color GenerateRandomColor(void);
static ColorRect *GenerateRandomColorRectSequence(float rectCount, float rectWidth, float screenWidth, float screenHeight);
static void ShuffleColorRectSequence(ColorRect *rectangles, int rectCount);

//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - random sequence");

    int rectCount = 20;
    float rectSize = (float)screenWidth/rectCount;
    ColorRect *rectangles = GenerateRandomColorRectSequence((float)rectCount, rectSize, (float)screenWidth, 0.75f*screenHeight);

    SetTargetFPS(60);
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose()) // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        if (IsKeyPressed(KEY_SPACE)) ShuffleColorRectSequence(rectangles, rectCount);

        if (IsKeyPressed(KEY_UP))
        {
            rectCount++;
            rectSize = (float)screenWidth/rectCount;
            RL_FREE(rectangles);

            // Re-generate random sequence with new count
            rectangles = GenerateRandomColorRectSequence((float)rectCount, rectSize, (float)screenWidth, 0.75f*screenHeight);
        }

        if (IsKeyPressed(KEY_DOWN))
        {
            if (rectCount >= 4)
            {
                rectCount--;
                rectSize = (float)screenWidth/rectCount;
                RL_FREE(rectangles);

                // Re-generate random sequence with new count
                rectangles = GenerateRandomColorRectSequence((float)rectCount, rectSize, (float)screenWidth, 0.75f*screenHeight);
            }
        }
        //----------------------------------------------------------------------------------

        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();

            ClearBackground(RAYWHITE);

            for (int i = 0; i < rectCount; i++)
            {
                DrawRectangleRec(rectangles[i].rect, rectangles[i].color);

                DrawText("Press SPACE to shuffle the current sequence", 10, screenHeight - 96, 20, BLACK);
                DrawText("Press UP to add a rectangle and generate a new sequence", 10, screenHeight - 64, 20, BLACK);
                DrawText("Press DOWN to remove a rectangle and generate a new sequence", 10, screenHeight - 32, 20, BLACK);
            }

            DrawText(TextFormat("Count: %d rectangles", rectCount), 10, 10, 20, MAROON);

            DrawFPS(screenWidth - 80, 10);

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    RL_FREE(rectangles);
    CloseWindow(); // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}

//------------------------------------------------------------------------------------
// Module Functions Definition
//------------------------------------------------------------------------------------
static Color GenerateRandomColor(void)
{
    Color color = {
        GetRandomValue(0, 255),
        GetRandomValue(0, 255),
        GetRandomValue(0, 255),
        255
    };

    return color;
}

static ColorRect *GenerateRandomColorRectSequence(float rectCount, float rectWidth, float screenWidth, float screenHeight)
{
    ColorRect *rectangles = (ColorRect *)RL_CALLOC((int)rectCount, sizeof(ColorRect));

    int *seq = LoadRandomSequence((unsigned int)rectCount, 0, (unsigned int)rectCount - 1);
    float rectSeqWidth = rectCount*rectWidth;
    float startX = (screenWidth - rectSeqWidth)*0.5f;

    for (int i = 0; i < rectCount; i++)
    {
        int rectHeight = (int)Remap((float)seq[i], 0, rectCount - 1, 0, screenHeight);

        rectangles[i].color = GenerateRandomColor();
        rectangles[i].rect = CLITERAL(Rectangle){ startX + i*rectWidth, screenHeight - rectHeight, rectWidth, (float)rectHeight };
    }

    UnloadRandomSequence(seq);

    return rectangles;
}

static void ShuffleColorRectSequence(ColorRect *rectangles, int rectCount)
{
    int *seq = LoadRandomSequence(rectCount, 0, rectCount -  1);

    for (int i1 = 0; i1 < rectCount; i1++)
    {
        ColorRect *r1 = &rectangles[i1];
        ColorRect *r2 = &rectangles[seq[i1]];

        // Swap only the color and height
        ColorRect tmp = *r1;
        r1->color = r2->color;
        r1->rect.height = r2->rect.height;
        r1->rect.y = r2->rect.y;
        r2->color = tmp.color;
        r2->rect.height = tmp.rect.height;
        r2->rect.y = tmp.rect.y;
    }

    UnloadRandomSequence(seq);
}

From raylib 6.2. The original on GitHub.