-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobot.rb
More file actions
104 lines (87 loc) · 2.41 KB
/
robot.rb
File metadata and controls
104 lines (87 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env ruby -w
class Robot
COURSE = ['NORTH', 'EAST', 'SOUTH', 'WEST'].freeze
def initialize(options = {space_width: 5, space_height: 6})
@width = options[:space_width]
@height = options[:space_height]
@position = {}
@course_index = 0
@init = false
end
def exec(input_str)
return if input_str.nil?
input_str.chomp!
return if input_str == ""
params = input_str.split(' ')
if placed?
case params[0]
when "LEFT" then left
when "RIGHT" then right
when "MOVE" then move
when "REPORT" then report
when "PLACE"
data = params[1].split(',')
place(data[0], data[1], data[2])
else
puts "You enter wrong command. Try again"
end
else
if params[0]=="PLACE"
data = params[1].split(',')
place(data[0], data[1], data[2])
else
puts "First command must be 'PLACE'"
end
end
end
#---------------------------------------PROTECTED METHODS--------------------------------------------#
protected
def left
@course_index = @course_index == 0 ? COURSE.size-1 : @course_index-1
end
def right
@course_index = @course_index == COURSE.size-1 ? 0 : @course_index+1
end
def move
case COURSE[@course_index]
when "NORTH"
@position[:y] += 1 if @position[:y] != @height-1
when "SOUTH"
@position[:y] -= 1 if @position[:y] != 0
when "WEST"
@position[:x] -= 1 if @position[:x] != 0
when "EAST"
@position[:x] += 1 if @position[:x] != @width-1
end
end
def report
p "Current position [#{@position[:x]}, #{@position[:y]}]. Course #{COURSE[@course_index]}"
end
def place(init_pos_x, init_pos_y, init_course)
begin
x = Integer(init_pos_x)
y = Integer(init_pos_y)
raise Error if incorrect_coordinates?(x,y)
raise Error unless correct_course?(init_course)
@course_index = COURSE.index(init_course)
@position[:x] = x
@position[:y] = y
@init = true
true
rescue
puts "You enter wrong command. Try again"
false
end
end
#---------------------------------------PRIVATE METHODS----------------------------------------#
private
def placed?
@init
end
def incorrect_coordinates?(x, y)
x>=@width || y>=@height || x<0 || y<0
end
def correct_course?(course)
COURSE.include?(course)
end
end