Created
March 19, 2014 18:17
-
-
Save malpinder/9647910 to your computer and use it in GitHub Desktop.
Refactoring excercise. A version of adventure.rb that has been refactored to a degree.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I'm less sorry but still a bit sorry. | |
class Adventure | |
def rooms | |
{ | |
room_one: "You are in a maze of twisty little passages, all alike", | |
room_two: "It is dark here. You are likely to be eaten by a grue.", | |
room_three: "It is dark here." | |
} | |
end | |
def room_for_direction(direction) | |
if @location == :room_one && direction == "SOUTH" | |
:room_two | |
elsif @location == :room_two && direction == "NORTH" | |
:room_one | |
elsif @location == :room_two && direction == "EAST" | |
:room_three | |
elsif @location == :room_three && direction == "WEST" | |
:room_two | |
else | |
nil | |
end | |
end | |
def move_into(location) | |
@location = location | |
puts rooms[@location] | |
end | |
def kind_of_direction?(result) | |
["NORTH", "SOUTH", "EAST", "WEST"].include?(result) | |
end | |
def in_a_room_with_a_grue? | |
@location == :room_three | |
end | |
def puts_help | |
puts "Here are the accepted commands:" | |
puts "NORTH to go NORTH" | |
puts "SOUTH to go SOUTH" | |
puts "EAST to go EAST" | |
puts "WEST to go WEST" | |
puts "INVENTORY to see what you are carrying" | |
puts "LOOK to see what you can see" | |
puts "PICK UP to pick something up" | |
end | |
def puts_inventory | |
puts "You have a lantern. It has no oil in it." | |
if @hat_on_head | |
puts "A jaunty hat rests upon your head." | |
end | |
end | |
def run | |
@location = :room_one | |
puts rooms[@location] | |
6.times do | |
puts "What do you do?" | |
result = gets.chomp | |
if result == "HELP" | |
puts_help | |
elsif kind_of_direction?(result) | |
room = room_for_direction(result) | |
if room | |
move_into(room) | |
else | |
puts "You can't go that way!" | |
end | |
elsif result == "INVENTORY" | |
puts_inventory | |
elsif result == "LOOK" && !@hat_on_head | |
puts "You can see a hat on the ground." | |
else | |
puts "I don't understand that." | |
end | |
if in_a_room_with_a_grue? | |
puts "You have been eaten by a grue!" | |
return | |
end | |
end | |
puts "You have died of starvation." | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment