我是ocaml的新手,并尝试使用Ocaml的图形库移动圆圈。这就是我所做的,但它不起作用。由于"虽然为真",它应该无限持续很长时间,但它不起作用,我无法给出输入。
#load "graphics.cma";;
#load "unix.cma";;
Graphics.open_graph " 800x250";;
Graphics.remember_mode true;;
Graphics.set_color 100;;
Graphics.foreground;;
let player = [|40;80;10|];;
Graphics.fill_circle player.(0) player.(1) player.(2);;
let rec check button =
if button = 'w'
then
player.(0) <- player.(0) + 50;
Graphics.fill_circle player.(0) player.(1) player.(2);
while true do
let s = Graphics.wait_next_event [Graphics.Button_down; Graphics.Key_pressed]
and bo=Graphics.key_pressed ()
in if not bo then check s.Graphics.key;
done;;
以下是问题的原因:
Graphics.fill_circle player.(0) player.(1) player.(2);
^^^^^^^
here should be a double semicolon
如果没有第二个分号,while 表达式被视为作为check
功能的一部分,正确的缩进澄清了这一点:
let rec check button =
if button = 'w'
then
player.(0) <- player.(0) + 50;
Graphics.fill_circle player.(0) player.(1) player.(2);
while true do
let s = Graphics.wait_next_event [Graphics.Button_down; Graphics.Key_pressed]
and bo=Graphics.key_pressed ()
in if not bo then check s.Graphics.key;
done
所以,你只是定义了一个函数检查,从来没有调用过它,这就是为什么什么都没有发生。
此外,OCaml是一种编程语言,因此最好尝试编写OCaml程序,而不是脚本。将以下内容放入graph.ml
文件中,
let player = [|40;80;10|]
let init () =
Graphics.open_graph " 800x250";
Graphics.remember_mode true;
Graphics.set_color 100;
Graphics.fill_circle player.(0) player.(1) player.(2)
let rec check button =
if button = 'w'
then
player.(0) <- player.(0) + 50;
Graphics.fill_circle player.(0) player.(1) player.(2)
let run () =
while true do
let s = Graphics.wait_next_event [
Graphics.Button_down;
Graphics.Key_pressed
] in
let bo = Graphics.key_pressed () in
if not bo then check s.Graphics.key;
done
let () =
init ();
run ()
使用以下命令编译并运行它
ocamlbuild -pkg graphics graph.native --