OCaml - 保持视觉计时器

时间:2015-04-02 12:57:45

标签: ocaml

我正在使用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 () 
    ;;

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

我到底做错了什么?

1 个答案:

答案 0 :(得分:2)

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

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

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

您可能会发现async_graphics很有趣,它是Async库的集成,与Lwt和Graphics模块非常接近。它甚至在Real World OCaml

中提到过