forked from olls/maze_interpreter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
537 lines (456 loc) · 18.7 KB
/
interpreter.py
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import sys
import time
import re
def separate(file_):
""" Split into program and functions lists. """
program, functions = [], []
for line in file_:
if '->' in line:
functions.append(line)
elif '##' in line or '..' in line:
program.append(line)
return program, functions
def organize_prog(program):
""" Split program lines into list of commands. """
new = [0 for i in program]
for i, line in enumerate(program):
new[i] = [j[:2] for j in line.split(',')]
return new
def organize_funcs(functions):
""" Split functions into name and command. """
functions = {function[:2]: function[5:] for function in functions}
for key, function in functions.items():
comment = False
for i, char in enumerate(function):
if char == '/':
if not comment:
comment = i
else:
functions[key] = functions[key][:comment]
else:
comment = False
while functions[key][-1:] == ' ':
functions[key] = functions[key][:-1]
return functions
def rep(program, functions, out):
""" Report the program and functions. """
out.output(str(program) + ' ' + str(functions))
def move_coords(direction, y, x):
""" Adjusts y and x in direction. """
if direction == 'N':
y -= 1
elif direction == 'E':
x += 1
elif direction == 'S':
y += 1
elif direction == 'W':
x -= 1
return y, x
def opp_direction(direction):
""" Returns the direction opposite to the one specified. """
if direction == 'N':
return 'S'
elif direction == 'E':
return 'W'
elif direction == 'S':
return 'N'
elif direction == 'W':
return 'E'
else:
return None
def move_car(car, instuction):
""" Moves the car with an instruction. """
if instuction == '%L':
car.set_direction('W')
elif instuction == '%R':
car.set_direction('E')
elif instuction == '%U':
car.set_direction('N')
elif instuction == '%D':
car.set_direction('S')
def fatal_error(error):
""" Prints the error and exits the program. """
print('Fatal Error: ' + error)
sys.exit()
def error(error, out):
""" Prints the error. """
out.output('Error: ' + error)
class Output(object):
""" Holds the output. """
def __init__(self, continuous=False):
self._out = ''
self._continuous = continuous
def __str__(self):
return self._out
def output(self, string):
self._out += '\n' + str(string)
if self._continuous:
print(string)
class Maze(object):
""" Holds and processes the maze. """
def __init__(self, program, functions, output):
self._program = program
self._functions = functions
self._output = output
if not len(self._cars) == 1:
fatal_error('Invalid car in program.')
def __str__(self):
string = ''
for row in self._program:
for cell in row:
if str(cell) == '..':
string += ' '
else:
string += str(cell)
string += '\n'
return string
@property
def running(self):
if len(self._cars) > 0:
return True
else:
return False
@property
def _cars(self):
no = 0
cars = []
for y, row in enumerate(self._program):
for x, cell in enumerate(row):
if cell == '^^':
self._program[y][x] = Car(y, x, '##')
if isinstance(self._program[y][x], Car):
no += 1
cars.append(self._program[y][x])
return tuple(cars)
def car_frames(self):
cars = self._cars
for car in cars:
car.frame()
def _move_cars(self):
cars = self._cars
for car in cars:
if car.hold == 0:
y, x = car.postion
directions = ['N', 'E', 'S', 'W']
# Move current direction to front
directions.remove(car.direction)
directions.insert(0, car.direction)
# Move current backwards direction to back
opp = opp_direction(car.direction)
directions.remove(opp)
directions.append(opp)
if car.cell == '<>':
directions = ['E', 'W']
for direction in directions:
yN, xN = move_coords(direction, y, x)
# If the new coords match allow traversing
reg1 = re.compile(r'[0-9]{2}')
reg2 = re.compile(r'[A-Z]{2}')
if (self._program[yN][xN] in ('..', '<>', '()', '>>',
'<<', '--', '%L', '%R',
'%U', '%D', '**') or
not reg1.match(self._program[yN][xN]) is None or
not reg2.match(self._program[yN][xN]) is None):
# Move Car into new pos, leaving old pos with orig value.
old = car.cell
new = self._program[yN][xN]
self._program[yN][xN] = car
self._program[y][x] = old
car.set_cell(new)
car.move(direction)
# If generating a new car, set direction opposite and move
if self._program[y][x] == '<>':
new_car_direction = opp_direction(direction)
yN, xN = move_coords(new_car_direction, y, x)
if (self._program[yN][xN] in ('..', '<>', '()',
'>>', '<<', '--',
'%L', '%R', '%U',
'%D', '**') or
not reg1.match(self._program[yN][xN]) is None or
not reg2.match(self._program[yN][xN]) is None):
self._program[yN][xN] = Car(yN, xN,
self._program[yN][xN],
car,
new_car_direction)
else:
fatal_error('Invalid program: No space for new car.')
break # Skip all other directions, as we used this one.
def _run_commands(self):
signal = False
is_function = False
reg1 = re.compile(r'[0-9]{2}')
reg2 = re.compile(r'[A-Z]{2}')
cars = self._cars
for car in cars:
y, x = car.postion
move_car(car, car.cell) # Moves the car if car.cell is a direction
if not reg1.match(car.cell) is None:
if car.hold == 0:
car.set_hold(car.cell)
elif car.cell == '()':
self._program[y][x] = car.cell
elif car.cell == '>>':
self._output.output(car.value)
elif car.cell == '<<':
car.set_value(input('>'))
elif car.cell == '--':
car.set_cell('##')
elif car.cell == '**':
signal = True
elif not reg2.match(car.cell) is None: # If it's a function
is_function = True
if is_function:
for car in cars:
if not reg2.match(car.cell) is None: # If it's a function
try:
function = self._functions[car.cell]
except KeyError:
function = False
error('Function undeclared.', self._output)
if function:
if function[:1] == '=':
if function[1:2] == '"':
car.set_value(function[2:-1])
else:
car.set_value(function[1:])
elif function[:2] == '-=':
try:
int(function[2:])
int_ = True
except ValueError:
int_ = False
if int_:
try:
car.set_value(int(int(car.value) - int(function[2:])))
except (TypeError, ValueError):
error('Can\'t subtract from non-integer.', self._output)
else:
error('Can\'t subtract non-integer.', self._output)
elif function[:2] == '+=':
try:
int(function[2:])
int_ = True
except ValueError:
int_ = False
if int_:
try:
car.set_value(int(int(car.value) + int(function[2:])))
except (TypeError, ValueError):
error('Can\'t add to non-integer.', self._output)
else:
error('Can\'t add non-integer.', self._output)
elif function[:2] == '*=':
try:
int(function[2:])
int_ = True
except ValueError:
int_ = False
if int_:
try:
car.set_value(int(int(car.value) * int(function[2:])))
except (TypeError, ValueError):
error('Can\'t multiply non-integer.', self._output)
else:
error('Can\'t multiply by non-integer.', self._output)
elif function[:2] == '/=':
try:
int(function[2:])
int_ = True
except ValueError:
int_ = False
if int_:
try:
car.set_value(int(int(car.value) / int(function[2:])))
except (TypeError, ValueError):
error('Can\'t divide non-integer', self._output)
else:
error('Can\'t divide by non-integer', self._output)
elif function[:2] == 'IF':
if 'THEN' in function:
comparition = False
if function[3:5] == '**':
if signal:
comparition = True
elif function[3:5] == '<=':
i = 0
val = ''
char = ''
while not char == ' ':
char = function[5 + i:6 + i]
val += char
i += 1
val = val[:-1]
try:
if int(car.value) <= int(val):
comparition = True
except ValueError:
error('Can\'t compare string.', self._output)
elif function[3:5] == '==':
i = 0
val = ''
char = ''
while not char == ' ':
char = function[5 + i:6 + i]
val += char
i += 1
val = val[:-1]
try:
if int(car.value) == int(val):
comparition = True
except ValueError:
error('Can\'t compare string.', self._output)
elif function[3:5] == '>=':
i = 0
val = ''
char = ''
while not char == ' ':
char = function[5 + i:6 + i]
val += char
i += 1
val = val[:-1]
try:
if int(car.value) >= int(val):
comparition = True
except ValueError:
error('Can\'t compare string.', self._output)
elif function[3:4] == '>':
i = 0
val = ''
char = ''
while not char == ' ':
char = function[4 + i:5 + i]
val += char
i += 1
val = val[:-1]
try:
if int(car.value) > int(val):
comparition = True
except ValueError:
error('Can\'t compare string.', self._output)
elif function[3:4] == '<':
i = 0
val = ''
char = ''
while not char == ' ':
char = function[4 + i:5 + i]
val += char
i += 1
val = val[:-1]
try:
if int(car.value) < int(val):
comparition = True
except ValueError:
error('Can\'t compare string.', self._output)
else:
error('Condition not recognized.', self._output)
then_pos = function.find('THEN')
if 'ELSE' in function:
else_pos = function.find('ELSE')
if comparition:
if 'ELSE' in function:
command = function[then_pos + 5:else_pos].strip()
else:
command = function[then_pos + 5:].strip()
move_car(car, command)
else:
if 'ELSE' in function:
command = function[else_pos + 5:].strip()
move_car(car, command)
else:
error('Invalid IF statement: Missing THEN')
def frame(self):
""" Updates the maze by one frame. """
self._move_cars()
self._run_commands()
class Car(object):
""" Holds information about a Car. """
def __init__(self, y, x, cell, car=None, direction='S'):
self._y = y
self._x = x
self._direction = direction
self._cell = cell
self._hold = 0
if car is None:
self._value = 0
else:
self._value = car.value
def __str__(self):
len_ = len(str(self._value))
if len_ == 1:
return '0' + str(self._value)
elif len_ == 0:
return '00'
elif len_ > 2:
return str(self._value)[:2]
else:
return str(self._value)
def frame(self):
if self._hold > 0:
self._hold -= 1
@property
def value(self):
return self._value
def set_value(self, value):
self._value = value
@property
def hold(self):
return self._hold
def set_hold(self, hold):
self._hold = int(hold)
@property
def cell(self):
return self._cell
def set_cell(self, cell):
self._cell = cell
def move(self, direction):
self._y, self._x = move_coords(direction, self._y, self._x)
self._direction = direction
@property
def postion(self):
return (self._y, self._x)
@property
def direction(self):
return self._direction
def set_direction(self, direction):
self._direction = direction
def main():
try:
if sys.argv[2] == '-c':
continuous = True
else:
continuous = False
except IndexError:
continuous = False
if continuous:
maze_out = True
else:
try:
if sys.argv[2] == '-o':
maze_out = True
else:
maze_out = False
except IndexError:
maze_out = False
if not maze_out:
continuous = True
output = Output(continuous)
program_file = open(sys.argv[1], 'r').read()
program_file = program_file.split('\n')
program, functions = separate(program_file)
program = organize_prog(program)
functions = organize_funcs(functions)
maze = Maze(program, functions, output)
FPS = 4
i = 0
while maze.running:
i += 1
if maze_out and i > 0:
print(('\n' * 80) + str(maze))
time.sleep(1 / FPS)
maze.car_frames()
maze.frame()
if maze_out:
print(maze)
print(output)
if __name__ == '__main__':
main()