Simultaneous text input/output in a command line game

Discussion in 'Ruby' started by rubyvic, Feb 12, 2006.

  1. rubyvic

    rubyvic Guest

    Hi everyone!

    I=92m 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 =3D rand(11)
    user_guess =3D gets.chomp.to_i

    until user_guess =3D=3D my_number
    if user_guess > my_number
    puts "Too high."
    else my_number > user_guess
    puts "Too low."
    end
    puts "Guess again:"
    user_guess =3D 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:=20
    http://violasong.com/tonyguessinggame.java. In addition to what my=20
    script does, his is able to taunt you with a random message if you don=92=
    t=20
    input any data for 5 seconds :).

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

    Victoria Wang
    rubyvic, Feb 12, 2006
    #1
    1. Advertising

  2. 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
    Timothy Goddard, Feb 12, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Fraser Gordon
    Replies:
    2
    Views:
    363
    John Roth
    Oct 2, 2003
  2. Ernesto
    Replies:
    1
    Views:
    773
    Ernesto
    Feb 1, 2006
  3. Dib Urim
    Replies:
    4
    Views:
    191
    Ben Liddicott
    Nov 23, 2003
  4. Dib Urim
    Replies:
    4
    Views:
    194
    Michele Dondi
    Dec 3, 2003
  5. Replies:
    1
    Views:
    140
    Brian McCauley
    Jul 2, 2005
Loading...

Share This Page