OCaml - 保持视觉计时器

OCaml - Keeping a visual timer

我正在使用 Graphics library.

在 OCaml 中制作数独游戏

我正在尝试在顶部添加一个计时器,以便玩家可以看到他解决数独问题需要多长时间。我环顾四周, Lwt library 似乎就是我要找的东西。

为了画定时器我写了一个函数draw_time,函数的内容太长而且不重要,但是它有这样的结构:

let rec hello () = 
    Lwt.bind (Lwt_unix.sleep 14400.) 
       (fun () -> print_endline "Hello, world !"; hello ())
Lwt.async (hello)

我已经对其进行了测试,该功能确实可以正常工作。

我游戏的主循环是这样的:

let main_loop gs f_init f_end f_key f_mouse = 

    f_init;
        let timer = draw_time () in
        try 
            while true do
                try 
                    if gs.completed <> true then
                        let event = Graphics.wait_next_event event_types in
                            if event.Graphics.keypressed then 
                                f_key event.Graphics.key
                            else if event.Graphics.button then 
                                f_mouse event.Graphics.mouse_x event.Graphics.mouse_y               
                with 
                | _ -> raise End
            done
        with 
        | End  -> f_end () 
    ;;

这似乎不起作用。该程序仅在我关闭 window(和程序)时执行 draw_time,而不是在 window 打开并且应该绘制计时器时执行。

我到底做错了什么?

为了 运行 Lwt 程序,您需要启动 main loop,它将处理您的线程,

let () = Lwt_main.run (Lwt_io.printl "Hello, world!")

Lwt 有将 Lwt 主循环集成到 Glib 中的代码。但是,据我所知,图形模块没有这样的集成。

您可能会发现 async_graphics interesting, it is an integration of the Async library, that is quite near to Lwt with Graphics module. It was even mentioned in Real World OCaml