Tuesday, November 11, 2008

My First Ruby Code

So I've written my first bit of Ruby code. Allow me to bore you with the story.

The other day my son and I were checking out the local thrift store. The Boy came across a board game that appeared to be brand new. The cards were still wrapped in cellophane, the cardboard chits were unpunched, and it was only $1.50.

He bought the game and raced home. He punched out the bits, was excited to play when much to his chagrin, he realized that there were two decks of cards missing. The game was incomplete. He was devastated.

What is a Dad to do? Well, I hopped onto boardgamegeek, posted a question about what was in the decks in the forum, and within 3 hours, I had the answer to my question. We now knew what the other decks comprised of.

My son recreated one of the decks with a bit of cardstock and our printer. That deck was basicly a ticket system, that moved you around the board. But the other deck was a bit more tricky. There were 26 cards, divided up into four types of flowers; 8 blue, 7 orange, 6 red, and 5 green. The idea was you flip over 3 cards, and then if you turned over two or three of the same color, then you get more or less points.

Being the geek that I am, and having just read about SmallBasic, the two of us sat down and wrote a small script that figured the chances of pulling out each card, and then displayed the appropriate card. Small Basic was very simple and easy to get into, but I've been meaning to poke around Ruby for quite some time. In the end, I rewrote it in Ruby, just to say I had done it.

Ruby ended up being easier than I thought, and very clean. I'll post both scripts below, for you geeks who care about things like that. Since I'm a complete and total novice, I'd be more than interested in any feedback from 'pros' out there. Is there a simpler or more elegant way to do it?

Small Basic

num = 0
num = (num + 1)

a = Math.GetRandomNumber(100)
While (num < 4)

If (a <32)
Then TextWindow.WriteLine("Blue")
Goto start

If (a < 59) Then
Goto start

If (a < 81) Then TextWindow.WriteLine("red")
Goto start

Goto start





round = 0
while round < 3 do
number = rand(100)

if number < 32 then puts "Blue" end
if number > 31 && number < 59 then puts "Orange" end
if number > 58 && number < 82 then puts "Red" end
if number > 81 then puts "Green" end
round += 1


Josi said...

Um, I cut out addition flashcards for my daughter and counted them to make sure I didn't lose any on the floor. That's got to count for something, right? You're an impressive father, geek or not

Seth said...

I would use the "elsif" statement after the first if. You can learn more here.