Class: RubyRobot::Robot

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_robot/robot.rb

Constant Summary collapse

VALID_DIRECTIONS =

Directions are clockwise from north

[:north, :east, :south, :west]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(direction) ⇒ Robot

Returns a new instance of Robot.

Raises:



10
11
12
13
14
15
16
17
# File 'lib/ruby_robot/robot.rb', line 10

def initialize(direction)
  orig_direction = direction
  err_msg = "New Robots must have direction value of one of the following symbols: #{VALID_DIRECTIONS.join(', ')}; invalid value '#{orig_direction}'"
  direction = direction.kind_of?(String) ? direction.downcase.to_sym : direction
  raise ConstructionError.new(err_msg) unless VALID_DIRECTIONS.include?(direction)
  @direction = direction
  @tabletop = nil
end

Instance Attribute Details

#directionObject (readonly)

Returns the value of attribute direction.



7
8
9
# File 'lib/ruby_robot/robot.rb', line 7

def direction
  @direction
end

#tabletopObject (readonly)

Returns the value of attribute tabletop.



8
9
10
# File 'lib/ruby_robot/robot.rb', line 8

def tabletop
  @tabletop
end

Instance Method Details

#inspectObject



19
20
21
22
23
24
25
26
27
# File 'lib/ruby_robot/robot.rb', line 19

def inspect
  case @direction
  when :north then "^"
  when :south then "|"
  when :east  then ">"
  # :west
  else "<"
  end
end

#leftObject



29
30
31
32
33
# File 'lib/ruby_robot/robot.rb', line 29

def left
  # A little cheating here...index -1 will effectively wrap around and
  # return the last element
  @direction = VALID_DIRECTIONS[dir_idx - 1]
end

#moveObject

TODO: Error checking for if @tabletop.nil? Also, @tabletop.move and @tabletop.move? together should be synchronized if multithreaded where > 1 Robot are on a Tabletop.

Return #report after call, whether it was successful or not (assuming it is in fact placed on a board).



59
60
61
62
# File 'lib/ruby_robot/robot.rb', line 59

def move
  @tabletop.move(self, direction) if @tabletop.move?(self, direction)
  report
end

#place(tabletop) ⇒ Object

Called by a Tabletop where this has been placed



42
43
44
# File 'lib/ruby_robot/robot.rb', line 42

def place(tabletop)
  @tabletop = tabletop
end

#reportObject



46
47
48
# File 'lib/ruby_robot/robot.rb', line 46

def report
  @tabletop.position(self).merge(direction: direction)
end

#rightObject



35
36
37
# File 'lib/ruby_robot/robot.rb', line 35

def right
  @direction = VALID_DIRECTIONS[(dir_idx + 1) % VALID_DIRECTIONS.size]
end