Created
February 9, 2015 15:53
-
-
Save DavidJRobertson/1a1d55d3c0014d0ef166 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
position 50 50 | |
line 50 0 | |
line -25 -50 | |
line -25 50 | |
move 100 0 | |
line 40 0 | |
line -20 -40 | |
line -20 40 | |
position 100 100 | |
circle 20 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Canvas | |
import string | |
import re | |
def pos_cmd(state, x, y): | |
state['pos'] = [int(x), int(y)] | |
def move_cmd(state, x, y): | |
pos = state['pos'] | |
newpos = [pos[0] + int(x), pos[1] + int(y)] | |
state['pos'] = newpos | |
def line_cmd(state, x, y): | |
pos = state['pos'] | |
newpos = [pos[0] + int(x), pos[1] + int(y)] | |
Canvas.create_line(pos[0], pos[1], newpos[0], newpos[1]) | |
state['pos'] = newpos | |
def circle_cmd(state, r): | |
centre = state['pos'] | |
Canvas.create_oval(centre[0] - r, centre[1] - r, centre[0] + r, centre[1] + r) | |
def parse_line(line): | |
line = re.sub(r'[_\s]+', ' ', line).strip().lower().split() | |
command = line[0] | |
arguments = line[1:] | |
p_args = [] | |
for argument in arguments: | |
p_args.append(int(argument)) | |
return [command, p_args] | |
def execute_file(path): | |
state = { | |
'pos': [0, 0], | |
'line': 1 | |
} | |
commands = { | |
'position': pos_cmd, | |
'move': move_cmd, | |
'line': line_cmd, | |
'circle': circle_cmd | |
} | |
input_fh = open(path, 'r') | |
input_file = input_fh.readlines() | |
input_fh.close() | |
input_lines = map(parse_line, input_file) | |
while state['line'] <= len(input_lines): | |
command, arguments = input_lines[state['line'] - 1] | |
print state['line'], command, arguments | |
if commands.has_key(command): | |
commands[command](state, *arguments) | |
elif command == 'define': | |
func_lines = [] | |
pass | |
elif command == 'end': | |
print '[Line '+str(state['line'])+'] Unexpected "end".' | |
return | |
else: | |
print '[Line '+str(state['line'])+'] Command not recognized: "' + command + '".' | |
return | |
state['line'] += 1 | |
Canvas.complete() | |
def main(): | |
execute_file('test1.txt') | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment