Turtle – Draw Lines using arrow keys
In this article, we will learn how to draw lines using the keyboard (arrow keys) in turtle graphics. Let’s first discuss some methods used in the implementation below:
- wn.listen(): Using this then we can give keyboard inputs
- wn.onkeypress(func, “key”): This function is used to bind fun to the key-release event of the key. In order to be able to register key-events, TurtleScreen must have focus.
- setx(position): This method is used to set the turtle’s second coordinate to x, leaving the first coordinate unchanged Here, whatever the position of the turtle is, it set the x coordinate to the given input keeping the y coordinate unchanged.
- sety(position): This method is used to set the turtle’s second coordinate to y, leaving the first coordinate unchanged Here, whatever the position of the turtle is, it set the y coordinate to the given input keeping the x coordinate unchanged.
- ycor(): This function is used to return the turtle’s y coordinate of the current position of the turtle. It doesn’t require any argument.
- xcor(): This function is used to return the turtle’s x coordinate of the current position of the turtle. It doesn’t require any argument
- head.penup: Picks the pen up so the turtle does not draw a line as it moves
- head.hideturtle: This method is used to make the turtle invisible. It’s a good idea to do this while you’re in the middle of a complicated drawing because hiding the turtle speeds up the drawing observably. This method does not require any argument.
- head.clear: This function is used to delete the turtle’s drawings from the screen
- head.write: This function is used to write text at the current turtle position.
- Import the turtle modules.
- Get a screen to draw on
- Define two instances for the turtle one is a pen and another is the head.
- Head is for telling which key is currently pressed
- Define the functions for the up, down, left, right movement of the turtle.
- In the respective up, left, right and down functions set the arrow to move 100 units in up, left, right, and down directions respectively by changing the x and y coordinates.
- Use function listen() for giving keyboard inputs.
- Use onkeypress in order to register key-events.
Below is the Python implementation of the above approach: