Skip to content

Instantly share code, notes, and snippets.

@sczizzo
Created December 12, 2011 16:30
Show Gist options
  • Save sczizzo/1468102 to your computer and use it in GitHub Desktop.
Save sczizzo/1468102 to your computer and use it in GitHub Desktop.
Simple dungeon map reader and walker
#!/usr/bin/env ruby -w
class Array
def second
self[1]
end
end
class Symbol
def to_i
{:north => -1, :south => 1, :east => 1, :west => -1}[self]
end
end
class Walker
attr_reader :raw_dungeon, :dungeon
def initialize raw_dungeon
@raw_dungeon = raw_dungeon
@dungeon = @raw_dungeon.lines.map(&:chars).map(&:to_a)
@position = find_me
end
def find_me
@dungeon.map do |line|
line.to_a.index '&'
end.each_with_index do |line, i|
unless line.nil?
return [i, line.to_i]
end
end
return nil
end
def can_step? direction
next_step = nil
if direction == :north or direction == :south
next_step = @dungeon[@position.first + direction.to_i][@position.second]
elsif direction == :east or direction == :west
next_step = @dungeon[@position.first][@position.second + direction.to_i]
end
return true if next_step == ' ' # next_step.steppable?
return false
end
def step direction
if can_step? direction
@dungeon[@position.first][@position.second] = ' '
if direction == :north or direction == :south
@position = [@position.first + direction.to_i, @position.second]
elsif direction == :east or direction == :west
@position = [@position.first, @position.second + direction.to_i]
end
@dungeon[@position.first][@position.second] = '&'
return @position
end
return nil
end
def look_at_dungeon
puts @dungeon.join
end
end
dungeon = <<-eodungeon
######################
# & #
# #
# @ #
######################
eodungeon
i = Walker.new dungeon
i.look_at_dungeon
9.times do
%w( south east ).map(&:to_sym).each do |direction|
if i.can_step? direction
i.step direction
puts '---'
puts i.look_at_dungeon
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment