创建包含关键事件的列表并在Pygam中使用

2024-06-16 12:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,所以你可能会觉得这很愚蠢,是的,我是一个初学者,当谈到编程,但有可能这样做吗?我的朋友试图用一些额外的代码来完成它,但它甚至无法启动。我很肯定我把清单弄乱了,所以我很感激你的提示和更正:)

import time

character_list = [a,b,c,d] # creating list with characters
buttons_list = [pygame.K_a,pygame.K_b,pygame.K_c,pygame.K_d]#creating list with key-events
while True:

    millis = int(round(time.time()*1000))
    hours = int(round( millis / 3600000))
    # print a letter to the screen with character_list[hours]
    necessary_button  = buttons_list[hours]
    if event.type == pygame.KEYDOWN:
        if event.key == necessary_button:
            # do some awesome stuff

这是我朋友给我的密码:

    import pygame

    pygame.init()

    display_width = 1600
    display_height = 900

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

    game_display = pygame.display.set_mode((display_width,display_height))
    pygame.display.set_caption('AYYLMAO')

    smallfont = pygame.font.SysFont("comicsansms",25)

    def text_objects(text,color,size):
        if size == "small":
            textSurf = smallfont.render(text, True, color)
        return textSurf, textSurf.get_rect()



    def message_to_screen(msg, color, y_displace = 0,size = "small"):
        textSurf, textRect = text_objects(msg,color,size)
        textRect.center = (display_width/2), ( display_height/2)+y_displace
        game_display.blit(textSurf, textRect)

    def gameLoop():
        game_display.fill(white)
        character_list = ["a","b","c","d","e"]
        buttons_list = [pygame.K_a, pygame.K_b, pygame.K_c, pygame.K_d, pygame.K_e]

        message_to_screen(character_list[0], red)
        pygame.display.update()
        necessary_button = buttons_list[0]
        if event.type == pygame.KEYDOWN:
            if event.key == necessary_button:
                message_to_screen(GG, red)
            if event.key == pygame.K_ESCAPE:
                pygame.QUIT()


    gameLoop()

这至少会把“a”打印到屏幕上,但我得到一个错误:“第38行,在gameLoop中 如果事件类型== pygame.KEYDOWN键: NameError:未定义全局名称“event”。“我希望这不仅仅是我犯的另一个愚蠢的错误:D


Tags: tokeytexteventifdisplaybuttonscreen