I am working on a clone of Breakout and I've already made a ball, bricks and a paddle that can be moved freely by keyboard, the ball can hit the bricks, it can hit the window, but it can’t hit the paddle. It just go through the paddle and hit the window below the paddle then bounce back. I don't know what to do. Sorry about the lack of comments I am really new to this.
import pygame
from pygame.locals import QUIT, KEYDOWN, K_LEFT, K_RIGHT
from pygame.locals import Rect
import math
pygame.init()
SURFACE = pygame.display.set_mode((400,300))
pygame.display.set_caption("Game Window")
FPSCLOCK = pygame.time.Clock()
class Block:
def __init__(self, color, rect):
self.color = color
self.rect = rect
def draw(self):
pygame.draw.rect(SURFACE, self.color, self.rect)
def delete(self):
blocks.remove(block)
pw = 40
ph = 5
paddle = Block((0, 0, 255),Rect(180, 295,pw, ph))
pygame.key.set_repeat(30, 30)
class Ball:
def __init__(self,a,b,c,d):
self.color=a
self.rect=b
self.dir=c
self.speed=d
def draw(self):
pygame.draw.ellipse(SURFACE, ball_color, ball_rect)
def move(self):
ball_rect.centerx += math.cos(math.radians(self.dir))*self.speed
ball_rect.centery -= math.sin(math.radians(self.dir))*self.speed
if ball_rect.centerx <=0 or ball_rect.centerx >= 400:
self.dir = 180 - self.dir
if ball_rect.centery <= 0 or ball_rect.centery >= 300:
self.dir = -self.dir
def bounce(self):
self.dir -= 180
left=6
top=30
width=45
height=20
color=(200,50,200)
blocks = []
for i in range(4):
for j in range(8):
rect = Rect(left, top, width, height)
blocks.append(Block(color, rect))
left += 49
left = 6
top += 24
ball_rect = Rect(150,100,10,10)
ball_color = (255,255,0)
ball = Ball(ball_color, ball_rect, 60, 5)
num=0
while True:
SURFACE.fill((0,0,0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_LEFT and paddle.rect.centerx-pw/2 > 0:
paddle.rect.centerx -= 10
elif event.key == K_RIGHT and paddle.rect.centerx+pw/2 < 400:
paddle.rect.centerx += 10
SURFACE.fill((0,0,0))
paddle.draw()
for block in blocks:
block.draw()
ball.draw()
ball.move()
for block in blocks:
if ball.rect.colliderect(block.rect)==True:
Block.delete(blocks)
ball.bounce()
pygame.display.update()
FPSCLOCK.tick(60)