Forum: Ruby Simultaneous text input/output in a command line game

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
rubyvic (Guest)
on 2006-02-12 08:08
(Received via mailing list)
Hi everyone!

I?m currently learning Ruby, and have made this simple number guessing
game:
____________________________
puts "I'm thinking of a number from 0 to 10. What's your guess?"

my_number = rand(11)
user_guess = gets.chomp.to_i

until user_guess == my_number
if user_guess > my_number
puts "Too high."
else my_number > user_guess
puts "Too low."
end
puts "Guess again:"
user_guess = gets.chomp.to_i
end

puts "Yep, it was " + my_number.to_s + ". You win!"
____________________________

A friend of mine wrote a Java version which you can see here:
http://violasong.com/tonyguessinggame.java. In addition to what my
script does, his is able to taunt you with a random message if you don?t
input any data for 5 seconds :).

I want to try adding that functionality to my script, and am wondering
if it's possible in Ruby ? to print a message every x seconds *while*
it's waiting for you to input something. If someone could point me in
the right direction, that would be much appreciated!

Victoria Wang
Timothy G. (Guest)
on 2006-02-12 12:38
(Received via mailing list)
As a method without having to worry about threads you could also use:

require 'timeout'

messages = ["What are you waiting for?", "I don't have all day.", "When
I said 'take your time', I didn't mean this long!", "Hurry up and enter
a value!"]

s = nil
until s
  begin
    Timeout::timeout(5) do
      puts "Enter a value: "
      s = gets
    end
  rescue Timeout::Error
    puts messages[rand(messages.length).to_i]
  end
end
Mark V. (Guest)
on 2006-02-12 20:26
(Received via mailing list)
On 2/12/06, Timothy G. <removed_email_address@domain.invalid> wrote:
>   begin
>     Timeout::timeout(5) do
>       puts "Enter a value: "
>       s = gets
>     end
>   rescue Timeout::Error
>     puts messages[rand(messages.length).to_i]
>   end
> end

I thought this was a good example, so I tried running your code. It
doesn't work using the latest One-Click Installer for Windows (1.8.4).
The timeout never occurs. It does however work under Fedora Core Linux
using Ruby 1.8.4.

I wonder if this is a Ruby problem or a One-Click Installer problem.
This topic is locked and can not be replied to.