-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ml
50 lines (46 loc) · 1.61 KB
/
main.ml
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
open Unix
open Board
(*ocamlbuild -pkg js_of_ocaml-lwt.graphics -pkg unix -pkg js_of_ocaml -pkg js_of_ocaml-ppx main.byte*)
let flush_kp () = while Graphics.key_pressed () do
let _ = Graphics.read_key ()
in ()
done
let get_input () : Board.action =
if not (Graphics.key_pressed ()) then Board.NoAction
else let k = Graphics.read_key () in
flush_kp ();
match k with
| ' ' -> Board.HardDrop
| 'z' -> Board.Rotate(false)
| 'x' -> Board.Rotate(true)
| 'c' -> Board.Swap
| 'n' -> Board.Translate(false)
| 'm' -> Board.Translate(true)
| 'b' -> Board.FastDrop
| _ -> Board.NoAction
let rec main board_state frame_time frame_count =
(* Display state here. *)
let next_state = Board.update board_state (get_input ()) frame_count in
if Board.lost_game next_state then begin
flush_kp ();
let _ = Graphics.wait_next_event[Graphics.Key_pressed] in
let init_board = Board.init () in
let start_time = (Unix.gettimeofday ()) in
main init_board start_time 0
end
else
let next_frame_count = if frame_count > 30 then 0 else frame_count + 1 in
(* Advance state by one frame here. *)
(* If less than 25ms have passed, delay until they have. *)
let rec delay () =
let duration = frame_time +. 0.025 -. Unix.gettimeofday () in
if duration > 0.0 then
try
sleepf duration
with Unix.Unix_error (Unix.EAGAIN, _, _) -> delay ()
in delay ();
main next_state (Unix.gettimeofday ()) next_frame_count
let init =
let init_board = Board.init () in
let start_time = (Unix.gettimeofday ()) in
main init_board start_time 0