0

My turtle should go direction which I show but there is a problem. When I press a key the turtle moves 10 and if I hold to press the key sometime it doesn't move. I want to change the turtle so that if my fingers are on a key it should keep moving

from turtle import Turtle
import turtle
STARTING_POSITION = (0, -260)
MOVE_DISTANCE = 20

screen = turtle.Screen()
screen.setup(width=900, height=600)


class Board(Turtle):
    def __init__(self):
        super().__init__()
        self.shape('square')
        self.hideturtle()
        self.shapesize(1, 6, 1)
        self.penup()
        self.goto(STARTING_POSITION)
        self.showturtle()
        self.speed("fast")

    def move_left(self):
        if self.xcor() > -390:
            self.back(MOVE_DISTANCE)

    def move_right(self):
        if self.xcor() < 390:
            self.forward(MOVE_DISTANCE)

    def go_to_start(self):
        self.goto(STARTING_POSITION)


board = Board()

screen.listen()
screen.onkey(board.move_left, "Left")
screen.onkey(board.move_right, "Right")


screen.mainloop()
Abduhoshim
  • 11
  • 2
  • 1
    Please provide a [mre] – Thomas Weller Feb 14 '22 at 18:15
  • 1
    Thanks for the edit, but we'd still need to understand where e.g. `screen` comes from. Again, please review the link provided by @ThomasWeller in the previous comment. – tripleee Feb 15 '22 at 10:49
  • Looks like a MRE now! Thanks for the edits. If you're creating a real-time game like Pong, see [How to bind several key presses together in turtle graphics?](https://stackoverflow.com/questions/47879608/how-to-bind-several-key-presses-together-in-turtle-graphics/70979967#70979967) -- you'll probably want to run a manual update loop with `ontimer`. – ggorlen Feb 15 '22 at 16:02

1 Answers1

0

If you use onkeypress instead of onkey, the turtle will continue moving when the key is pressed.

From the python turtle documentation:

turtle.onkeypress(fun, key=None)

Parameters fun – a function with no arguments or None

key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)

Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Remark: in order to be able to register key-events, TurtleScreen must have focus.

Sriram Srinivasan
  • 650
  • 2
  • 4
  • 14