I a creating a program to parse a simple language in a text file and delegate those actions to python-turtle. You pass the path to the file(s) you want to be parsed into the program, and a turtle window is shown.
This is my code:
import sys
import turtle
import time
t = turtle.Turtle()
functions = {
"F": t.forward,
"B": t.backward,
"R": t.right,
"L": t.left,
"H": t.seth,
"C": t.circle,
"U": t.penup,
"D": t.pendown,
"W": time.sleep,
"T": t.shape,
"V": t.speed,
"P": t.pensize,
"S": t.shapesize,
"O": turtle.done
}
def prep_args(args):
output = []
for arg in args:
try:
output.append(int(arg))
except:
output.append(arg)
return output
def parse_line(line):
if line.strip() == "":
return
action = line.strip()[0]
assert action in functions, f"Unknown Action: {action}"
args = line.strip().split(" ")[1:]
args = prep_args(args)
functions[action](*args)
def parse_file(path):
with open(path, "r") as f:
for line in f.readlines():
parse_line(line)
for argv in sys.argv[1:]:
parse_file(argv)
Example input file:
F 100
R 90
F 50
C 20
T square
W 5
V 0
S 5
U
F 50
D
C 30 180 5
H 90
F 3
S 1
O
I would be grateful for any help to improve this program.