Quinn R Quinn R - 22 days ago 10
Python Question

On-screen typing in Pygame

For a programming project in school I have to create a spelling game using pygame. However, as I am fairly new to this whole thing, I can't manage to work out how to allow the user to input letters and make them appear on the game display. This is my code so far (along with my failing attempt at solving this problem):

import pygame
import random

pygame.init()

display_width = 800
display_height = 600

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Spelling Game")
myfont = pygame.font.SysFont("Arial", 50)
clock = pygame.time.Clock()
mouse = pygame.mouse.get_pos()

city = pygame.image.load("city.png")

charac_str = "" #new string to store written character
# font object to render str to surface
font_renderer = pygame.font.SysFont("Arial",30)

def background(x,y):
gameDisplay.blit(city,(-200,-100))

with open("words.txt") as f:
WORDS = f.read().split()

def random_word():
return random.choice(WORDS)


gameExit = False
word = random_word()

while not gameExit:
#event-handling loop based on user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

gameDisplay.fill(white)

background(0,0)
textsurface = myfont.render(word, True, red)
gameDisplay.blit(textsurface, (340, 400)) #the random word

rendered_charac = font_renderer.render(charac_str, True, red)
gameDisplay.blit(rendered_charac, (100,100))

pygame.display.update()

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if pygame.K_0 < event.key < pygame.K_9: #checks key pressed
character = chr(event.key) #conv num to char
charac_str += str(character) # add num to end of string
gameDisplay.blit(charac_str) # display the input?doesn't work

Answer Source

pygame.KEYDOWN events have a unicode attribute which you can simply add to a string, e.g. text += event.unicode. Then the text is rendered and displayed in the main loop.

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 32)
    clock = pg.time.Clock()
    color = pg.Color('dodgerblue2')
    text = ''

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_RETURN:
                    print(text)
                    text = ''
                elif event.key == pg.K_BACKSPACE:
                    text = text[:-1]
                else:
                    text += event.unicode

        screen.fill((30, 30, 30))
        txt_surface = font.render(text, True, color)
        screen.blit(txt_surface, (50, 100))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()