Skip to content

Instantly share code, notes, and snippets.

@n4sm
Last active September 16, 2020 20:48
Show Gist options
  • Save n4sm/e656d76d0b5cc50c7f47525970dbfc42 to your computer and use it in GitHub Desktop.
Save n4sm/e656d76d0b5cc50c7f47525970dbfc42 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import turtle
PENUP = "u"
PENDOWN = "d"
FORWARD = "f"
BACKWARD = "b"
LEFT = "l"
RIGHT = "r"
HOME = "h"
def r_arg(dic: dict, sub: str) -> tuple:
n = 1
for c in range(len(sub)):
char = sub[c]
if char == " ":
n += 1
break
elif char in dic.keys():
n += 1
break
elif not char.isdecimal():
print("[FATAL] Bad char")
exit(-1)
n += 1
return int(sub[:n-1]), n
def parse_str(s: str, o: object) -> list:
"""
s: str
returns a list fot which:
ret[0] -> returns the method to call
ret[x] -> argument for the function
"""
r = []
# sanity checks
assert isinstance(s, str), "[FATAL] The argument is not a string !"
assert len(s) > 0, "[FATAL] The argument is null"
dic_cmd = {
PENUP : o.penup,
PENDOWN : o.pendown,
FORWARD : o.forward,
BACKWARD : o.backward,
LEFT : o.left,
RIGHT : o.right,
HOME : o.home
}
i = 0
while i+1 < len(s):
# Is it a blank char
if s[i] == " ":
i += 1
continue
elif s[i] not in dic_cmd.keys():
print("[FATAL] Bad char in the string")
exit(-1)
current = s[i]
# current character
if current == PENUP:
r.append([dic_cmd[PENUP]])
elif current == PENDOWN:
r.append([dic_cmd[PENDOWN]])
elif current == FORWARD:
# slice on the argument of the command
sub = s[i+1:]
if sub[0] == " ":
print("[FATAL] Bad instruction")
exit(-1)
arg, n = r_arg(dic_cmd, sub)
i += n
r.append([dic_cmd[FORWARD], arg])
continue
elif current == BACKWARD:
sub = s[i+1:]
if sub[0] == " ":
print("[FATAL] Bad instruction")
exit(-1)
arg, n = r_arg(dic_cmd, sub)
i += n
r.append([dic_cmd[BACKWARD], arg])
continue
elif current == LEFT:
sub = s[i+1:]
if sub[0] == " ":
print("[FATAL] Bad instruction")
exit(-1)
arg, n = r_arg(dic_cmd, sub)
i += n
r.append([dic_cmd[LEFT], arg])
continue
elif current == RIGHT:
sub = s[i+1:]
if sub[0] == " ":
print("[FATAL] Bad instruction")
exit(-1)
arg, n = r_arg(dic_cmd, sub)
i += n
r.append([dic_cmd[RIGHT], arg])
continue
elif current == HOME:
r.append([dic_cmd[HOME]])
i += 1
return r
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Init
s = turtle.Screen()
t = turtle.Turtle()
si = 'b100 r90 f150 '
li = parse_str(si, t)
print(parse_str(si, t))
for l in li:
if len(l) == 1:
l[0]()
continue
l[0](l[1])
s.mainloop()
#
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment