Class: ToyRobot::Robot

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

Overview

Robot class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table = nil) ⇒ Robot

Returns a new instance of Robot.



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

def initialize(table = nil)
  @placed = false
  @table = table
  @x = nil
  @y = nil
  @facing = nil
end

Instance Attribute Details

#facingObject

Returns the value of attribute facing.



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

def facing
  @facing
end

#placedObject

Returns the value of attribute placed.



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

def placed
  @placed
end

#tableObject

Returns the value of attribute table.



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

def table
  @table
end

#xObject

Returns the value of attribute x.



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

def x
  @x
end

#yObject

Returns the value of attribute y.



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

def y
  @y
end

Instance Method Details

#calculate_potential_movement(facing) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/toy_robot/robot.rb', line 64

def calculate_potential_movement(facing)
  case facing
  when 'NORTH'
    { x: nil, y: 1 }
  when 'WEST'
    { x: -1, y: nil }
  when 'SOUTH'
    { x: nil, y: -1 }
  when 'EAST'
    { x: 1, y: nil }
  end
end

#leftObject



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

def left
  check_pre_conditions
  @facing = next_facing('left')
end

#moveObject



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/toy_robot/robot.rb', line 40

def move
  check_pre_conditions
  result = calculate_potential_movement(facing)

  x_should_be = result[:x].nil? ? @x : (@x + result[:x])
  y_should_be = result[:y].nil? ? @y : (@y + result[:y])

  raise Surface::TableOutOfBound unless @table.can_be_placed?(x_should_be, y_should_be)

  @x = x_should_be
  @y = y_should_be
end

#place(x, y, facing) ⇒ Object



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

def place(x, y, facing)
  return if @placed
  raise Surface::TableIsNotSet if @table.nil?
  raise Surface::TableOutOfBound unless @table.can_be_placed?(x, y)
  raise ToyRobot::InvalidFacing unless DIRECTIONS.include?(facing)

  @x = x
  @y = y
  @facing = facing
  @placed = true
end

#report(format = 'console') ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/toy_robot/robot.rb', line 53

def report(format = 'console')
  raise ToyRobot::RobotIsNotPlaced unless @placed

  case format
  when 'console'
    to_s
  else
    { x: @x, y: @y, facing: @facing }
  end
end

#rightObject



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

def right
  check_pre_conditions
  @facing = next_facing('right')
end