Advertisements
I am making a Calculator with Pygame and I want to check if the user has pressed a key which is an integer. If the key is an integer like 1 or 2 then blit the number onto the screen.
I have tried but many times but failed
Here’s my code
import pygame, math
pygame.init()
screen_width = 1200
screen_height = 500
gameWindow = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Calculator')
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
black = (0, 0, 0)
grey = (128, 128, 128)
font = pygame.font.SysFont('comicsans', 40)
fps = 60
clock = pygame.time.Clock()
def text_screen(text, color, x, y):
screen_text = font.render(text, True, color)
gameWindow.blit(screen_text, [x ,y])
def welcome_screen(run):
clock.tick(fps)
gameWindow.fill(grey)
while not run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = True
if event.type == pygame.KEYDOWN:
if event.key == # Code to check whether the key is integer or not:
pass
pygame.display.update()
def gameLoop(run):
clock.tick(fps)
gameWindow.fill(grey)
while not run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = True
pygame.display.update()
if __name__ == "__main__":
welcome_screen(False)
>Solution :
You could convert the keycode to representing character, then check if that is a digit with isdigit().
if event.type == pygame.KEYDOWN:
if pygame.key.name(event.key).isdigit():
pass # Do stuff