为什么我的方块不动?我垃圾邮件的箭头键,但代码没有给出错误,只是没有工作的方式,它的意图

2024-09-30 10:27:41 发布

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

当我垃圾邮件的箭头键,没有任何工作,我的广场不会动摇。这是一个python课程的家庭作业,我真的需要帮助,所以谁知道为什么?如果是,请告诉我。。。请

    import pygame
    pygame.init()
    scrlengthX = 640
    scrlengthY = 480
    b = 20

    x = (scrlengthX-b)/2
    y = (scrlengthY-b)/2
    r = pygame.Rect(x,y,b,b)
    #this explains where the square is supposed to be
    while True:
        screen = pygame.display.set_mode([scrlengthX,scrlengthY])
        # size of the screen
        def draw():

            screen.fill([0,0,255])

            r = pygame.Rect(x,y,b,b)


            pygame.draw.rect(screen,(0,0,0), r)
            pygame.display.flip()

        a = 1
        while a == 1:
            draw()
                e = pygame.event.get(pygame.QUIT)
            print(e)
            if len(e) > 0:
                pygame.quit()

        k = pygame.event.get(pygame.KEYDOWN)
        for i in k:
            if i.key == pygame.K_UP:
                y = y-5
            if i.key == pygame.K_DOWN:
                y = y+5
            if i.key == pygame.K_LEFT:
                x = x-5
            if i.key == pygame.K_RIGHT:
                x = x+5
            # button detecting, but it does not work :(
            # this is where everything goes wrong, anybody help?

    pygame.quit()

Tags: thekeyrecteventifisdisplaythis
2条回答

试试这个微妙的变化:

k = pygame.event.get()
for i in k:
    if i.type == pygame.KEYDOWN:
        if i.key == pygame.K_UP:
            y -= 5
        if i.key == pygame.K_DOWN:
            y += 5
        if i.key == pygame.K_LEFT:
            x -= 5
        if i.key == pygame.K_RIGHT:
            x += 5

你可能把事情搞砸了吗

据我所知,您的程序在退出时只会离开while a==1循环,但所有的输入处理都落后于该循环

我认为,您可能希望增加代码的缩进,从k=...行开始

有了这个改变,代码对我来说就行了

相关问题 更多 >

    热门问题