sdl3_the-functional-way

This sdl3 interface can be used with a functional loop.

open Sdl3

let () =
  Sdl3.init ();
  let w, r = Render.create_window_and_renderer (340, 220) in

  let rec aux i =
    Printf.printf "> %d\n%!" i;
    Render.set_draw_color r (20, 80, 210);
    Render.clear r;
    Render.present r;
    Timer.delay 1000;
    if i >= 6 then (Sdl3.quit (); exit 0)
    else aux (succ i)
  in
  aux 0
;;

This loop will run about 6 times, with a pause of one second, at each step.

Render.clear clears the drawing area with a selected color.

Render.present should be called at the end of every frame, after each sequence of drawing commands.

Timer.delay 1000; will make a pause for 1 second (1000 milliseconds).

You can try to select random values between 0 and 255 (included), for Render.set_draw_color, with Random.int 256.


the-event-loop

open Sdl3

let () =
  Sdl3.init ();
  let w, r = Render.create_window_and_renderer (340, 220) in

  let rec event_loop () =
    let e = Events.poll_event () in
    match e with
    | None -> ()
    | Some ev ->
        match ev with
        | Quit_event -> Sdl3.quit (); exit 0
        | _ -> event_loop ()
  in
  let rec aux () =
    event_loop ();
    Render.set_draw_color r (20, 80, 210);
    Render.clear r;
    Render.present r;
    Timer.delay 600;
    aux ()
  in
  aux ()
;;

Why Events.poll_event should be called in a loop?

Because several events can arrive, at each step of the main game-loop (aux).

The event-loop should only return when poll_event returns None.

Quit_event is the event that occures when the user clics on the little cross of the window handle at the top-right.


place-holders

You can draw the elements of your game with place-holders, if you don't have graphics yet.

You can draw rectangles and squares first. Here is how to fill this shape, and draw its strokes:

  Render.set_draw_color r (60, 120, 250);
  Render.fill_rect r (x, y, 20, 20);
  Render.set_draw_color r (2, 20, 120);
  Render.draw_rect r (x, y, 20, 20);

graphics_one-sprite

  let s = Surface.load_bmp ~file:"./one-sprite.bmp" in
  let t = Texture.create_texture_from_surface r s in

  let draw_sprite (x, y) =
    Render.render_texture r t (0, 0, 20, 20) (x, y, 20, 20);
  in

One image, with one sprite, with size: (20, 20), to be drawn at position: (x, y).

(0, 0), is the position of the rectangle, in the source image.

It is drawn, with the same size, (w, h), than in the original image.


graphics_sprite-atlas

Group all the sprites, in a single atlas.

  let s = Surface.load_bmp ~file:"./graphics-atlas.bmp" in
  Surface.set_color_key s (255, 0, 255);
  let t = Texture.create_texture_from_surface r s in

  let draw_sprite pos sprite =
    Render.render_texture r t (src_rect) (dst_rest);
  in

The color-key is the color to be used as transparent-pixel.


the-end