user3482826
user3482826

Reputation: 3

Python: Using variable in for loop for substitution

I'm trying to condense repetition in a Python program that utilizes pygame. I currently have some number of lines that are like this:

if pygame.key.get_pressed()[pygame.K_q]: q.PerformNote()
if pygame.key.get_pressed()[pygame.K_w]: w.PerformNote()
if pygame.key.get_pressed()[pygame.K_e]: e.PerformNote()
if pygame.key.get_pressed()[pygame.K_r]: r.PerformNote()
if pygame.key.get_pressed()[pygame.K_t]: t.PerformNote()

I would like to achieve something like this:

keyList = ['q', 'w', 'e', 'r', 't']
for currentKey in keyList:
    if pygame.key.get_pressed()[pygame.K_currentKey]:
        currentKey.PerformNote()

The resulting error is

AttributeError: 'module' object has no attribute 'K_currentKey'

I think I might have spent too much time in BASH recently as this construct makes perfect sense to my brain. I've searched around with no idea of the proper way to implement this.

Upvotes: 0

Views: 270

Answers (2)

bpmason1
bpmason1

Reputation: 1940

if you want to retrieve a class member from a string with its name then try:

keyList = ['q', 'w', 'e', 'r', 't']
for currentKey in keyList:
    if pygame.key.get_pressed()[getattr(pygame, 'K_' + currentKey)]:
        currentKey.PerformNote()

Upvotes: 1

Claudiu
Claudiu

Reputation: 229361

Map pygame keys to their corresponding variables:

keyMap = {
    pygame.K_q: q,
    pygame.K_w: w,
    pygame.K_e: e,
    pygame.K_r: r,
    pygame.K_t: t,
}

Then you can do:

pressed = pygame.key.get_pressed()
for key, toProc in keyMap.items():
    if pressed[key]:
        toProc.PerformNote()

Upvotes: 6

Related Questions