The starter code below imports modules and creates a window and a turtle. It also provides some useful constants about the window borders.
Create two global variables to store random x and y coordinates, assign them both the value 0 for now.
Create a function called goto_random()
. Inside this function, assign the two global variables random values that are within the window edges(use the randrange function and the constants provided). Note that you will need to use the global keyword (followed by the names of the two variables) inside this function so that you can actually assign the variables values. Editing global variables inside of functions is typically a bad thing to do, but you need to do it here. In a few weeks you will learn a better way to do this.
Add a goto() statement inside this function that will send the turtle kyra to a random spot in the window, using the variables from the previous step.
Create another function called reset()
. This function should return the turtle to the center of the window and clear all the pen lines that the turtle has drawn.`` kyra.clear()`` will achieve this.
At the bottom of the program, register the two functions so that they respond to user key presses. The reset() function should be called when the r key is pressed and the goto_random() function should be called when the g key is pressed.
Call the reset() function near the bottom of the program. This ensures that the turtle window shows up, because a turtle command is acutally called.
Finally, add the wn.listen()
command at the end of the script. This must be the last line.
Test to make sure this works. Click in the window, then hit the ‘g’ key a few times to make sure the turtle moves around. Then hit the ‘r’ key to ensure the turtle returns to the center and all the lines disappear.