Liam Emery Liam Emery - 3 months ago 20
Python Question

How can I 'cycle' through list items when using classes in python pygame to change object colors?

I have drawn a caterpillar using

pygame.draw
and it's color is set as
self.color_scheme[0]
For example.

self.color_scheme = [red,yellow,purple]
...
...
pygame.draw.ellipse(screen, self.color_scheme[0], [x, y, 40, 45])


What I'm trying to enable is that when the user presses a key, lets say
s
then the color will change to
self.color_scheme[1]
or
self.color_scheme[2]


Something along the lines of

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
#scroll through self.color_scheme or randomly select a color

Answer

To cycle:

self.color_scheme_idx = -1

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_s:
        self.color_scheme_idx += 1
        pygame.draw.ellipse(screen, self.color_scheme[self.color_scheme_idx], [x, y, 40, 45])

To randomize:

import random

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_s:
        pygame.draw.ellipse(screen, random.choice(self.color_scheme), [x, y, 40, 45])
Comments