2015-04-02 84 views
0

我正在与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,而不是当窗口打开并且应该绘制定时器时执行draw_time。

我究竟做错了什么?

+0

中提到它有点不足,请显示'draw_time'的定义。 – Drup 2015-04-02 14:37:08

+0

我不认为这是必要的,因为问题不在draw_time。如果我打电话给你,而不是draw_time,那就是完全相同的问题。该程序开始打印“你好,世界!”我每秒都会关闭程序,而不是在程序运行时关闭程序。 – 2015-04-02 16:06:07

回答

2

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

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

LWT有代码,将LWT主回路融入油嘴。但据我所知,Graphics模块没有这种集成。

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