【问题标题】:Python PyGame image (Donkey Kong) not movingPython PyGame 图像(大金刚)不动
【发布时间】:2019-12-25 07:45:51
【问题描述】:

我制作了一个简单的 pygame,它应该用箭头键左右移动驴图像。驴图像在文件夹中并且已经出现,但它不会左右移动。如果有帮助,我在 python 3.7 上。

我已经找了半个多小时,但我不明白为什么它不起作用,请帮忙。

这是我的代码:

import pygame
from pygame.locals import*
charx = 1
chary = 1
vel = 10
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Pygame")
char = pygame.transform.scale(pygame.image.load('donkey.jpg'), (128, 128))

keys = pygame.key.get_pressed()
clock = pygame.time.Clock()
run = True
while run:
    clock.tick(10)

    if keys[pygame.K_LEFT]:
        charx = charx - vel
    elif keys[pygame.K_RIGHT]:
        charx = charx + vel
    else:
        run = False
    run = True

    win.blit(char,(charx, chary))
    pygame.display.update()

当我运行程序时,窗口会出现,左上角有大金刚。但他没有用箭头键移动。

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    我不确定具体原因,但如果您添加事件循环,它就可以工作。
    您还需要在while 循环内移动keys = pygame.key.get_pressed() 行。

    while run:
        #add the following 3 lines, to check over events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            charx = charx - vel
        elif keys[pygame.K_RIGHT]:
            charx = charx + vel
        else:
            run = False
        run = True
    
        win.blit(char,(charx, chary))
        pygame.display.update()
        clock.tick(10)
    

    我只能猜测如果pygame.event.get() 没有在主循环中消耗,pygame.key.get_pressed() 将无法正常工作。

    【讨论】:

    • 非常感谢,这工作除了 sys.exit() 部分。我想我需要导入 sys 什么的。身份证
    • 是的。 import sys。当您单击 x 关闭窗口时,这将允许程序终止。
    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2016-08-20
    相关资源
    最近更新 更多