Instead of doing a long if..elif
, is there a way to store code in a list
or dictionary to be run? Something like:
my_dict = {'up': 'y=y+1', 'down': 'y=y-1', 'left': 'x=x-1', 'right': x=x+1'}
Then you match up the choice to the dict
and run the result?
Or is the next best thing to a traditional if..elif
chain a conditional expression:
x = x+1 if choice == 'right' else x-1 if choice == 'left' else x
y = y+1 if choice == 'up' else y-1 if choice == 'down' else y
Part of the reason I am asking, apart from sheer curiosity, is that I am writing a game in Pygame to help learn Python coding. I have 12 keys I am checking for being pressed, and I am using a very long and ungainly if..elif
structure that makes me think there has to be a more beautiful way of doing it. Basically what I have looks like this:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_t:
red += 10
elif event.key == pygame.K_g:
red -= 10
elif event.key == pygame.K_5:
red += 1
elif event.key == pygame.K_b:
red -= 1
elif event.key == pygame.K_y:
green += 10
elif event.key == pygame.K_h:
green -= 10
elif event.key == pygame.K_6:
green += 1
elif event.key == pygame.K_n:
green -= 1
elif event.key == pygame.K_u:
blue += 10
elif event.key == pygame.K_j:
blue -= 10
elif event.key == pygame.K_7:
blue += 1
elif event.key == pygame.K_m:
blue -= 1
Is that what my Python code is supposed to look like? Or is there a more Pythonic way to code this?