Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!
DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5886 posts at DZone. View Full User Profile

Simple Ruby Text Adventure

04.11.2006
Email
Views: 3210
  • submit to reddit
        This is part of <a href="/snippets/tag/rubyadventure">a series..</a>

# Ultra simple Ruby Text Adventure!
# By Peter Cooper

class Location
        attr_accessor :name, :description, :west, :east, :south, :north

        def initialize(params)
                @name = params[:name]
                @description = params[:description]
        end

        # We have to create our own setter methods to do the mirrored east/west north/south relationships
        def west=(loc)
                @west = loc
                @west.east = self unless @west.east
        end

        def east=(loc)
                @east = loc
                @east.west = self unless @east.west
        end

        def south=(loc)
                @south = loc
                @south.north = self unless @south.north
        end

        def north=(loc)
                @north = loc
                @north.south = self unless @north.south
        end
end



# Create a location
main_room = Location.new( :name => "Central Room" )

# Put a location to the west of the original location
main_room.west = Location.new( :name => "West Room" )

# And to the east..
main_room.east = Location.new( :name => "East Room" )

# Tack some rooms onto the west side
west_room = main_room.west
west_room.north = Location.new( :name => "The North of the West Room" )
west_room.north.north = Location.new( :name => "The Really Far North Room" )


# Now the game logic really begins!

current_room = main_room

catch :end_of_game do
        loop do
                puts "You are in #{current_room.name}. Which direction?"
                instruction = gets
                next_room = case instruction.chomp
                        when "north"
                                current_room.north
                        when "south"
                                current_room.south
                        when "west"
                                current_room.west
                        when "east"
                                current_room.east
                        when "exit"
                                throw :end_of_game
                end
                if next_room
                        current_room = next_room
                else
                        puts "You can't go that way!"
                end
        end
end

puts "Bye bye!"