Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # works on things turning and moving
- class Grid
- attr_accessor :x, :y
- def at(x, y)
- self.x = x
- self.y = y
- end
- def coordinates
- [x, y]
- end
- def advance(bearing)
- self.y += 1 if bearing == :north
- self.y -= 1 if bearing == :south
- self.x += 1 if bearing == :east
- self.x -= 1 if bearing == :west
- end
- end
- # can orient and move
- class Robot
- DIRECTIONS = [:north, :east, :south, :west].freeze
- attr_accessor :bearing, :grid
- def initialize
- @grid = Grid.new
- end
- def place(args = {})
- x = args[:x]
- y = args[:y]
- direction = args[:direction]
- at(x, y)
- self.bearing = direction
- self
- end
- def orient(direction)
- raise ArgumentError unless DIRECTIONS.include? direction
- self.bearing = direction
- end
- def turn_right
- current_index = DIRECTIONS.index(bearing)
- next_indext = (current_index + 1) % 4
- self.bearing = DIRECTIONS[next_indext]
- end
- def turn_left
- current_index = DIRECTIONS.index(bearing)
- next_indext = (current_index - 1)
- self.bearing = DIRECTIONS[next_indext]
- end
- def at(x, y)
- grid.at(x, y)
- end
- def coordinates
- grid.coordinates
- end
- def advance
- grid.advance(bearing)
- end
- end
- # handles instructions for robot
- class Simulator
- DICTIONARY = { 'L' => :turn_left,
- 'R' => :turn_right,
- 'A' => :advance }.freeze
- def instructions(command_string)
- command_string.chars.map do |letter|
- DICTIONARY[letter]
- end
- end
- def place(robot, args = {})
- robot.place(args)
- end
- def evaluate(robot, command_string)
- instructions = instructions(command_string)
- instructions.each do |instruction|
- robot.send(instruction)
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement