0

I am working on a clone of Breakout. I've already made ball and bricks and let the ball hit the bricks but when the ball and the block collide, the ball goes through instead of bouncing back. What should i do? Sorry about the lack of comments I am really new to this.

import pygame
from pygame.locals import QUIT
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)
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
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()
    for block in blocks:
        block.draw()
    ball.draw()
    ball.move()
    for block in blocks:
        if ball.rect.colliderect(block.rect)==True:
            Block.delete(blocks)
            print("{}回目の衝突".format(num))
            num += 1
    pygame.display.update()
    FPSCLOCK.tick(60)

tesla bee
  • 13
  • 3

1 Answers1

1

If you want the ball to bounce, then add a new method -

def bounce(self):
    self.dir -= 180

It will bounce the ball back. Note: this might be glitchy and might not go the correct direction. Try changing the angles and add conditions to make it perfect.

Then add this -

 if ball.rect.colliderect(block.rect)==True:
    Block.delete(blocks)
    ball.bounce()
    print("{}回目の衝突".format(num))
    num += 1
PCM
  • 2,692
  • 2
  • 7
  • 29