Make Your First Text Adventure in Ruby

Objects and Messages

Ruby is what is known as an "object oriented" programming language. This means that it concerns objects and the messages that they send to eachother.

In ruby, everything is an object.

1.is_a? Object
# => true 
"hello world".is_a? Object
# => true 
Fixnum.is_a? Object
# => true

In ruby, even nothing is an object!

nil.is_a? Object
# => true

Have a look at this code:

"Hello, world!".is_a? Object

In the above snippet, we are sending the message "is_a?" to the object "hello world". Objects may respond to a message.

"hello world".is_a? Object
# => true

They may not.

"hello world".you_dont_know_me
NoMethodError: undefined method `you_dont_know_me' for "hello world":String

The ruby programming language provides you with a stunning array of objects out of the box. Your task as a designer is to decide which of these you need and which new objects you will need to create to fulfil the needs of your game. If you have been thinking about your game so far, you will probably have an idea.

What nouns have surfaced in your thoughts repeatedly? Do you find yourself mentally repeating the phrase "the x does this, the x does that"? It is not unlikely that x will become an object unto itself in your application. The same applies to verbs. If there is a recurring verb, it may end up as one of the messages you pass from one object to another.

Objects of Your Own

Unless your game is supremely simple, you will soon outgrow the array of objects provided to you by the language. When this time comes, you have no choice but to roll up your sleeves and create your own objects. The most common way of achieving this is by creating a class.

class Player
end

That's all there is to it. You can now create Player objects whenever you desire!

player = Player.new
player.class
# => Player

This is great, but our player doesn't currently do very much. We have an object, but without the ability to send or receive messages, we have nothing. Let's give our player a name.

class Player
  def name
    @name
  end

  def name=(new_name)
    @name = new_name
  end
end

Our Player class now responds to two messages. It responds to name and name=. Instances of the Player class can now respond to inquiries regarding the content of the @name instance variable. They can also take a new value and assign the value of @name to the received value.

You now know about the objects that describe your application and the messages that define its behaviour. Next, we will look at the core component of our game: the game loop.

Work Prompts

  • What objects do you think you might need? The chances are the first one you thought of was player! I showed you how to create that. What others might you want?
  • What messages do you think you might send? If you have a player object, you might want to tell it to move.