Ocaml: mini SDL example 2
January 13th, 2008Images residue in an array now, we passed them around individually before. This is how we load and free them.
let load_images () =
[|
load_image "data/background.bmp" ;
load_image "data/ship.bmp" ;
load_image "data/rock1.bmp" ;
|]
;;
let free_surfaces images = Array.iter (function(img) -> free_surface img) images;;

Input is better handeled now. Ship moves while you hold the appropriate arrow key down. But it is not as it should be at the end. If you start pressing more than 1 keys at once it won’t work as expected.
Rocks have been added. They are records that residue in a list. Those two functions are used for drawing and calculating/making the new rock. The power that OCaml gives you with records shows here a little.
let draw_rocks screen images (r:particle) =
let { pos = p } = r in apply_surface p images.(2) screen;;
let update_rocks (r:particle) =
{ r with pos = if r.pos.x > (-r.size) then r.pos +| r.vel else (vec2 650 r.pos.y) } ;;
That +|is an operator we defined. It represents the addition of two vectors. Vectors and this operator are defined in 3 lines of code.
type vec2 = { x: int; y: int };;
let vec2 x y = {x=x; y=y};;
let ( +| ) a b = {x = a.x + b.x; y = a.y + b.y}
Click to look at the source code.
I warn you however. I am learning OCaml as I type this and this is the first time I use SDL also. If you notice any mistakes or stupidities let me know. I am still proud (and surprised) that there is no mutable or global stuff in the code. Basically one chat on the IRC hinted me how I should think in FP at all, much better than anything I read before, and it worked so far. I intend to post that IRC chat here soon.
Thanks to bluestorm on #ocaml IRC for proposing few improvements to the code. It has been updated.
