-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoy_robot_simulator.rb
109 lines (88 loc) · 2.25 KB
/
toy_robot_simulator.rb
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
104
105
106
107
108
109
module ToyRobotSimulator
TABLE_EDGE = 4
ROBOT_MOVE_COMMANDS = %w[MOVE LEFT RIGHT].freeze
ROBOT_INFO_COMMANDS = %w[REPORT].freeze
DIRECTIONS = %w[NORTH EAST SOUTH WEST].freeze
COMMAND_FILTER = /
^(?:PLACE\s[0-#{TABLE_EDGE}],[0-#{TABLE_EDGE}],(?:#{DIRECTIONS.join('|')}))
|#{ROBOT_MOVE_COMMANDS.join('|')}|#{ROBOT_INFO_COMMANDS.join('|')}$
/x.freeze
class Commander
attr_reader :robot, :commands
def initialize
@robot = nil
@commands = filtered_input
end
def filtered_input
Enumerator.new do |yielder|
ARGF.each_line do |line|
yielder << line.chomp if COMMAND_FILTER.match?(line)
end
end
end
def place_robot
commands.next until commands.peek[0..4] == "PLACE"
(x_pos, y_pos, facing) = commands.next[6..-1].split(',')
@robot = Robot.new(x_pos, y_pos, facing)
end
def command_robot
loop do
command = commands.next
command_sym = command.downcase.to_sym
if ROBOT_MOVE_COMMANDS.include?(command)
robot.public_send command_sym
elsif ROBOT_INFO_COMMANDS.include?(command)
puts robot.public_send command_sym
end
end
end
end
class Robot
attr_reader :x_pos, :y_pos, :facing
def initialize(x_pos, y_pos, facing)
@x_pos = x_pos.to_i
@y_pos = y_pos.to_i
@facing = DIRECTIONS.index(facing)
end
def x_pos=(pos)
@x_pos = pos.clamp(0, TABLE_EDGE)
end
def y_pos=(pos)
@y_pos = pos.clamp(0, TABLE_EDGE)
end
def facing=(index)
@facing = (index + DIRECTIONS.size).modulo(DIRECTIONS.size)
end
def move
public_send DIRECTIONS[facing].downcase.to_sym
end
def north
self.y_pos = y_pos.succ
end
def east
self.x_pos = x_pos.succ
end
def south
self.y_pos = y_pos.pred
end
def west
self.x_pos = x_pos.pred
end
def left
self.facing = facing.pred
end
def right
self.facing = facing.succ
end
def report
"#{x_pos},#{y_pos},#{DIRECTIONS[facing]}"
end
end
module_function
def run
commander = Commander.new
commander.place_robot
commander.command_robot
end
end
ToyRobotSimulator.run if $PROGRAM_NAME == __FILE__