首页 > 解决方案 > Ocaml 图形事件

问题描述

我在这里创建了这个函数来从键盘获取事件:

let get_move() : string =
let e = Graphics.wait_next_event [Key_pressed] in
let ke = if e.keypressed then Printf.sprintf "%c" e.key else "" in
ke;;

我正在制作俄罗斯方块,所以我希望这个功能在等待事件时可以关闭。

目前,当它等待一个事件时,它会“暂停”循环。我应该怎么办 ?

标签: ocaml

解决方案


我从未使用过Graphics自己,但仅通过阅读文档,我建议将其loop_at_exitPoll事件一起使用:

Graphics.loop_at_exit [Key_pressed; Poll] begin fun e ->
  if e.keypressed then
    ...
  else
    ...
end

或者用你自己的循环key_pressed来检查你是否可以read_key在没有阻塞的情况下调用:

let get_move () : char option =
  if Graphics.key_pressed () then
    Some (Graphics.read_key ())
  else
    None

推荐阅读