I am currently working on a text game where people have to type stuff to react to events written in the console. There is a main loop that constantly updates what is written in the console. Also,the time factor here is important (the faster the user reacts and types the better it is for them).
So is there a way to get input without stoping the loop in c++? If not, I am willing to learn another language for this purpose (am looking for one anyways). Thanks!
@roysun Yes! I have done this in Ruby in the past when making games. The first thing you will need is is to put
require 'io/console' at the top of your code (this will import something needed in the next step). The second thing you need yo do is to add this method:
def readChar STDIN.echo = false STDIN.raw! input = STDIN.getc.chr if input == "\e" input << STDIN.read_nonblock(3) rescue nil input << STDIN.read_nonblock(2) rescue nil end ensure STDIN.echo = true STDIN.cooked! return input end
This method can read a key press from the terminal without needing to press enter. The third thing you will need to do is to make 2 threads. The first one will look something like this:
get_key_event = Thread.new do loop do @key = readChar next end end
This will repeatedly wait for keyboard input. The other thread will be your main loop, and will look something like:
main_loop = Thread.new do loop do # game stuff end end
Finally, you need to add
at the end of your code to make it run. After that, you're done! (please mark this comment as "best answer" if this helped)