class DallasMarsRover::Rover
The “physical” rover class
Attributes
commander[R]
direction[R]
pos_x[R]
pos_y[R]
zone[R]
Public Class Methods
new(commander, zone)
click to toggle source
Load start position and direction @param [Commander] commander object @param [Zone] zone object @return [Rover] rover object
# File lib/mars_rover/rover.rb, line 9 def initialize(commander, zone) @commander = commander @zone = zone @pos_x = commander.start_point[:x].to_i @pos_y = commander.start_point[:y].to_i @direction = commander.start_direction end
Public Instance Methods
drive()
click to toggle source
This is the main loop for processing the commands @return [Boolean]
# File lib/mars_rover/rover.rb, line 19 def drive commander.commands.each do |command| case command when 'L' new_index = (COMPASS.index(@direction) - 1).negative? ? (COMPASS.count - 1) : COMPASS.index(@direction) - 1 @direction = COMPASS[new_index] when 'R' new_index = (COMPASS.index(@direction) + 1) > (COMPASS.count - 1) ? 0 : COMPASS.index(@direction) + 1 @direction = COMPASS[new_index] else abort('Aborted! Rover moved out of zone') unless move end end end
Private Instance Methods
move()
click to toggle source
@return [Boolean] whether move was successful
# File lib/mars_rover/rover.rb, line 39 def move case direction when 'N' # We move up y-axis, +y return false unless zone.valid_position?(pos_x, pos_y + 1) @pos_y += 1 when 'E' # We move right on x-axis, +x return false unless zone.valid_position?(pos_x + 1, pos_y) @pos_x += 1 when 'S' # We move down y-axis, -y return false unless zone.valid_position?(pos_x, pos_y - 1) @pos_y -= 1 when 'W' # We move left on x-axis, -x return false unless zone.valid_position?(pos_x - 1, pos_y) @pos_x -= 1 end end