Created
December 19, 2017 20:26
-
-
Save ynonp/fb1f00b57ad2fbf3ca726bc363cb6dbc to your computer and use it in GitHub Desktop.
advent of code day19
This file contains hidden or 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
class Maze | |
attr_accessor :data | |
def initialize(stdin) | |
self.data = [] | |
stdin.each_line do |line| | |
data.push(line.chomp.split('')) | |
end | |
end | |
def row(i) | |
data[i] | |
end | |
def val_at(point) | |
data[point.y][point.x] || ' ' | |
end | |
end | |
class Point | |
attr_accessor :x, :y, :game | |
def initialize(game, x, y) | |
self.x = x | |
self.y = y | |
self.game = game | |
end | |
def valid_move? | |
game.val_at(self) != ' ' | |
end | |
def empty? | |
game.val_at(self) == ' ' | |
end | |
def letter? | |
game.val_at(self) =~ /[A-Z]/ | |
end | |
def val | |
game.val_at(self) | |
end | |
end | |
class Game | |
attr_accessor :maze, :pos, :dir, :letters, :steps | |
def val_at(pos) maze.val_at(pos) end | |
def initialize | |
self.maze = Maze.new(ARGF) | |
self.steps = 1 | |
self.pos = find_start_position | |
self.dir = find_direction | |
self.letters = [] | |
end | |
def up() Point.new(self, pos.x, pos.y - 1) end | |
def down() Point.new(self, pos.x, pos.y + 1) end | |
def left() Point.new(self, pos.x - 1, pos.y) end | |
def right() Point.new(self, pos.x + 1, pos.y) end | |
def find_start_position | |
x = maze.row(0).find_index { |val| val && val != ' ' } | |
y = 0 | |
Point.new(self, x, y) | |
end | |
def find_direction | |
[ | |
dir != method(:up) && method(:down), | |
dir != method(:down) && method(:up), | |
dir != method(:left) && method(:right), | |
dir != method(:right) && method(:left) | |
].find { |d| d && d.call.valid_move? } | |
end | |
def step | |
next_sqr = dir.call | |
if next_sqr.valid_move? | |
self.pos = dir.call | |
letters << next_sqr.val if next_sqr.letter? | |
self.steps += 1 | |
return | |
end | |
# hit a wall | |
self.dir = find_direction | |
unless dir | |
puts "Found: #{letters}. Took #{steps} steps" | |
raise 'Game Over' unless dir | |
end | |
end | |
end | |
g = Game.new | |
loop { | |
g.step | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment