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