-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
executable file
·472 lines (268 loc) · 8.78 KB
/
script.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
#! /usr/bin/env python
#
"""Scripting module."""
from __future__ import print_function
import re
class Controllable(object):
"""Abstract class for controllable objects."""
def fall(self):
"""Fall."""
raise NotImplementedError()
def forward(self):
"""Move forward."""
raise NotImplementedError()
def backward(self):
"""Move backward."""
raise NotImplementedError()
def left(self):
"""Move left."""
raise NotImplementedError()
def right(self):
"""Move right."""
raise NotImplementedError()
def up(self):
"""Move up."""
raise NotImplementedError()
def down(self):
"""Move down."""
raise NotImplementedError()
def jump(self):
"""Jump."""
raise NotImplementedError()
class DummyObject(Controllable):
"""Simple testing class."""
def forward(self):
print("Moving forward...")
def backward(self):
print("Moving backward...")
def left(self):
print("Moving left...")
def right(self):
print("Moving right...")
def up(self):
print("Moving up...")
def down(self):
print("Moving down...")
class ScriptException(Exception):
pass
class Script(object):
"""Class for scripts running.
Args:
script_file (str): script filename
controllable_obj (Controllable): object for controlling
"""
def __init__(self, script_file, controllable_obj):
self.state = CommandState()
self.controllable_obj = controllable_obj
self.token_pattern = r"""
(?P<command>[a-zA-Z]+)
|(?P<float>[+-]?[0-9]+[.][0-9]+)
|(?P<integer>[0-9]+)
|(?P<hash>[#]+)
|(?P<newline>\n)
|(?P<whitespace>[ \t])
"""
self.tokenizer = Tokenizer(self.token_pattern)
self.script_str = self.load_script(script_file)
self.script_tokens = self.analyze_script(self.script_str)
self.token_index = 0
self.stopped = False
self.action_completed = False
@staticmethod
def load_script(filename):
"""Load script string from file.
Args:
filename (str): filename
Return:
str: script string
"""
with open(filename) as fo:
script_str = fo.read()
return script_str
def analyze_script(self, text):
"""Analyze script string.
Args:
text (str): script string
Return:
list of (token name, token value): script tokens
"""
tokens = []
for name, value in self.tokenizer.tokenize(text):
tokens.append((name, value))
return tokens
def next_token(self):
"""Return token.
Return:
(token name, token value): token
"""
act_index = self.token_index
self.token_index += 1
if act_index >= len(self.script_tokens):
return None
return self.script_tokens[act_index]
def action_done(self):
"""Set action completed status."""
self.action_completed = True
def next_action(self):
"""Run next action.
Return:
True if next action exists
"""
if not self.stopped:
self.action_completed = False
while not self.action_completed:
new_state = self.next()
if not new_state:
return False
else:
pass
return True
def next(self):
"""Transition to state.
Return:
ScriptState or None: next state
"""
if self.state:
self.state.process(self)
# return new state
return self.state
else:
return None
def set_next_state(self, state):
"""Set next state.
Args:
state (ScriptState): new script state
"""
self.state = state
def start(self):
"""Start script."""
self.stopped = False
def stop(self):
"""Stop/pause script."""
self.stopped = True
def restart(self):
"""Restart script."""
self.state = CommandState()
self.token_index = 0
self.action_completed = False
def reload(self, script_file):
# print("Reloading script file...")
self.script_str = self.load_script(script_file)
self.script_tokens = self.analyze_script(self.script_str)
self.restart()
class CameraScript(Script):
pass
class ScriptState(object):
"""Base class for script states."""
def __init__(self):
pass
def process(self, context):
pass
class CommandState(ScriptState):
def process(self, context):
while True:
token = context.next_token()
# print("Token: {}".format(token))
if token:
if token[0] == "whitespace":
continue
elif token[0] == "newline":
continue
elif token[0] == "command":
# print("Command: {}".format(token[1]))
context.set_next_state(MultiplierState(token[1]))
break
elif token[0] == "hash":
context.set_next_state(CommentState())
break
else:
context.set_next_state(None)
break
class MultiplierState(ScriptState):
def __init__(self, command):
super(MultiplierState, self).__init__()
self.command = command
def process(self, context):
while True:
token = context.next_token()
# print("Token: {}".format(token))
if token:
if token[0] == "whitespace":
continue
elif token[0] == "newline":
context.set_next_state(CommandState())
break
elif token[0] == "integer":
# print("{} x {}".format(self.command, token[1]))
context.set_next_state(
ProcessCommandState(self.command, int(token[1])))
break
else:
context.set_next_state(None)
break
class CommentState(ScriptState):
def process(self, context):
while True:
token = context.next_token()
# print("Token: {}".format(token))
if token:
if token[0] == "newline":
context.set_next_state(CommandState())
break
else:
context.set_next_state(None)
break
class ProcessCommandState(ScriptState):
def __init__(self, command, multiplier):
super(ProcessCommandState, self).__init__()
self.command = command
self.multiplier = multiplier
def process(self, context):
if self.multiplier > 0:
# print("Processing {} ({})".format(self.command, self.multiplier))
# action
if self.command == "forward":
context.controllable_obj.forward()
elif self.command == "backward":
context.controllable_obj.backward()
elif self.command == "left":
context.controllable_obj.left()
elif self.command == "right":
context.controllable_obj.right()
elif self.command == "up":
context.controllable_obj.up()
elif self.command == "down":
context.controllable_obj.down()
context.action_done()
self.multiplier -= 1
context.set_next_state(self)
else:
context.set_next_state(CommandState())
class TokenizerException(Exception):
pass
class Tokenizer(object):
"""Class for token tools."""
def __init__(self, pattern):
self.token_pattern = pattern
self.token_re = re.compile(self.token_pattern, re.VERBOSE)
def tokenize(self, text):
position = 0
while True:
match_obj = self.token_re.match(text, position)
if not match_obj:
break
position = match_obj.end()
token_name = match_obj.lastgroup
token_value = match_obj.group(token_name)
yield token_name, token_value
if position != len(text):
raise TokenizerException(
"Tokenizer stopped at pos {} of {}".format(
position, len(text)))
if __name__ == "__main__":
pass
# script = Script("script.txt", DummyObject())
#
# for token in script.script_tokens:
#
# print(token)