Getting input without stopping code (preferably in c++)
roysun (1)

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!

You are viewing a single comment. View All
theangryepicbanana (823)

@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
	input = STDIN.getc.chr
	if input == "\e"
		input << STDIN.read_nonblock(3) rescue nil
		input << STDIN.read_nonblock(2) rescue nil
	STDIN.echo = true
	return input

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 = do
	loop do
		@key = readChar

This will repeatedly wait for keyboard input. The other thread will be your main loop, and will look something like:

main_loop = do
	loop do
		# game stuff

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)