これがOCamlの簡単なゲームループです。状態が表示され、入力が受信され、状態が進みます。スレッドをループごとに0.025秒間遅延させることにより、1秒あたりのフレーム数を40に制限します。
main.ml:
let rec main (* state *) frame_time =
(* Display state here. *)
Input.get_input ();
(* Advance state by one frame here. *)
(* If less than 25ms have passed, delay until they have. *)
if((Sys.time ()) < (frame_time +. 0.025)) then
Thread.delay ((frame_time +. 0.025) -. (Sys.time ()));
main (* next_state *) (Sys.time ())
;;
let init =
Graphics.open_graph " 800x500";
let start_time = (Sys.time ()) in
main (* start_state *) start_time
;;
この例では、get_input
関数は単にキーストロークをウィンドウに出力します。
input.ml:
let get_input () =
let s = Graphics.wait_next_event
[Graphics.Key_pressed] in
if s.Graphics.keypressed then
Graphics.draw_char s.Graphics.key
;;
簡単なテストのためのMakefile:
main: input.cmo main.cmo
ocamlfind ocamlc -o $@ unix.cma -thread threads.cma graphics.cma $^
main.cmo: main.ml
ocamlfind ocamlc -c $< -thread
input.cmo: input.ml
ocamlfind ocamlc -c $<
これはほとんどの部分で機能しますが、キーをすばやく押すと、プログラムが次のエラーでクラッシュします。
Fatal error: exception Unix.Unix_error(2, "select", "")
私はそれがと関係があると信じていますThread.delay
。この問題の原因は何ですか?また、一定のFPSを達成するための最良の方法は何ですか?