I'm currently trying to program a Pong clone, but I can't manage to integrate the collisions with graphics. There are 3 graphics in the game:
- Graphic for player 1
- Graphic for player 2
- Graphic for the playing ball
I read somewhere that I have to convert the graphs into rectangles and then build in the collisions based on the diameter of the 3 graphics. Unfortunately, I get the following error message:
Traceback (most recent call last):
File "C:\Users\...Pong.py", line 67, in <module>
if image_ball_center.collidepoint(image_player1_center):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'collidepoint'
How can I install the collisions correctly? Does anyone have any ideas? That is my source code:
import pygame
pygame.init()
WIDTH = 1280
HEIGHT = 720
screen = pygame.display.set_mode((WIDTH,HEIGHT))
background_image = pygame.image.load("sky.jpg")
tennisball = pygame.image.load("tennisball.png")
player1 = pygame.image.load("player1.jpg")
player2 = pygame.image.load("player2.jpg")
x1 = 80
y1 = 300
x2 = 1200
y2 = 300
tennisball_x = 650
tennisball_y = 300
movement_x = 1
movement_y = 1
running = True
while (running):
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
y1 = y1 - 2
if keys[pygame.K_DOWN]:
y1 = y1 + 2
if keys[pygame.K_s]:
y2 = y2 + 2
if keys[pygame.K_w]:
y2 = y2 - 2
tennisball_x = tennisball_x + movement_x
tennisball_y = tennisball_y + movement_y
if tennisball_y > HEIGHT or tennisball_y < 0:
movement_y = movement_y * -1
if tennisball_x > WIDTH or tennisball_x < 0:
movement_x = movement_x * -1
image_ball = tennisball
rect = image_ball.get_rect()
image_ball_center = rect.center
image_player1 = player1
rect2 = image_player1.get_rect()
image_player1_center = rect2.center
if image_ball_center.collidepoint(image_player1_center):
movement_x = movement_x * -1
screen.blit(background_image, (0,0))
screen.blit(tennisball,(tennisball_x,tennisball_y))
screen.blit(player1,(x1,y1))
screen.blit(player2, (x2, y2))
pygame.display.update()
pygame.quit()