In: Computer Science
Turtle Command Interpreter
You will write a program that reads a sequence of codes, converts
them into Turtle commands, and then executes them. The codes are in
a Python list, passed as an argument to your function.
turtleRunner(t, x)
t is a Turtle
x is a list of Turtle commands
(f, d) | Move forward by d pixels |
---|---|
u | Lift pen up |
d | Put pen down |
(l, d) | Turn left by d degrees |
(r, d) | Turn right by d degrees |
(c, s) | Change color to "s" |
(w, d) | Change pen width to d |
For example [("f", 100), ("r", 30), ("c", "red"), "u", ("f",
50), ("r", 60), "d", ("f", 100)] will execute:
t.forward(100)
t.right(30)
t.color("red")
t.penup()
t.forward(50)
t.right(60)
t.pendown()
t.forward(100)
Your program will need to do the following:
x =
[("w",3),("c","red"),("f",100),("r",120),("c","blue"),("f",100),("r",120),("c","green"),("f",100)]
turtleRunner(t, x)
Draws the shape below:
isinstance(x, y) returns True if x is an instance of class y. So
isinstance(e, tuple) will return True if e is a Tuple.
(Note no quotes around tuple in the call)
isinstance(e, str) will return True if e is a String.
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
import turtle
t = turtle.Turtle(shape="arrow")
t.speed(5);
window = turtle.Screen()
window.setup (width=500, height=500)
def turtleRunner(t, x):
for command in x:
if isinstance(command, tuple):
commandMode = command[0]
if commandMode=="f":
commandVal = command[1]
t.forward(commandVal)
elif commandMode=="r":
commandVal = command[1]
t.right(commandVal)
elif commandMode=="l":
commandVal = command[1]
t.left(commandVal)
elif commandMode=="u":
t.penup()
elif commandMode=="d":
t.pendown()
elif commandMode=="c":
commandVal = command[1]
t.color(commandVal)
elif commandMode=="w":
commandVal = command[1]
t.pensize(commandVal)
x =
[("w",3),("c","red"),("f",100),("r",120),("c","blue"),("f",100),("r",120),("c","green"),("f",100)]
turtleRunner(t, x)
window.bgcolor("white")
window.exitonclick()