class ToyRobot::Orientation

A class to represent the orientation of a toy robot

Constants

VECTORS

Attributes

dx[R]

change in x value following a move in this orientation

dy[R]

change in y value following a move in this orientation

Public Class Methods

new(key) click to toggle source

Create a new Orientation. Must supply the name of the orientation (NORTH, SOUTH, EAST, or WEST) or a 2 element array containing dx and dy values, that can be 1, 0 or -1.

# File lib/toy_robot/orientation.rb, line 20
def initialize(key)
        if key.is_a? String
                vector = VECTORS[key.upcase.strip.to_sym]
             raise ArgumentError, "supplied argument of #{key} is not a valid Orientation name - valid Orientation names are #{VECTORS.keys.join(', ')}" unless vector
                @dx, @dy = vector
        elsif key.is_a? Array
                raise ArgumentError, "supplied orientation array has length of #{key.length} - an orientation array must have a length of two" unless key.size == 2 
                raise ArgumentError, "supplied orientation array has a dx value of #{key[0]} - valid values are 1, 0 or -1" unless [1,0,-1].include?(key[0])
                raise ArgumentError, "supplied orientation array has a dy value of #{key[1]} - valid values are 1, 0 or -1"  unless [1,0,-1].include?(key[1])
                raise ArgumentError, "supplied orientation array has both dx and dy values of 0 - one of the values must be non-zero" if key[0] == 0 && key[1] == 0
                raise ArgumentError, "supplied orientation array has both dx and dy values as non-zero - one of the values must be zero" if key[0] != 0 && key[1] != 0
                @dx, @dy = key
        else
                raise ArgumentError, "supplied argument is of type #{key.class.name}. An orientation name or array is required"
        end
end

Public Instance Methods

left() click to toggle source

return a new Orientation that is 90 degrees to the left of self

# File lib/toy_robot/orientation.rb, line 39
def left
        turn(-1)
end
right() click to toggle source

return a new Orientation that is 90 degrees to the right of self

# File lib/toy_robot/orientation.rb, line 45
def right
        turn(1)
end
to_s() click to toggle source

return the name of the Orientation (NORTH, SOUTH, EAST, or WEST)

# File lib/toy_robot/orientation.rb, line 51
def to_s
        inverted[ [@dx, @dy] ].to_s
end

Private Instance Methods

inverted() click to toggle source

caching method to return a vector that allows lookup of an Orientation name from it's dx and dy values

# File lib/toy_robot/orientation.rb, line 67
def inverted
        @inverted ||= VECTORS.invert
end
turn(direction) click to toggle source

unified turn function, because maths

# File lib/toy_robot/orientation.rb, line 59
def turn(direction)
        dx = @dx == 0 ? direction * @dy : 0
        dy = @dy == 0 ? direction * -1 * @dx : 0
        ToyRobot::Orientation.new( [ dx, dy] )
end