0

I am attempting to make something like a simple 2D game engine. It's not really, but kinda. The point of it is to allow for not just square tiling but triangular and hexagonal tiling as well. I'm using pygame for it, so it's also an easier way to access pygame. Anyways, I'm currently working on the button input. I have this rn:

def keyboardInput(key: str):
    keys=pygame.key.get_pressed()
    if keys[pygame.key.key_code(key)]:
        return True
    else:
        return False

I think this is currently working tho but it seems like there’s still a problem. Maybe it’s with the code in main.py.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

2 Answers2

0

No, there is no pygame function that converts a string into the pygame key enumerator. See pygame.key module. You have to create your own dictionary that maps a string to a key. e.g.:

key_map = { 
    "left" : pygame.K_LEFT,
    "right" : pygame.K_RIGHT,
    ... 
}
def keyboardInput(key: str):
     keys = pygame.key.get_pressed()
     return key in key_map and keys[key_map[key]]

Alternatively you can get key enumerator constant with getattr:

import pygame.locals

def keyboardInput(key: str):
    keys = pygame.key.get_pressed()
    try:
        return keys[getattr(pygame.locals, "K_" + key)]
    except:
        return keys[getattr(pygame.locals, "K_" + key.upper())]

In any case you need to handle the events. See pygame.event.get() respectively pygame.event.pump():

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.

Therefor you must call pygame.event.pump() once in every frame. You can do this in an another function:

def updateInput():
    pygame.event.pump()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

You can use getattr to perform any kind of variable lookup:

key=getattr(pygame.locals,key)

Using locals reduces the number of meaningless hits (like mixer). Of course, you could just write

from pygame import locals as magic

to provide the real constants as (say) ….magic.K_TAB. Or, if you want to provide a single module that has those constants and some interface of your own, do

from pygame.locals import *

in that module. (It’s usually considered bad form to use import * to avoid qualification, but here you would be using it to adapt qualification.)

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • @Rabbid76: I don’t see any statement about the form of the string in the question. One could upcase multi-character inputs and add `K_` if that mattered. Of course, there **is** [key_code](https://www.pygame.org/docs/ref/key.html#pygame.key.key_code) in pygame 2, which was added to the question while I was writing a (more generic) answer and is probably a better answer to the original question! – Davis Herring Dec 11 '21 at 20:50