Ask coding questions

← Back to all posts
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!

Answered by theangryepicbanana (865) [earned 5 cycles]
View Answer
roysun (1)

@theangryepicbanana Oh, just got the idea and started it, but realized that I was stuck here.... I could link it but there's literally nothing there....

theangryepicbanana (865)

@roysun ok well after looking, it seems as though you will need to use something like conio.h to get "unbuffered" input

roysun (1)

@theangryepicbanana Unfortunately, it seems that conio.h does not work on with c++. Some source say it is not compatible with c++ while other forums say they are usable in c++ (with windows). Do you know if there is anything that can accomplish this in Ruby? I started coding by learning a bit of ruby.

theangryepicbanana (865)

@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)

roysun (1)

@theangryepicbanana Thanks! I'm going to dive back into my ruby pdf and test it out!