Ocaml: mini SDL example v3
January 24th, 2008This is the 3rd iteration of OCaml SDLCaml game example that I make and learn OCaml at the same time. Changes are:
- keyboard input as it should be (multiple keys at the same time, diagonal speed same as orthogonal)
- ship shoots bullets (ctrl)
- very dumb enemy space ships besides rocks
- a scene record that holds all elements of the scene
Few codebits. Here we define the scene record and a function that creates an empty scene.
type scene = { ship: ship ; bullets : particle list ; rocks : particle list; aliens : particle list; }
let empty_scene = { ship = {poss = (vec2 0 0); shoot_count = 0} ; bullets = [] ; rocks = [] ; aliens = [] }
This functions handle bullets. First updates each bullet and second one looks at a key-map and creates new bullets if needed.
let update_bullets r = { r with pos = r.pos +| r.vel }
let make_bullets bullets keys ship_pos =
match keys.shoot with
| 0 -> bullets;
| _ -> { pos = ship_pos +| vec2 16 16 ; vel = vec2 12 0 ; size = 5 } :: bullets
If you are asking yourself what is +| – it is a vector operator (infix function). We defined it like this.
let ( +| ) a b = {x = a.x + b.x; y = a.y + b.y}
Click here to see the full source
Again thanks a lot to all who commented and suggested code improvements on #ocaml IRC channel. Especially asmanur suggested a lot of great improvements.
