INST326 Homework 02 Framework

Tracing with Turtles

The following code should read in a file, parse the file line by line, and move the turtle cursor accordingly.

Each line of the file will look like one of the following lines:

p _number_ _number_
f _number_
r _number_
l _number_
u
d 
h

  • p number number sets the x or y position of the turtle

  • f number moves the turtle forward

  • r number rotates the turtle to the right

  • l number rotates the turtle to the left

  • u lift the pen head up (no line)

  • d put the pen head down (start line)

  • h reset the cursor's location and orientation

Assignment

Fill in code to read each line of the file and move the turtle accordingly. You will be graded on how well your turtle can recover the image in a test file.

Trace Setup and Configuration

In [1]:
# Import the turtle package for drawing
import turtle
In [2]:
# Create a screen on which we draw
screen = turtle.Screen()

# Configure a default size
dimX = 600
dimY = 400
screen.setup(dimX, dimY)

Function for parsing line

In [ ]:
def parseLine(ttl, line):
    lineArray = list(map(lambda x: x.strip(), line.split(" ")))

    if ( len(line.strip()) == 0 ):
        pass
    elif ( lineArray[0] == "f" ):
        ttl.forward(float(lineArray[1]))
    elif ( lineArray[0] == "b" ):
        ttl.backward(float(lineArray[1]))
    elif ( lineArray[0] == "r" ):
        ttl.right(float(lineArray[1]))
    elif ( lineArray[0] == "l" ):
        ttl.left(float(lineArray[1]))
    elif ( lineArray[0] == "u" ):
        ttl.penup()
    elif ( lineArray[0] == "d" ):
        ttl.pendown()
    elif ( lineArray[0] == "h" ):
        ttl.home()
    elif ( lineArray[0] == "p" ):
        ttl.setposition(float(lineArray[1]), float(lineArray[2]))
    elif ( lineArray[0] == "#" ):
        # Comment
        pass
    else:
        raise ValueError(line)
In [ ]:
# Reset the screen
turtle.clearscreen()
screen.reset()
screen.screensize(dimX, dimY)
turtle.tracer(1)

# Create a turtle
ttl = turtle.Turtle()
ttl.speed(9)

with open("umd.trace", "r") as inFile:
    for line in inFile:
        parseLine(ttl, line)
In [ ]:
# Reset the screen
turtle.clearscreen()
screen.reset()
screen.screensize(dimX, dimY)
turtle.tracer(1)

# Create a turtle
ttl = turtle.Turtle()
ttl.speed(9)

with open("pacman.trace", "r") as inFile:
    for line in inFile:
        parseLine(ttl, line)

            
In [ ]:
# Reset the screen
turtle.clearscreen()
screen.reset()
screen.screensize(dimX, dimY)
turtle.tracer(1)

# Create a turtle
ttl = turtle.Turtle()
ttl.speed(9)

with open("blinky.trace", "r") as inFile:
    for line in inFile:
        parseLine(ttl, line)

            
In [ ]:
 
In [ ]:
 
In [ ]: