Home>

tmp_blocks = []

for block in blocks:
if ball.rect.colliderect (block.rect)! = True:
tmp_blocks.append (block)

blocks = tmp_blocks
Isn't this working? The block does not disappear. What should i do

import sys
import pygame
import math
from pygame.locals import QUIT
from pygame.locals import Rect
pygame.init ()
SURFACE = pygame.display.set_mode ((400,300))
FPSCLOCK = pygame.time.Clock ()
class Block:
     def __init __ (self, color, rect): #Constructor
          self.color = color #ball color (R, G, B)
          self.rect = rect # initial position and size (using Rect)
    #Drawing method
     def draw (self):
        pygame.draw.rect (SURFACE, self.color, self.rect)
class Ball:
     def __init __ (self, color, rect, dir = 320, speed = 10):
          self.color = color #ball color (R, G, B)
          self.rect = rect # initial position and size (using Rect)
          self.dir = dir
          self.speed = speed
     def draw (self):
          pygame.draw.ellipse (SURFACE, self.color, self.rect)
     def move (self):
          if self.rect.centerx<0 or self.rect.centerx>400:
                self.dir = 180-self.dir
          if self.rect.centery<0 or self.rect.centery>300:
                self.dir = -self.dir
          self.rect.centerx + = math.cos (math.radians (self.dir)) * self.speed
          self.rect.centery-= math.sin (math.radians (self.dir)) * self.speed

#Block object creation
left = 50
top = 50
width = 45
height = 20
color = (200, 50, 200)
blocks = []
for i in range (6):
     rect = Rect (left, top, width, height)
     blocks.append (Block (color, rect))
     left = left + 50

#Ball object creation
ball_rect = Rect (150,100,10,10)
ball_color = (255,255,0)
ball = Ball (ball_color, ball_rect, 320, 10)

tmp_blocks = [] # Create a temporary list of tmp_blocks
for block in blocks: From #blocks, add non-collision blocks to tmp_blocks
     if ball.rect.colliderect (block.rect)! = True:
          tmp_blocks.append (block)
Update the blocks list by assigning blocks = tmp_blocks #tmp_blocks to blocks

while True:
    for event in pygame.event.get ():
         if event.type == QUIT:
              pygame.quit ()
              sys.exit ()
    SURFACE.fill ((0,0,0))
    ball.move ()
    for block in blocks:
         block.draw ()
    ball.draw ()

    pygame.display.update ()
    FPSCLOCK.tick (30)
code
  • Answer # 1

    The block does not disappear. What should i do

    This is because this collision detection is not in the while True: process.

      ball.move ()
        tmp_blocks = [] # Create a temporary list of tmp_blocks
        for block in blocks: From #blocks, add non-collision blocks to tmp_blocks
            if ball.rect.colliderect (block.rect)! = True:
                tmp_blocks.append (block)
        Update the blocks list by assigning blocks = tmp_blocks #tmp_blocks to blocks


    And let's move after ball.move ().