导致游戏延迟的原因是什么?

时间:2021-05-04 12:00:16

标签: python pygame lag

我用pygame用python做了一个很简单的游戏,不知道为什么会卡顿,有人可以帮帮我吗?

我试图自己修复它,但我不能,我也找不到在线修复它的方法。

这不是因为我的电脑,它有 16 GB 的 RAM、512 GB 的固态硬盘、处理器:英特尔酷睿 i7-7600U 2.90 GHz。

这是代码:

import pygame

pygame.init()

win = pygame.display.set_mode((500, 500))

pygame.display.set_caption("Platformer")

colour = (255, 0, 0) # Colour red
x = 50
y = 50
width = 40
height = 60
vel = 5

isJump = False
jumpCount = 10

run = True

while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x > vel:
        x = x - vel

    if keys[pygame.K_RIGHT] and x < 500 - width - vel:
        x = x + vel

    if not(isJump):

        if keys[pygame.K_UP] and y > vel:
            y = y - vel

        if keys[pygame.K_DOWN] and y < 500 - height - vel:
            y = y + vel

        if keys[pygame.K_SPACE]:
            isJump = True

    else:
        if jumpCount >= -10:
            neg = 1
            if jumpCount < 0:
                neg = -1
            y = y - (jumpCount ** 2) * 0.5 * neg
            jumpCount = jumpCount - 1
            
        else:
            isJump = False
            jumpCount = 10
            

    win.fill((0, 0, 0))
    pygame.draw.rect(win, colour, (x, y, width, height))
    pygame.display.update()
    

pygame.quit()

1 个答案:

答案 0 :(得分:0)

应用程序滞后,因为应用程序循环中的延迟很大。删除延迟:

pygame.time.delay(100)


使用 pygame.time.Clock 控制每秒帧数,从而控制游戏速度。

tick() 对象的方法 pygame.time.Clock 以这种方式延迟游戏,即循环的每次迭代消耗相同的时间段。见pygame.time.Clock.tick()

<块引用>

这个方法应该每帧调用一次。

这意味着循环:

<块引用>
clock = pygame.time.Clock()
run = True
while run:
   clock.tick(60)

每秒运行 60 次。


完整示例:

import pygame

pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Platformer")

colour = (255, 0, 0) # Colour red
x = 50
y = 50
width = 40
height = 60
vel = 5

isJump = False
jumpCount = 10

clock = pygame.time.Clock()
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and x > vel:
        x = x - vel
    if keys[pygame.K_RIGHT] and x < 500 - width - vel:
        x = x + vel

    if not(isJump):
        if keys[pygame.K_UP] and y > vel:
            y = y - vel
        if keys[pygame.K_DOWN] and y < 500 - height - vel:
            y = y + vel
        if keys[pygame.K_SPACE]:
            isJump = True

    else:
        if jumpCount >= -10:
            neg = 1
            if jumpCount < 0:
                neg = -1
            y = y - (jumpCount ** 2) * 0.5 * neg
            jumpCount = jumpCount - 1
            
        else:
            isJump = False
            jumpCount = 10
            

    win.fill((0, 0, 0))
    pygame.draw.rect(win, colour, (x, y, width, height))
    pygame.display.update()

pygame.quit()
相关问题