Keyboard Commands with Python Turtle
- Step 1 - Create a new python (with turtle program) called "yourname_keyboard" and set the speed to "fast"
import turtle
t=turtle.Turtle() t.speed("fast") |
- Step 2 - Create a function that will move the turtle upwards when the "up" arrow key is pressed. Note that we re-orientate the turtle to face up
#function to move turtle up
def go_up(): if (t.heading() != 90): t.setheading(90) t.forward(50) |
- Step 3 - Create a function to listen to see if a key is pressed and to act accordingly based on which key is pressed
#function to listen for a key to be pressed and to respond accordingly
def keyboard_commands(): turtle.Screen().onkey(go_up,"Up") turtle.Screen().listen() |
- Step 4 - Call the function in the main program
# main program
t.setheading(0) keyboard_commands() |
- Step 5 - Do the programming that will move the turtle correctly when the following keys are pressed: down arrow, left arrow, right arrow
- Step 5B - Can you modify the program to utilize a variable that controls the distance travelled each time a button is pressed
- Step 6 - Make sure to embed your program in your weebly page
- Extension:
Can you figure out how to move the turtle at a slight angle left or right (possibly by pressing the "r" or "l" keys or the "<" or ">" keys until desired angle reached) and then moving the turtle forward in that direction by pressing a key (possibly F for forward)
Later - With Graphics:
- Go to https://trinket.io/ and create a user account