This is my function for generating an apple, I want it to generate a random color each time the snake eats it.

    def AppleGenerator():
        fruit_colors = [crimson,powderblue,yellow,hotpink,orange,darkorchid,lime]
        x = random.randrange(1,6)
        return fruit_colors[x]

This is when I call it, AppleX, AppleY, and size are just the dimensions of the rectangle. The problem is that the 'apple' just flashes random different colors from the list and doesn't stick to one color.


By the way, the reason why I didn't just simply do

def AppleGenerator():
   fruit_colors = [crimson,powderblue,yellow,hotpink,orange,darkorchid,lime]
   return random.randrange(fruit_colors[0],fruit_colors[6])

is because the colors are tuples, and randrange() only accepts integers.


1 Answer 1


You're calling the AppleGenerator() function every time you draw the fruit, so each time you draw it, that function gives it a new random colour.

You need to only call it whenever the fruit is created, then store the colour result and pass that in instead.

Something like:

// Get colour (call this once per apple)
apple_colour = AppleGenerator()

// Draw the appple (call this every frame)
pygame.draw.rect(gameScreen, apple_colour, [AppleX,AppleY,size,size])

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .