游戏延迟-障碍产生错误



我在这款简单的游戏中遇到了一个问题,即障碍的创造导致游戏严重滞后,并且变成了红色条纹而不是单个立方体:

import pygame
import random
pygame.init()
white = (225, 225, 225)
black = (0,0,0)
red = (225,0,0)
blue = (0,0,225)
clock = pygame.time.Clock()
millisToEvent = random.randint(500, 2001)
millisFromEvent = 0
gameDisplay = pygame.display.set_mode((300, 300))
pygame.display.set_caption("Jumpy!")
exitGame = False
touchingGround = False
Y = 180;
YV = 1;
obX = 300
grounded = True
fps = 200
def createObstacle(obX):
    obX = 300
    pygame.time.wait(random.randrange(200, 1600))
    while obX > -19:
        obX -= 0.1
        gameDisplay.fill(red, rect = [obX, 180, 20, 20])
        pygame.display.update()
while not exitGame:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exitGame = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                if grounded == True:
                    YV -= 3
                    Y += YV
    if Y <= 180:
        YV += 0.1
        Y += YV
        grounded = False
    else:
        YV = -0.1
        grounded = True
    gameDisplay.fill(white)
    gameDisplay.fill(blue, rect = [50, Y, 20, 20])
    gameDisplay.fill(black, rect = [0, 200, 300, 100])
    pygame.display.update()
    millisFromEvent += clock.tick(fps)
    if millisFromEvent > millisToEvent:
        createObstacle(obX)
        millisToEvent = random.randint(500, 2001)
        millisFromEvent = 0
    createObstacle(obX)
    clock.tick(fps)
pygame.quit()
quit()

你知道怎么解决这个问题吗?

很明显,您似乎认为您有多个线程正在进行,但是当您调用createObstacle时,它不会将控制返回到主循环,直到它完成运行。你需要在每一帧的正确位置绘制框,而不是在每一帧的所有位置。

要修复延迟,删除这行pygame.time.wait(random.randrange(200, 1600)),将fps设置为合理的值,例如60而不是200。另外,不要调用display。每帧更新整个屏幕一次以上。你可以在clock.tick(fps)之前调用一次。这也适用于时钟。打勾,每个循环只打一次。

遵循教程并检查(播放和修改!)包含的示例可能是一个好主意。

最新更新