Class: MarsRoverAlvin::Rover

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

Constant Summary collapse

GRID_X =
5
GRID_Y =
5

Instance Method Summary collapse

Constructor Details

#initialize(x_coordinate, y_coordinate, cardinal_point) ⇒ Rover



10
11
12
13
14
# File 'lib/mars_rover_alvin.rb', line 10

def initialize(x_coordinate, y_coordinate, cardinal_point)
  @x_coordinate = x_coordinate.to_i
  @y_coordinate = y_coordinate.to_i
  @cardinal_point= cardinal_point
end

Instance Method Details

#current_positionObject



64
65
66
# File 'lib/mars_rover_alvin.rb', line 64

def current_position
  puts "Your rover is at this #{@x_coordinate} #{@y_coordinate} #{@cardinal_point} location"
end

#moveObject

‘M’ in nasa commands



37
38
39
40
41
42
43
# File 'lib/mars_rover_alvin.rb', line 37

def move
  if @cardinal_point == 'N' then @y_coordinate += 1
  elsif @cardinal_point == 'E' then @x_coordinate += 1
  elsif @cardinal_point == 'S' then @y_coordinate -= 1
  elsif @cardinal_point == 'W' then @x_coordinate -= 1
  end
end

#parse(instruction) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/mars_rover_alvin.rb', line 45

def parse(instruction)
  instruction.each_char do |char|
    if char == 'L'
      self.turn_left
    elsif char == 'R'
      self.turn_right
    elsif char == 'M'
      self.move
      if @x_coordinate > GRID_X || @y_coordinate > GRID_Y 
        puts "Your Rover has reached the upper limit of the grid"
        abort
      elsif @x_coordinate < 0 || @y_coordinate < 0 
        puts "Your Rover has reached the lower limit of the grid"
        abort          
      end         
    end   
  end
end

#turn_leftObject

‘L’ in nasa commands



18
19
20
21
22
23
24
# File 'lib/mars_rover_alvin.rb', line 18

def turn_left
  if @cardinal_point == 'N' then @cardinal_point = 'W'
  elsif @cardinal_point == 'W' then @cardinal_point = 'S'
  elsif @cardinal_point == 'S' then @cardinal_point = 'E'
  elsif @cardinal_point == 'E' then @cardinal_point = 'N'
  end
end

#turn_rightObject

‘R’ in nasa commands



28
29
30
31
32
33
34
# File 'lib/mars_rover_alvin.rb', line 28

def turn_right
  if @cardinal_point == 'N' then @cardinal_point = 'E'
  elsif @cardinal_point == 'E' then @cardinal_point = 'S'
  elsif @cardinal_point == 'S' then @cardinal_point = 'W'
  elsif @cardinal_point == 'W' then @cardinal_point = 'N'
  end
end