2

I want to make a kind of level editor in a way, and I want to be able to click the blocks to delete them, one block gets destroyed when I run the code, but from there nothing works.

here's my code.

    def update(self):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        mouse_hover = blocks.rect.collidepoint(mouse_x, mouse_y)
        clicked = pygame.event.get(pygame.MOUSEBUTTONUP)  
        if mouse_hover:
            if clicked:
                blocks.kill()
                print(1)
Dergus
  • 21
  • 2
  • You should ensure your questions remains a [mre]. In this segment, I think you want `self.kill()` instead of `blocks.kill()`. You don't want to call `pygame.event.get()` for each sprite. – import random Oct 28 '22 at 03:57

1 Answers1

0

I've rearranged your code a little to check for collision in the event handler, on a left mouse click:

import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

class ground(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        # self.image = pygame.image.load('graphics/wall.png')
        self.image = self.image = pygame.Surface((10, 12), pygame.SRCALPHA)
        self.image.fill("firebrick")
        self.rect = self.image.get_rect(center=(x, y))

    def update(self):
        pass

# create a sprite group
GroundGroup = pygame.sprite.Group()
# Fill the group
for x in range(40):
    for y in range(30):
        platform = ground(x * 20, y * 20)
        GroundGroup.add(platform)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                # check for collision on left-click
                for block in GroundGroup:
                    if block.rect.collidepoint(event.pos):
                        GroundGroup.remove(block)
    ## Update game state
    GroundGroup.update()
    ## Clear the screen
    screen.fill("black")
    ## Draw sprites
    GroundGroup.draw(screen)
    ## Update screen
    pygame.display.flip()
    clock.tick(60)
pygame.quit()

Your issue may be that you weren't redrawing the screen properly, you need to clear the screen/refresh the background image and then redraw the sprites. This will clear away your deleted sprites.

import random
  • 3,054
  • 1
  • 17
  • 22
  • Yeah sorry I realised that after and fixed that but the main problem still stands. If i just use ```mouse_hover``` then it destroys sprites, and if i just use ```clicked``` it destroys random blocks but i can't use them together. – Dergus Oct 28 '22 at 03:48