Note that there are some explanatory texts on larger screens.

plurals
  1. POThread delay and keyboard events in OCaml
    text
    copied!<p>Here is a simple game loop in OCaml. The state is displayed, input is received, and the state is advanced. The number of frames per second is contrained to 40 by delaying the thread for 0.025 seconds each loop.</p> <p>main.ml:</p> <pre class="lang-ml prettyprint-override"><code>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 ()) &lt; (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 ;; </code></pre> <p>For this example, the <code>get_input</code> function simply prints keystrokes to the window.</p> <p>input.ml:</p> <pre class="lang-ml prettyprint-override"><code>let get_input () = let s = Graphics.wait_next_event [Graphics.Key_pressed] in if s.Graphics.keypressed then Graphics.draw_char s.Graphics.key ;; </code></pre> <p>Makefile for easy testing:</p> <pre><code>main: input.cmo main.cmo ocamlfind ocamlc -o $@ unix.cma -thread threads.cma graphics.cma $^ main.cmo: main.ml ocamlfind ocamlc -c $&lt; -thread input.cmo: input.ml ocamlfind ocamlc -c $&lt; </code></pre> <p>This works for the most part, but when keys are pressed very quickly, the program crashes with this error:</p> <p><code>Fatal error: exception Unix.Unix_error(2, "select", "")</code></p> <p>I believe it has something to do with <code>Thread.delay</code>. What is causing this issue, and what is the best way to achieve a constant FPS?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload