-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogo
executable file
·82 lines (71 loc) · 1.55 KB
/
logo
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
#!/usr/bin/env ruby
class Logo
def initialize(grid_size, program)
@grid_size = grid_size
@program = parse(program)
@grid = []
# setup_grid
# print_grid
run
end
def setup_grid
@grid_size.times do |i|
row = []
@grid_size.times do |j|
row << "."
end
@grid << row
end
end
def parse(program)
commands = program.split
stack = []
i = 0
while i < commands.size
if %w[FD RT LT BK].include?(commands[i])
stack << [commands[i], commands[i + 1]]
i += 2
elsif commands[i] == "REPEAT"
repeat = []
times = commands[i + 1]
while commands[i] != "]"
if %w[FD RT LT BK].include?(commands[i])
repeat << [commands[i], commands[i + 1]]
i += 2
else
i += 1
end
end
stack << ["REPEAT", times, repeat]
i += 2
else
i += 1
end
end
stack
end
def print_grid
puts @grid.map { |row| row.join("") }.join("\n")
end
def run
@program.each do |command|
if command[0] == "REPEAT"
command[1].to_i.times do
command[2].each do |repeat_command|
puts repeat_command[0] + " " + repeat_command[1]
end
end
else
puts command[0] + " " + command[1]
end
end
end
end
filename = ARGV[0]
if File.exists?(filename)
data = File.read(filename)
grid_size, program = data.split("\n\n")
Logo.new(grid_size.to_i, program)
else
puts "error:could not read file #{filename}."
end