From 9833eb520eaa5fd9c965a469cfbe0b651f9207e9 Mon Sep 17 00:00:00 2001 From: zapashcanon Date: Tue, 6 Dec 2022 03:30:16 +0100 Subject: [PATCH] add basic movements --- src/island_client.ml | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/src/island_client.ml b/src/island_client.ml index 187b2dd..1eb731c 100644 --- a/src/island_client.ml +++ b/src/island_client.ml @@ -1,3 +1,5 @@ +let () = Random.self_init () + module Map = struct type background = | Grass @@ -8,12 +10,12 @@ module Map = struct let height = 1000 - let player_pos = ref (500, 500) + let player_pos = ref (20, 3) let m = Array.init width (fun _x -> Array.init height (fun _y -> - if Random.int 1000 = 42 then Water else Grass ) ) + if Random.int 1000 <= 42 then Water else Grass ) ) let get_tile_kind ~x ~y = try m.(x).(y) with Invalid_argument _ -> Black end @@ -82,10 +84,7 @@ let draw_map () = done; let (_ : Jv.t) = Jv.call context "drawImage" - [| papy_bottom - ; Jv.of_int ((width / 2) - (tile_size / 2)) - ; Jv.of_int ((height / 2) - (tile_size / 2)) - |] + [| papy_bottom; Jv.of_int (width / 2); Jv.of_int (height / 2) |] in () @@ -96,6 +95,34 @@ let () = in () +let kb_handler e = + let x, y = !Map.player_pos in + let x, y = + match Jv.to_string @@ Jv.get e "key" with + | "z" -> (x, y - 1) + | "q" -> (x - 1, y) + | "s" -> (x, y + 1) + | "d" -> (x + 1, y) + | _s -> (x, y) + in + let x = max 0 x in + let x = min (Map.width - 1) x in + let y = max 0 y in + let y = min (Map.height - 1) y in + Map.player_pos := (x, y); + draw_map () + +let bind_keys () = + Jv.call window "addEventListener" + [| Jv.of_string "keydown"; Jv.repr kb_handler |] + +let () = + let (_ : Jv.t) = + Jv.call window "addEventListener" + [| Jv.of_string "load"; Jv.repr bind_keys |] + in + () + (* let draw_background () = for x = 0 to tiles_per_w - 1 do