From a question about DSLs.
See:
The code in the Adventure::Room
class could be made a little cleaner using a gem like fattr
From a question about DSLs.
See:
The code in the Adventure::Room
class could be made a little cleaner using a gem like fattr
class Adventure | |
attr_reader \ | |
:current_room, | |
:rooms | |
class Room | |
attr_accessor \ | |
:exits, | |
:long, | |
:short | |
def initialize( short , long , exits ) | |
@short = short | |
@long = long | |
@exits = exits | |
end | |
def long( val = false ) | |
if val | |
self.long = val | |
else | |
self.long | |
end | |
end | |
def short( val = false ) | |
if val | |
self.short = val | |
else | |
self.short | |
end | |
end | |
def door(direction, destination, &block) | |
if exits.has_key?( direction ) | |
puts "Error: Room #{@current_room} already has an exit defined in #{direction}" | |
else | |
exits[ direction ] = {:where => destination, :condition => block_given? ? block : true} | |
end | |
end | |
end | |
def initialize | |
@rooms = Hash.new | |
@current_room = nil | |
end | |
def room(reference, &block) | |
@current_room = | |
if @rooms.has_key?(reference) | |
puts "Error: Room #{reference} has already been defined" | |
@rooms[ reference ] | |
else | |
@rooms[ reference ] = Room.new '' , '' , Hash.new | |
end | |
@current_room.instance_eval( &block ) if block_given? | |
end | |
end | |
class Object | |
def adventure(&block) | |
a = Adventure.new | |
a.instance_eval( &block ) if block_given? | |
end | |
end | |
adventure do | |
room :cave do | |
short "You are in a large cave" | |
long "You are in a very large cave" | |
door :west, :another_cave | |
door :east, :exit do | |
if player.has_item(:key) | |
true | |
else | |
false | |
end | |
end | |
end | |
room :another_cave do | |
short "A cave" | |
long "Oh great ... another cave" | |
door :east, :cave | |
end | |
room :exit do | |
short "Freedom" | |
long "Freeeeeeeeeeedom!!!!!!" | |
door :west, :cave | |
end | |
require 'pp' | |
pp @rooms | |
end |