Search code examples
pythonpython-3.xpygame2d-gamespygame-surface

How to customize a map in python3 whith events?


I can't set up changing the pack of blocks for drawing maps in the platformer. In theory, pressing numbers should work. All files are stored in a folder with the appropriate hierarchy.

what is the best format to write it in? method, class? I do not want to prescribe conditions for 100+ options

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_1:
            block_pack = 'dirt'
        elif event.key == pygame.K_2:
            block_pack = 'grass'
        elif event.key == pygame.K_3:
            block_pack = 'planet'
        elif event.key == pygame.K_4:
            block_pack = 'sand'
        elif event.key == pygame.K_5:
            block_pack = 'snow'
        elif event.key == pygame.K_6:
            block_pack = 'stone'
        elif event.key == pygame.K_7:
            block_pack = 'enemies'
        elif event.key == pygame.K_8:
            block_pack = 'tiles'
        elif event.key == pygame.K_9:
            block_pack = 'items'
        elif event.key == pygame.K_0:
            block_pack = 'bg'
block_img = pygame.image.load(f'PNG/Ground/{block_pack}/{block_pack}.png')
blockLeft_img = pygame.image.load(f'PNG/Ground/{block_pack}/{block_pack}Left.png')
blockRight_img = pygame.image.load(f'PNG/Ground/{block_pack}/{block_pack}Right.png')
blockMid_img = pygame.image.load(f'PNG/Ground/{block_pack}/{block_pack}Mid.png')

hierarchy


Solution

  • Yeah, a dict would be your best bet here. I know you have a lot of options (100+), but you're going to have to map it in some way. Dicts are fast and easy to access. The following code would be an option:

    keypress_options = {
       pygame.K_1: 'dirt',
       pygame.K_2: 'grass',
       pygame.K_3: 'planet',
       pygame.K_4: 'sand',
       pygame.K_5: 'snow',
       pygame.K_6: 'stone',
       pygame.K_7: 'enemies',
       pygame.K_8: 'tiles',
       pygame.K_9: 'items',
       pygame.K_0: 'bg'
    }
    

    and then you can access it using get to find out if that keypress is mapped to anything

    if option := keypress_options.get(event.key):
       do this