(Windows 7 x64 running Ruby 1.9.3)
Here’s the situation: I’ve made text game in Ruby, and I’m using the traditional gets method to get input from the user. When something is happening in the game (i.e. stuff is being printed to the screen), whatever the user has typed for input gets lost and the user has to continue typing what he/she has typed on a new line. What he/she has originally typed before it got lost is still there, just doesn’t get shown.
If the above didn’t make sense try executing this code, and you’ll see the problem:
Thread.new do
loop do
puts "Hello!"
sleep 2
end
end
Thread.new do
loop do
gets
end
end
What I want is the line printed (in this case "Hello!") to be placed before the line the user is typing into.
I understand that to achieve this I might need to delve into the Windows API. It may even be impossible. But if there’s a way, I’d really like to know.
The most useful libraries for creating interactive terminal programs are Curses and Readline. The former lets you move the cursor anywhere in the terminal, print in colors, create separate “windows”, etc. The latter is essentially a robust alternative to
gets, with command history and autocompletion like inirb.If you want to use Curses with Threads, you can check out my fork of Ruby, which adds this functionality (as well as refactoring the entire curses library).