2

I'm trying to make code that checks if the letter the user pressed was the first letter of any word in a list of strings using pygame, the list is generated by urrlib importing from a web page then I have code as follows to check pygame.init() pygame.display.set_mode((100, 100))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if x[str(event.key)] in [i[0] for i in final]:
                return('Forward')
            else:
                return 'nope', final

but when I run the code it only prints 'nope' and an empty list, I tried wrapping it in a function and calling it afterwards but I got the error TypeError: 'Function' object has no attribute getitem

Note: final is the list of words and x is a dict referring to the value of each letter since event.key returns an int id

1 Answer 1

3

event.keys are just integers and if you convert them into strings, you only get strings like '97' or '115'.

You should use the event.unicode attribute if you need the actual letter. Then you can use the any function and pass this generator expression, any(word.lower().startswith(event.unicode) for word in strings) to see if a word starts with the entered letter.

import pygame as pg

pg.init()

screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
strings = ['some', 'Random', 'words']

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            print(event.unicode)
            if any(word.lower().startswith(event.unicode) for word in strings):
                print('Forward')
            else:
                print('nope')

    screen.fill(BG_COLOR)
    pg.display.flip()
    clock.tick(30)

pg.quit()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.