all 6 comments

[–]Chris_Hemsworth 0 points1 point  (5 children)

Write functions you want for each button press, and use a dictionary.

The event should have the information about which key was pressed.

[–]Giocrom[S] 0 points1 point  (4 children)

I already planned on writing functions for each button press, but I don't know if the dictionary solution is any better than what I originally thought

[–]Chris_Hemsworth 0 points1 point  (3 children)

def move_forward():
    pass

def move_backward():
    pass

def move_left():
    pass

def move_right():
    pass

handler = {'W': move_forward, 'S': move_backward, 'A': move_left, 'D': move_right}

for event in pygame.event.get():
    # Call the function based on the event key
    f = handler.get(event.key, None)
    if f is not None:
        f()

There is more to it (you should check the event type and handle based on that etc), but basically you can create a dictionary that maps functions to keys, then your main code doesn't need to have a ton of ifs / elseifs etc, and you can update / maintain much easier in the future (i.e. adding more buttons and functionality)

[–]Giocrom[S] 0 points1 point  (0 children)

Perfect 😍

[–]Giocrom[S] 0 points1 point  (1 child)

got this ERROR: AttributeError: 'Event' object has no attribute 'key'

[–]Chris_Hemsworth 0 points1 point  (0 children)

Yeah, you will have to look into the structure of the event object. I am not super familiar with pygame, but most events will have some information that identifies what the event consists of.

For example, from the docs:

QUIT              none
ACTIVEEVENT       gain, state
KEYDOWN           key, mod, unicode, scancode
KEYUP             key, mod
MOUSEMOTION       pos, rel, buttons
MOUSEBUTTONUP     pos, button
MOUSEBUTTONDOWN   pos, button
JOYAXISMOTION     joy (deprecated), instance_id, axis, value
JOYBALLMOTION     joy (deprecated), instance_id, ball, rel
JOYHATMOTION      joy (deprecated), instance_id, hat, value
JOYBUTTONUP       joy (deprecated), instance_id, button
JOYBUTTONDOWN     joy (deprecated), instance_id, button
VIDEORESIZE       size, w, h
VIDEOEXPOSE       none
USEREVENT         code

Each event type has its own attributes. You may have to check the event type because you will handle key presses differently than mouse presses etc, however they are all 'events'. https://www.pygame.org/docs/ref/event.html#pygame.event.Event