Is it possible to set event.key to a variable?

Viewed 115

I'm working on a small project in Python, just to learn more about the language, but have run into a problem. I am trying to set a random variable, and whenever I press the corresponding number on the keyboard, I win the game. However, I don't know if I am able to set the event.key variable to a string, or another variable that will change along with the random number.

import pygame
import sys
import random

pygame.init()

key = random.randint(0,9)
key2 = ('K_', key)

window = pygame.display.set_mode((300, 300))

pygame.display.set_caption('Text Editor')
font_color = (0, 150, 250)
font_obj = pygame.font.SysFont('forte', 25)

text_obj = font_obj.render(str(key), True, font_color)
won = font_obj.render('you won', True, font_color)
while True:
    window.fill((255,255,255))
    window.blit(text_obj,(22,0))
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==key2:
                window.blit(won,(22,50))
                print('you won')
    pygame.display.update()
1 Answers

In Pygame, keys are referenced via constants defined in pygame.locals. You should compare your key event against one of those:

from pygame.locals import *

num_keys = [K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9]
target = random.choice(num_keys)

# ...

while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key == target:
            window.blit(won, (22,50))
            print('you won')
Related