~/SDL Random Walk Implementation Guide

Apr 14, 2019


A random walk is a process where an entity randomly moves one step at a time. Using SDL in C lets you visualize this process easily. This brief guide shows how to set up and animate a 2D random walk.

Setup SDL in your project following the official SDL tutorial.

Core steps:

  1. Initialize SDL and create a window.
  2. Draw a starting point.
  3. Each frame, randomly choose direction and update coordinates.
  4. Draw the new point.
  5. Repeat until the user closes the window.

Sample C code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <SDL2/SDL.h>
#include <stdlib.h>
#include <time.h>

int main() {
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* win = SDL_CreateWindow("SDL Random Walk",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);

    int x = 320, y = 240;
    srand((unsigned)time(NULL));

    int running = 1;
    SDL_Event event;
    while (running) {
        while (SDL_PollEvent(&event)) if (event.type == SDL_QUIT) running = 0;
        int dir = rand() % 4;
        if (dir == 0) x++; // right
        else if (dir == 1) x--; // left
        else if (dir == 2) y++; // down
        else y--; // up
        SDL_SetRenderDrawColor(ren, 0, 0, 0, 255);
        SDL_RenderClear(ren);
        SDL_SetRenderDrawColor(ren, 255, 255, 255, 255);
        SDL_RenderDrawPoint(ren, x, y);
        SDL_RenderPresent(ren);
        SDL_Delay(10);
    }
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);
    SDL_Quit();
    return 0;
}

This code animates a single pixel performing a random walk in a window. Build and run as per the SDL build guide.

For more custom movement or multiple walkers, adjust the direction logic and store walkers in a struct or array.

See the random walk Wikipedia page for theory and SDL documentation for API details.

Tags: [sdl] [random] [c] [graphics]