Dec-29-2022, 11:20 PM
(This post was last modified: Dec-29-2022, 11:20 PM by deanhystad.)
You need to listen() for key press events. You also had an indenting problem on wn.onkeypress()
You should consider making some classes to organize your code. This is your program using classes to make two movable paddles and a ball with 14 fewer lines of code.
You should consider making some classes to organize your code. This is your program using classes to make two movable paddles and a ball with 14 fewer lines of code.
import turtle class Paddle(turtle.Turtle): def __init__(self, x, keys=None, color='black'): super().__init__() self.speed(3) self.shape('square') self.shapesize(stretch_wid=5, stretch_len=1) self.color(color) self.penup() self.goto(x, 0) if keys: # Have key press events move the paddles wn.onkeypress(lambda: self.move_y(20), keys[0]) wn.onkeypress(lambda: self.move_y(-20), keys[1]) def move_y(self, step): self.sety(self.ycor()+step) class Ball(turtle.Turtle): def __init__(self, color='black', keys=None): super().__init__() self.speed(3) self.shape('circle') self.color(color) self.penup() self.goto(0, 0) wn = turtle.Screen() wn.setup(width=800, height=600) paddles = (Paddle(-350, "ad"), Paddle(350, "jl")) ball = Ball() wn.listen() # Need to call this to have turtle listen for key press events. while True: wn.update()