這是OCaml中的一個簡單遊戲循環。顯示狀態,接收輸入,狀態爲高級。通過延遲線程每個循環0.025秒,每秒幀數限制爲40。OCaml中的線程延遲和鍵盤事件
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 [email protected] 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的最佳方式是什麼?
Jeffrey對所有帳戶都是正確的。您可以獲得有關Thread的更多信息。延遲[這裏](http://ocamlunix.forge.ocamlcore.org/threads.html#htoc63)。 –