Search code examples
pythonobjectpygameinstancedel

Instance of a class not being destroyed with del


I'm trying to delete an object (in this case, and instance of a Fruit class) when it intersects with the head of my snake. The problem is that when it detects a fruit object, del doesn't appear to do anything. I don't know if I'm not implementing the delete function correctly, or it may be something to do with how I am feeding the objects to the function.

Here's part of the main.py script that deals the game functionality:

    # Main loop
    while running:
        # event handling, gets all event from the event queue
        for event in pygame.event.get():
            # only do something if the event is of type QUIT
            if event.type == pygame.QUIT:
                # change the value to False, to exit the main loop
                running = False

        # Modify game fruit properties
        if fruit_tick < 50:
            fruit_tick += 1
        else:
            game.spawn_fruit()
            fruit_tick = 0

        # Modify game player properties
        if not game.player_python:
            game.spawn_player()
        else:
            game.player_python.move()
            game.player_python.detect_object(game.get_objects())

        # Modify display properties
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        game.draw_shapes()
        pygame.display.flip()

Here's the function that is being executed when the head is at the same position of a Fruit object:

    # Detect object
    def detect_object(self, objects):
        for obj in objects:
            if obj.pivot == self.location:
                if isinstance(obj, Fruit):
                    self.grow(obj.get_growth())
                    del obj

If I add a print() statement under if isinstance(obj, Fruit):, it executes no problem. The problem is that del obj does nothing.


Solution

  • Don't delete iterator variable or items in a list while looping over it as that's a bad practice, whatever, try another way. Maybe some objects can be deleted this way:

    # Detect object
    def detect_object(self, objects):
        del_indices = []
    
        for i in len(objects):
            obj = objects[i]
    
            if obj.pivot == self.location:
                if isinstance(obj, Fruit):
                    self.grow(obj.get_growth())
                    # del obj
                    del_indices.append(i)
    
        # Remove some objects
        new_objects = []
    
        for i in len(objects):
            if not i in del_indices:
                new_objects.append(objects[i])
    
        objects = new_objects
        # return objects