K_1 is hitting the 1 key on the keyboard, I don't know if it is possible to put a variable into the actual pygame.K_ parameter. if I could figure out a way to add a variable to this I could condense my code down a lot because I am using this type of repetition on multiple occasions. I am making sudoku for anyone who is wondering
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
numList[cell_num] = "1"
if keys[pygame.K_2]:
numList[cell_num] = "2"
if keys[pygame.K_3]:
numList[cell_num] = "3"
if keys[pygame.K_4]:
numList[cell_num] = "4"
if keys[pygame.K_5]:
numList[cell_num] = "5"
if keys[pygame.K_6]:
numList[cell_num] = "6"
if keys[pygame.K_7]:
numList[cell_num] = "7"
if keys[pygame.K_8]:
numList[cell_num] = "8"
if keys[pygame.K_9]:
numList[cell_num] = "9"
CodePudding user response:
I prefer event handling rather than looking at which keys are currently pressed. Presumably you're using a recent version of PyGame, so you should be able to handle TEXTINPUT
CodePudding user response:
To help reduce repetition I would use a for each
statement. Additonally I would create a dictionary with a key
and value
to store all your values.
To avoid confusion I have renamed your keys
variable as follows (we will be using a key
later for so want to avoid confusion):
key_pressed = pygame.key.get_pressed()
Then create a dictionary to hold all the pygame.K_parameters as the key
and set the value
to the number you want. This would look as follows:
thisdict = {
pygame.K_1: "1",
pygame.K_2: "2",
pygame.K_3: "3"
#...etc...
}
After this, we can write a for each
statement with an if
statement. This would iterate through the dictionary each time the key was pressed and compare the key_pressed
to the key
in the dictionary. If the values equal each other than set numList[cell_num]
to value
:
for key, value in thisdict.items()
if key_pressed == key :
numList[cell_num] = value
# you could use else if key_pressed is a key that isn't the ones you specifically want
There are probably a number of ways of doing this but this is how I would do it :)