Demo:
Procedural Ruby

A walkthrough of a simple game coming together in Ruby.

Scroll down...

Content

Resources

Comments

Until now, you've mostly been building self-contained scripts. During the next several units, we'll be applying OOP principles and turning your scripts into full-fledged programs. To start bridging the gap, we'll start out working through a procedural games script.

In this brief demo, we'll walk through building a simple children's game using procedural Ruby. We'll take input from the Command Line and display our results to the same. Our goal is to show you simple game mechanics, Ruby scripting, and user input.

We'll build this game in a procedural style, meaning we won't make use of classes or object instances along the way. That's coming up soon enough!

Higher/Lower

The game we're playing is simple: The computer will pick a random number from 1 to 10. You have 3 guesses. After each guess, the computer will tell you if you've won or if the hidden number is higher or lower than your guess.

Initial Planning

Because this is a procedural problem, we just need to think through what's happening from the top and then work our way through it. In this case:

Player starts the game (script)

The game randomly determines the hidden number

Player is prompted for the first guess

The guess is checked against the hidden number

If the guess is right, the game ends. Otherwise player gets feedback about the guess.

Player is prompted for the second guess

The guess is checked against the hidden number

The guess results are again presented

Player is prompted for the third guess

The guess is checked against the hidden number

The guess results are again presented

If the number hasn't been guessed, the game ends in a loss.

Coding it Up

We'll start by putting together the basic linear procedure in one jumbled script. You'll likely be able to jump right to using loops and methods... we've done this for the sake of being explicit.

See the video below (6:37):

Note: If it's your style, these videos can be accelerated to 1.25, 1.5 or 2x speed. See the options icon in the player to do so.

Extensions

There are a number of different extensions to this and you're welcome to try them out on your own. One typical pattern would be checking user input. You might build a loop around your input until it's valid:

Wrapping Up

This is just a bite-sized script to get you thinking about procedural Ruby. In this case, we were very (needlessly) explicit about doing things the long way. In reality, you'll almost certainly see the need for a loop or a method without having to actually copy-paste code first. But don't feel like you need to perfect the code going in -- you'll want to have a plan but often it won't become fully clear until you've actually started working.