This is my code so far. I need to take the self.rect variable from the Player class and use it in the ball class so I can add a collision statement to detect when the ball hits the paddle. I want to change the if statement to the collision so the ball doesnt bounce off of nothing. Does anyone know the fix?
import sys, pygame, random
pygame.init()
Width = 1200
Height = 700
black = (0,0,0)
screen = pygame.display.set_mode((Width,Height))
color = (255,255,255)
class Player():
def __init__(self):
self.speed = 1
self.WIDTH = 300
self.HEIGHT = 20
self.color = (255,255,255)
self.rect = pygame.Rect(350,600,self.WIDTH,self.HEIGHT)
def left(self):
self.rect.x -= self.speed
if self.rect.x < 0:
self.rect.x = 0
def right(self):
self.rect.x += self.speed
if self.rect.x > 900:
self.rect.x = 900
def drawRect(self):
pygame.draw.rect(screen,self.color,self.rect)
class Ball():
def __init__(self):
self.speed = 1
self.radius = 10
self.color = (255,255,255)
self.centerX = 600
self.centerY = 350
self.rect = pygame.Rect(self.centerX-10,self.centerY-10,20,20)
def drawBall(self):
ballBox = pygame.draw.rect(screen,black,self.rect)
ball = pygame.draw.circle(screen,self.color[self.centerX,self.centerY],self.radius)
def move(self):
randomSpeed = random.randint (-10,10)
if self.centerY > 600:
self.speed = -1
if self.centerY < 0:
self.speed = 1
if self.centerX > 1180:
self.centerX = 1180
if self.centerX < 0:
self.centerX = 0
self.centerY += self.speed
self.centerX += randomSpeed
def clear():
screen.fill((black))
def main():
user = Player()
ball = Ball()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
user.left()
if keys[pygame.K_RIGHT]:
user.right()
pygame.display.flip()
clear()
user.drawRect()
ball.drawBall()
ball.move()
if __name__ == '__main__':
main()