简体   繁体   English

尝试使用图形库Ocaml移动圆

[英]Trying to move a circle using graphics library Ocaml

I am new to ocaml and trying to move a circle using Graphics library of Ocaml. 我是ocaml的新手,并尝试使用Ocaml的图形库移动圆。 This is what I did but it is not working. 这是我所做的,但是没有用。 It should continue for infinite time because of "while true" but it is not working and I am not able to give an Input. 由于“ while true”,它应该持续无限时间,但它不起作用,我无法提供输入。

#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;;

Here is the cause of problems: 这是引起问题的原因:

 Graphics.fill_circle player.(0) player.(1) player.(2);
                                                 ^^^^^^^
                       here should be a double semicolon

Without a second semicolon, the while expression was considered as a part of check function, the proper indentation clarifies this: 如果没有第二个分号,则将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

So, you just defined a function check, and never called it, that's why nothing was happening. 因此,您仅定义了一个功能检查,而从未调用它,这就是什么也没发生的原因。

Also, OCaml is a programming language, so it is better to try to write OCaml programs, not scripts. 另外,OCaml是一种编程语言,因此最好尝试编写OCaml程序,而不是脚本。 Put the following in a graph.ml file, 将以下内容放在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 ()

Compile and run it with the following command 使用以下命令编译并运行

 ocamlbuild -pkg graphics graph.native --

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM