Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created January 4, 2024 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/28befdc3ad3b5284ffc50e2dea98d65a to your computer and use it in GitHub Desktop.
Save ssaurel/28befdc3ad3b5284ffc50e2dea98d65a to your computer and use it in GitHub Desktop.
Ball Object for a Pong Game on the SSaurel's Blog
# First, we design the Ball Object
class Ball:
def __init__(self, canvas, width, velocity, boardwidth, boardheight):
self.width = width
self.boardwidth = boardwidth
self.boardheight = boardheight
# we center the ball on the board
self.topx = boardwidth / 2 - width / 2
self.topy = boardheight / 2 - width / 2
self.velocity = velocity
self.vx = velocity
self.vy = velocity
self.canvas = canvas
self.id = self.canvas.create_rectangle(self.topx, self.topy, self.topx + self.width, self.topy + self.width, fill = 'white')
# we define a method to draw the ball on the canvas
def draw(self):
self.canvas.coords(self.id, self.topx, self.topy, self.topx + self.width, self.topy + self.width)
# we define a restart method for restarting the ball move
def restart(self):
self.topx = self.boardwidth / 2 - self.width / 2
self.topy = self.boardheight / 2 - self.width / 2
# we define a random direction for the ball when restarting
self.vx = (-1, 1)[rand.random() > 0.5] * self.velocity
self.vy = (-1, 1)[rand.random() > 0.5] * self.velocity
# Move the ball
# we need to pass the pong game instance and the paddles in the move method of the Ball. You can improve this by yourself later ;)
def move(self, pong, paddleright, paddleleft):
# if the ball touches the top or the bottom of the board, we invert direction y
if self.topy <= 0 or (self.topy + self.width) >= self.boardheight:
self.vy = self.vy * -1
# if the ball touches one of both paddles, we invert direction x
if paddleright.collideright(self) or paddleleft.collideleft(self):
self.vx = self.vx * -1
# if the ball touches the right or the left of the board, we update paddle points and we return True
if (self.topx + self.width) >= self.boardwidth:
pong.leftpoints = pong.leftpoints + 1
return True
if self.topx <= 0:
pong.rightpoints = pong.rightpoints + 1
return True
# we update ball position
self.topx = self.topx + self.vx
self.topy = self.topy + self.vy
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment