I am creating the Pong game using the Turtle module in Python. So far, I have one file for the paddles (the bars that players control to hit the ball) called paddles.py and a second file for the main gameplay control called game.py. I still plan on making a file for the ball and another for score-keeping.
In my paddles file, I create a Paddle
class using the Turtle
class. It doesn’t exactly inherit from Turtle
, but instead creates several Turtle
instances inside each Paddle
. I made a condition inside the __init__
of Paddle
which sets a “left” paddle to the left and a “right” paddle to the right. Then I import the Paddle
file to game.py and create a left_pad
and a right_pad
as follows:
left_pad = Paddle("left")
right_pad = Paddle("right")
On running the game.py file, the left_pad
appears briefly then disappears, then only the right_pad
is actually showing on the screen.
The shape is correct, the positioning is correct, but the left_pad
is simply not there.
Here is the code for paddles.py (for now I am not worried about the moving functions):
from turtle import Turtle
class Paddle:
side = ""
paddle = [Turtle(shape="square") for i in range(4)]
paddle_bottom = -30
paddle_range = []
def __init__(self, side):
self.side = side
self.paddle_range = [self.paddle[0].screen.canvheight-10, -self.paddle[0].screen.canvheight+10]
for box in range(len(self.paddle)):
self.paddle[box].penup()
# Set to middle height
for box in range(len(self.paddle)):
self.paddle[box].sety(self.paddle_bottom + 20*box)
# Set to sides
if side == "left":
for box in range(len(self.paddle)):
self.paddle[box].setx((-self.paddle[0].screen.canvwidth / 2) + 20)
else:
for box in range(len(self.paddle)):
self.paddle[box].setx((self.paddle[0].screen.canvwidth / 2) - 20)
def move():
global paddle
for box in len(range(paddle)):
paddle[box].forward(1)
paddle[0].screen.update()
def move_up():
global paddle_range
global move
for box in len(range(paddle)):
paddle[box].setheading(90)
while paddle[-1].ycor() < paddle_range[0]:
move()
def move_down():
for box in len(range(paddle)):
paddle[box].setheading(270)
while paddle[0].ycor() > paddle_range[1]:
move()
if side == "left":
paddle[0].screen.onkey(key="w", fun=move_up)
paddle[0].screen.onkey(key="s", fun=move_down)
else:
paddle[0].screen.onkey(key="Up", fun=move_up)
paddle[0].screen.onkey(key="Down", fun=move_down)
and the game.py:
from turtle import Screen
from paddles import Paddle
screen = Screen()
screen.bgcolor("beige")
screen.title("Pong!")
screen.setup(width=820, height=620)
screen.screensize(canvwidth=800, canvheight=600)
screen.tracer(0)
screen.listen()
left_pad = Paddle("left")
screen.update()
right_pad = Paddle("right")
screen.update()
screen.exitonclick()