pygame-examples icon indicating copy to clipboard operation
pygame-examples copied to clipboard

the apple desapairs

Open gabopython opened this issue 2 years ago • 1 comments

sometimes there is no apple to eat, i think it takes the same position then the rock

gabopython avatar Mar 01 '23 17:03 gabopython

It seems like both snake.py and snake2.py don't keep track of position of Snake, Apple and Stone. To fix this, you could create a global array and insert the position of each created object (Apple, Snake and Stone). Then you could try to generate a new position until you get one that is not in the array yet.

It could look like this:

# Global array to keep track of positions of all spawned objects
init_positions = []

# Function to generate a unique position
def get_random_position():

    # Lambda function to generate random position within the game screen
    random_position = lambda: (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE)

    # Generate initial random position
    position = random_position()

    # Keep generating a new position until it's one that is not in the array yet
    while(position in init_positions):
        position = random_position()

    # Store the new position
    init_positions.append(position)

    # Return the newly generated position
    return position

And then replace the position assignments in both the Rock and Snake class from

        self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE)    

to

        self.position = get_random_position()

rFurgan avatar Nov 16 '24 15:11 rFurgan