Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pygame delete object

Tags:

python

pygame

I need help deleting an object, and I mean delete, not draw over or other things. My code so far:

def detect_collision(player_pos, enemy_pos):
    p_x = player_pos[0]
    p_y = player_pos[1]

    e_x = enemy_pos[0]
    e_y = enemy_pos[1]

    if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x+enemy_size)):
        if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y+enemy_size)):
            return True
    return False

def bullets():
    b_x = player_pos[0]
    b_y = player_pos[1]
    keep_going = True
    pygame.draw.rect(screen, TEAL, (b_x, b_y, 15, 50))
    while keep_going:
        b_y += 75
        if detect_collision(player_pos, enemy_pos):
            # deleting part here

Here is what makes my player and enemy:

enemy_size = 50
enemy_pos = [random.randint(0,WIDTH-enemy_size), 0]
enemy_list = [enemy_pos]


def drop_enemies(enemy_list):
    delay = random.random()
    if len(enemy_list) < 10 and delay < 0.1:
        x_pos = random.randint(0,WIDTH-enemy_size)
        y_pos = 0
        enemy_list.append([x_pos, y_pos])

def draw_enemies(enemy_list):
    for enemy_pos in enemy_list:
        pygame.draw.rect(screen, RED, (enemy_pos[0], enemy_pos[1], 
        enemy_size, enemy_size))

def update_enemy_positions(enemy_list, score):
    for idx, enemy_pos in enumerate(enemy_list):
        if enemy_pos[1] >= 0 and enemy_pos[1] < HEIGHT:
            enemy_pos[1] += SPEED
        else:
            enemy_list.pop(idx)
            score += 1
     return score

Player part:

player_size = 50
player_pos = [WIDTH/2, HEIGHT-2*player_size]

pygame.draw.rect(screen, TEAL, (player_pos[0], player_pos[1], player_size, 
player_size))
like image 742
Kromydas Avatar asked Jul 31 '26 09:07

Kromydas


1 Answers

The best way to solve your issue is to learn how to use Sprite objects in pygame. Together with Group objects, they can already do what you want, right out of the box.

In brief, your "enemy" should be an instance of some Sprite subclass, and you'd add it to an instance of Group (rather than building your own enemy_list). When you want the enemy to die, you can call the kill() method on it, which will remove it from the Group. This serves to delete it from the game, since you should be using methods on the Group object to update and draw all the sprites it contains (but not ones that have been killed).

like image 152
Blckknght Avatar answered Aug 01 '26 23:08

Blckknght