首页 > 解决方案 > 我尝试在某个时间点在 pygame 中插入一个字符。我究竟做错了什么?

问题描述

我试图在某个时刻在我的窗口中显示一个角色。我究竟做错了什么?

这是我的第一个游戏,我是 pygame 的新手。我尝试了谷歌给我的代码。

screenwidth = 800
screenheight = 600

win = pygame.display.set_mode((screenwidth, screenheight))

bg = pygame.image.load("bg.png")
char = pygame.image.load("char.png")

x = 400
y = 300
vel = 5

isJumping = False
running = True

clock = pygame.time.Clock()


def redrawBackground():
    win.blit(bg, (0, 0))    
    pygame.display.update()

def player(x, y):
    win.blit(char, (x, y))

while running:
    clock.tick(60)
    pygame.time.delay(50)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        player_one_x -= vel

    if keys[pygame.K_RIGHT]:
        player_one_x += vel

    if not(isJumping):
        if keys[pygame.K_SPACE]:  
            for i in range(10):
                player_one_y -= vel

        isJumping = True
    player(x, y)
    redrawBackground()

我希望这段代码的结果显示名为“char.png”的文件,但它没有显示出来。

标签: python-3.xpygame

解决方案


您的代码正在绘制播放器,然后用背景覆盖它:

while running:
    #...
    player(x, y)
    redrawBackground()

这可能会更好:

def redrawBackground():
    win.blit(bg, (0, 0))    
    # removed the call to pygame.display.update()

while running:
    #...
    redrawBackground()
    player(x, y)
    pygame.display.update()

推荐阅读