Main.py:
from turtle import Screen
from Paddle import Paddle
#creating screen
screen = Screen()
screen.screensize(1000, 600)
screen.bgcolor('black')
screen.title('Pong')
screen.tracer(0)
#paddle objects: rPaddle is for the paddle in the right and lPaddle for the left one
rPaddle = Paddle((350, 0)) #the tuple is for the starting position of the paddle object
lPaddle = Paddle((-350, 0))
#screen listeners
screen.listen()
screen.onkey(lPaddle.up, 'w')
screen.onkey(lPaddle.down, 's')
screen.onkey(rPaddle.up, 'Up')
screen.onkey(rPaddle.down, 'Down')
game_on = True
while game_on:
screen.update()
screen.exitonclick()
Paddle.py:
from turtle import Turtle
class Paddle(Turtle):
def __init__(self, starting_coords): #creates the paddles
super().__init__()
self.paddle = Turtle("square")
self.paddle.color('white')
self.paddle.shapesize(5, 1)
self.paddle.penup()
self.paddle.goto(starting_coords)
def up(self):
new_y = self.paddle.ycor() + 40 #makes the paddle move 40 pixels up
self.goto(self.xcor(), new_y)
print("up")
def down(self):
new_y = self.paddle.ycor() - 40 # moves the paddle 40 pixels down
self.goto(self.xcor(), new_y)
print('down')
I left some print statements to make sure the key is being pressed, but still the paddle would not move even if it shows the print statements, so I am very confused about what to do as I am following a tutorial.
It's strange that you're subclassing Turtle and also composing a Turtle instance as a field of the class. This seems to have created confusion: you're displaying
self.paddleon the screen, then usingself.goto()to move.selfis a totally different, invisible turtle! You probably mean:self.paddle.goto(), which moves the composed turtle rather than the inherited turtle that's implicitly created when you subclass.Remove
Turtlefromclass Paddle(Turtle):and removesuper().__init__()to get rid of the invisible turtle and display a clear error if you accidentally mix up calls.A useful way to debug this is
turtle.turtles()method, which returns a list of all turtles that have been created, from the perspective of theturtlemodule. After yourPaddleinstantiations, run:You'll see:
4 turtles--what?!
See How to create a subclass in python that is inherited from turtle Module for more reasons why you shouldn't subclass turtle, if this isn't evidence enough.
As an aside,
while game_on:slams the CPU as hard as possible, giving a non-portable framerate--fast machines run fast, slow machines run slow. It's better to useontimerto run the event loop. Here's an example.This is what the CPU looks like on my machine running your code (Xwayland is handling the Tkinter turtle window blasting away, causing my fan to turn on):
Running the
ontimerexample from the link:Less work, more stable framerate.