I was writing a feature for a game where the user can press a key on the keyboard and that would change the colour of all the objects drawn on the screen to that colour. For example, if g
is pressed, everything turns green.
To do this, I could write:
while True:
while start==True:
clock.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == K_SPACE:
start =False
match_start=time.time()
if event.key==K_w:
colour=white
elif event.key==K_g:
colour=green
elif event.key==K_y:
colour=yellow
elif event.key==K_b:
colour=blue
elif event.key==K_r:
colour=red
elif event.key==K_p:
colour=purple
This code works perfectly well. However, I need to write the exact same code later on. To avoid repetition, I considered encapsulating the code using a function like this:
def set_colour():
if event.key==K_w:
colour=white
elif event.key==K_g:
colour=green
elif event.key==K_y:
colour=yellow
elif event.key==K_b:
colour=blue
elif event.key==K_r:
colour=red
elif event.key==K_p:
colour=purple
Then later in the program I could call the function on multiple occassions at several different points in the code, like this:
while True:
while start==True:
clock.tick(30)
for event in pygame.event.get():
if event.type ==QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key ==K_SPACE:
start =False
match_start=time.time()
set_colour()
Unfortunately, this does not work. I have not received an error message, but the colour does not change when one of the defined keys is pressed. I think this is something to do with the function requiring more input data, but I'm not sure.
I would appreciate any advice you can give.
It doesn't seem like you've passed the event to your set_colour()
function for it to use and then your function doesn't return back the chosen color or do anything with it for the colour to change. It seems like your function is only changing the local colour
variable instead of the one in the scope for where the function is called.
You probably want to change the function to return the chosen colour
and have the event be passed in as a parameter like this:
def set_colour(event):
colour = None # Make sure colour is initialized
if event.key == K_w:
colour = white
elif event.key == K_g:
colour = green
elif event.key == K_y:
colour = yellow
elif event.key == K_b:
colour = blue
elif event.key == K_r:
colour = red
elif event.key == K_p:
colour = purple
return colour
Then in your code where you call this function do it like so:
colour = set_colour(event)