问题
Edit. I am working in a Windows environment.
I want to write a simple game in console output with OCaml. I need to be able to use a 'read_key' function. But :
- The graphics module throws an error :
Exception: Graphics.Graphic_failure "graphic screen not opened".
But I do not want to open the graphic window. - The function
read_line
forces the user to press "return" after every key press...
回答1:
It is not possible to implement such function using pure OCaml. You will need to call to platform specific libraries. It is not an OCaml problem, this is the same for other languages, including python, java, c, etc. Actually, interacting with a terminal in a portable way is kind of rocket science. Mostly for historical reasons.
I suspect, that you don't want to get into such troubles, so I can suggest few easy solutions:
Use OCamlSDL library, - you're developing a game, and SDL is for games
Use Graphics module, yes you will need to open the graphic window, and your game will not be a pure console... but maybe this is not a big issue. Also, you can make a black background and emulate a terminal :)
Install Cygwin version of OCaml. You will get a unix-like environment, and
Unix.tc_*
will start to work.Switch to a normal operating system. Where by normal I mean Unix-like. You can use virtual machine, or containers, like Docker, for a first time.
来源:https://stackoverflow.com/questions/36089021/ocaml-read-pressed-key-without-graphical-window