1

(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.

2

1 Answer 1

3

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 in irb.

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

3
  • Thanks! I think I'm going to go with Curses because I'm patient and like the sound of it :) Aug 30, 2012 at 12:15
  • Hrm... Readline doesn't solve the problem at all... in the example code I provided, it prints "Hello!" and prints a new line. I was hoping to find a way to get the "Hello!" line to be inserted before the line the Readline prompt was in :\ Aug 30, 2012 at 13:04
  • Yeah, readline doesn't handle cursor position. It only does input. Curses is the way to go but it doesn't support non-blocking reads for threading and it's basically a straight port of the C library (i.e. it's hideous to work with). If you're feeling ambitious, you can check out my curses fork of Ruby on github to compile a better organized, threaded, version of the library.
    – Max
    Aug 30, 2012 at 22:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.