Subscribe to Martyr2's Programming Underground        RSS Feed

Small High-Low Game Example in Ruby

Icon 8 Comments
Well it has been awhile since I made an entry so I thought I would make one while also answering someone's question. The user named "Cunningham" asked about an example high-low number guessing game to get started with learning Ruby. The game is essentially guessing the random number generated by the computer to see how quick you can guess it. The computer picks a random number in a range of numbers and the user then tries to guess that number. The more turns it takes you, the more you are a loser I guess. :dontgetit:/> But we will cover a simple example of this game in Ruby right here on the Programming Underground!

<Jay-Z's song "Young Forever" but with the words "live forever" replaced with "code forever" theme music>

So as I explained to Cunningham, there are some basic parts essential to the game. We need to be able to ask the user for input, generate a random number hidden from the user, compare the numbers to know if the user is too high, too low or if they guessed the number and do this as many times as necessary until they either quit the game or guess the number and say "no" to playing again.

The example below is really basic and of course doesn't go into the type of validation that it should to make it a real bulletproof example. The one major upgrade would be to evaluate the user's input to make sure it is a number. Either way, to_i is going to return an integer of some sort.

puts "Welcome to a game of high-low."

# A simple flag variable to know if we want to play again.
# It is started with "y" so that the game immediately goes into the first iteration.
playagain = "y"

# We keep playing while they say "y"
while playagain == "y"

    # Our win flag, to know if they won yet
    win = false
    # Generate random number between 1 - 100
    randNum = rand(100) + 1

    puts "Please enter a number (1-100) or -1 to exit: "
    # While we haven't won yet, keep prompting for numbers and comparing.
    while !win
        # Get number from user
        guessedNumber = gets.to_i

        # Wants to quit
        if guessedNumber == -1 then
        # Lets compare our number to computer number
        if guessedNumber > randNum then
            puts "Too high, try again."
        elsif guessedNumber < randNum then
            puts "Too low, try again."
            puts "You win!"
            win = true
    # If we reached here, the game has ended, ask the user if they want to play again.
    puts "Want to play again? (y/n)"
    playagain = gets.chomp!

puts "Thanks for playing!"

The code comments really say it all in this short example. We start the game by first setting up a flag variable to let us know if the user wants to play another game. It is defaulted to "y" so that when we first start it will enter the loop and begin a game. Once in the loop we start another flag, but this one is to let us know if the user won or not. It is defaulted to false because obviously the user hasn't even played yet, so they can't be a winner. Well, unless you are a leet h4x0r in which case you are just full of win!

This is followed by our code to generate our secret computer number on a range from 1 - 100. We then go into the major game loop where we ask the user for a number, see if it is the escape "sentinel" value of -1 and if not, we compare it against the one generated by the computer. If it is too low or too high, we print out the appropriate message and around the loop we go once more. If it is the right number, we print a winner message and set our "win" flag to "true" in which case we escape our while loop and go into asking the user if they wish to play another game. If they choose "y" then they will play again. Otherwise, the games end and we all get back to real business of hacking the CIA or something.

Hope you enjoy the small example and keep in mind... with ruby, you can code the same thing a bajillion different ways and always make it more "compact". Hope this helps you beginner ruby users out there! Thanks for reading! :)

If you want more blog entries like this, check out the official blog over on The Coders Lexicon. There you will find more code, more guides and more resources for programmers of all skill levels!

8 Comments On This Entry

Page 1 of 1


15 October 2010 - 11:22 AM
Have you ever used Ruby for scripting, as in if I were to use it to control certain parts of a game without having to recompile. I am using Lua at the minute which I have no complaints about but I want to try something else :)


15 October 2010 - 03:16 PM
Ruby is a scripting language. When you run "ruby guess.rb" you are just interpreting the file... no executable or link file is made or anything like you would get with compiling. So in that case, yes I have used Ruby for scripting. So since they are not compiled, yes you can switch them out without a recompile of the game. :)


22 October 2010 - 07:43 AM
very nice, how much?


23 October 2010 - 09:37 AM
For you Neo, it is on the house. How can I think of even charging one of my celebrity guest stars of DIC's All My Programmers? That would just be a crime against humanity. ;)


25 October 2010 - 08:18 AM
Awesome blog, I have just started with Liberty Basic making a similar game. Could you please explain why the +1 is added after the random number generation line?


25 October 2010 - 12:48 PM
rand(100) generates a number that's between 0 to 99 (including 0 and 99).
So rand(100)+1 would generate a number between 1 to 100.


25 October 2010 - 01:37 PM
Ah I see, so do programming languages/computers always start counting at zero? Sorry for asking an other question :sweatdrop:


04 November 2010 - 12:47 PM
For things like arrays and other types of indexing yes almost all start at zero. This is because of how the structure is put together in memory (they are linear, even multi-dimensional arrays). myarray[1] is actually considered one unit away from the start of the array. The name "myarray" being the pointer to where the array is located in memory. So myarray[0] is essentially saying "go to where myarray is pointing to and from there grab the first item from the beginning".
Page 1 of 1

September 2020

2021 22 23242526

Recent Entries

Recent Comments

Search My Blog

2 user(s) viewing

2 Guests
0 member(s)
0 anonymous member(s)