class DallasMarsRover::Commander
The commander class controls the non rover operations and handles pre-checks
Attributes
commands[R]
start_direction[R]
start_point[R]
zone_size[R]
Public Class Methods
new(file)
click to toggle source
@param [Text] file @return [Commander] commander object
# File lib/mars_rover/commander.rb, line 8 def initialize(file) # Initialise variables @zone_size = {} @start_point = {} @start_direction = '' @commands = [] # File is valid, now we can process zone_size, start_point, command = load_commands file @zone_size[:x] = zone_size[0].to_i @zone_size[:y] = zone_size[1].to_i @start_point[:x] = start_point[0].to_i @start_point[:y] = start_point[1].to_i @start_direction = start_point[2] @commands = command # Check start point is in the zone raise 'Invalid start co-ordinates.' unless valid_start? # Check we have a valid start direction raise 'Invalid starting direction.' unless valid_direction? # Check all commands are valid raise 'Invalid commands passed.' unless valid_commands? end
Private Instance Methods
load_commands(file)
click to toggle source
@param [file handle] file @return [Array<Integer>] survey zone boundaries @return [Hash] rover start co-ordinates and direction @return [Array<String>] string of rover commands
# File lib/mars_rover/commander.rb, line 36 def load_commands(file) zone = [] start = [] commands = [] file.each_line do |line| # Line 1 is the zone definition zone = line.tr("\n", '').split(' ') if file.lineno == 1 # Line 2 is the starting point and direction of rover start = line.tr("\n", '').upcase.split(' ') if file.lineno == 2 # Line 3 are the commands to process commands = line.tr("\n", '').tr(' ', '').upcase.split('') if file.lineno == 3 end return zone, start, commands end
valid_commands?()
click to toggle source
@return [Boolean] if all the commands are valid for the rover
# File lib/mars_rover/commander.rb, line 52 def valid_commands? invalid_commands = 0 # Check each element is in the Command vocabulary commands.each do |val| invalid_commands += 1 unless COMMANDS.include? val end # If 0 then all are valid invalid_commands.zero? end
valid_direction?()
click to toggle source
@return [Boolean] Start direction a valid cardinal point
# File lib/mars_rover/commander.rb, line 75 def valid_direction? # Is the start direction a valid cardinal point COMPASS.include? start_direction end
valid_start?()
click to toggle source
@return [Boolean] if the start co-ordinates are valid
# File lib/mars_rover/commander.rb, line 63 def valid_start? # Check we have only 2 elements, x , y return false unless start_point.count == 2 # Check start X is less than zone X return false unless start_point[:x] < zone_size[:x] # Check start Y is less than zone Y return false unless start_point[:y] < zone_size[:y] # Valid true end