Class: Toy::Robot

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

Defined Under Namespace

Modules: Error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table = Toy::Table.new, direction = Toy::Direction) ⇒ Robot

Returns a new instance of Robot.



7
8
9
10
11
# File 'lib/toy/robot.rb', line 7

def initialize(table=Toy::Table.new, direction=Toy::Direction)
  @table = table
  @direction = direction
  @facing = nil
end

Instance Attribute Details

#facingObject (readonly)

Returns the value of attribute facing.



5
6
7
# File 'lib/toy/robot.rb', line 5

def facing
  @facing
end

#tableObject (readonly)

Returns the value of attribute table.



5
6
7
# File 'lib/toy/robot.rb', line 5

def table
  @table
end

Instance Method Details

#move!Object



30
31
32
33
34
# File 'lib/toy/robot.rb', line 30

def move!
  raise Toy::Robot::Error::PlacementError unless placed?

  place(target.x, target.y, @facing) if target && target.available?
end

#place(x, y, facing) ⇒ Object



13
14
15
16
17
18
# File 'lib/toy/robot.rb', line 13

def place(x, y, facing)
  raise Toy::Direction::Error::DirectionError unless Toy::Direction::DIRECTION.include?(facing)

  @table.hold!(x, y, self)
  @facing = facing
end

#placed?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/toy/robot.rb', line 20

def placed?
  !!current_unit
end

#positionObject



24
25
26
27
28
# File 'lib/toy/robot.rb', line 24

def position
  raise Toy::Robot::Error::PlacementError unless placed?

  [current_unit.x, current_unit.y, @facing]
end

#turn_left!Object



36
37
38
39
40
# File 'lib/toy/robot.rb', line 36

def turn_left!
  raise Toy::Robot::Error::PlacementError unless placed?

  @facing = @direction.rotate_left(@facing)
end

#turn_right!Object



42
43
44
45
46
# File 'lib/toy/robot.rb', line 42

def turn_right!
  raise Toy::Robot::Error::PlacementError unless placed?
  
  @facing = @direction.rotate_right(@facing)
end