How to check for variable key presses in pygame

I have been trying to create a game using pygame and I am struggling to get pygame to check for a keypress based on a variable.

The code I have so far is:

import random, pygame, sys
from pygame.locals import *
points=0
pygame.init()

screen = pygame.display.set_mode((600,350))
pygame.display.set_caption("LETTERPRESS")

while True:
FONT = pygame.font.SysFont("Comic Sans MS",30)
Letter=random.randint(1,26)
Letters={
    1 :"a",
    2 :"b",
    3 :"c",
    4 :"d",
    5 :"e",
    6 :"f",
    7 :"g",
    8 :"h",
    9 :"i",
    10:"j",
    11:"k",
    12:"l",
    13:"m",
    14:"n",
    15:"o",
    16:"p",
    17:"q",
    18:"r",
    19:"s",
    20:"t",
    21:"u",
    22:"v",
    23:"w",
    24:"x",
    25:"y",
    26:"z"}
label = FONT.render(Letters[Letter],1,(255,0,0))
screen.blit(label,(285,160))
pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_[Letters[Letter]]:
                points +=1
                break

The problematic part of the code is:

if event.key == pygame.K_[Letters[Letter]]:

Also, if you have any ways that I can clean up my program, please tell me.

Upvotes: 3

Views: 688

Answers (1)

James K
James K

Reputation: 3752

One fix would be to change the dictionary to

 Letters={
    1 :pygame.K_a,
    2 :pygame.K_b,
    3 :pygame.K_c,

and so on, then if event.key == Letters[Letter]:

For general clean-up, you can take this to code-review, in particular, I see no reason to use a dictionary instead of a list for Letters

Letters = [pygame.K_a, pygame.K_b ...]

List are 0 indexed so you would need to remember that 0 is 'a' and so on.

You could improve label = FONT.render(Letters[Letter],1,(255,0,0)) as label = FONT.render(chr(Letter+65),1,(255,0,0)), which removes the need for the values in Letters to be literal letters.

Finally there is a syntax error with the line if event.type == pygame.KEYDOWN: as it is not followed by an indented block.

Upvotes: 3

Related Questions