繁体   English   中英

我的程序非常滞后。 我使用 Python/Pygame

[英]My Program Is Very Laggy. I use Python/Pygame

我正在尝试制作一个球从 window 的边缘反弹的游戏。 我的问题是它超级滞后。 我不知道为什么。 我正在使用 python3.10 和 pygame。 谁找到答案,非常感谢。 下面是我的游戏的源代码。 如果您修复它,请将源代码留给已修复的游戏,因为我是 python 的新手,可能会搞砸自己。 哈哈

import pygame

init()

S0 = 640
S1 = 480

screen = display.set_mode((S0, S1))
display.set_caption("Zero-Player-Game")

clock = pygame.time.Clock()

x = 10
y = 10

dx = 2
dy = 1

Black = (0, 0, 0)
White = (255, 255, 255)

p_size = 50

end = False

while not end:
    for e in event.get():
        if e.type == QUIT:
            end = True
        x += dx
        y += dy
        if y < 0 or y > S1 - p_size:
            dy *= -1
        if x < 0 or x > S0 - p_size:
            dx *= -1
        screen.fill(Black)
        draw.ellipse(screen, White, (x, y, p_size, p_size))
        clock.tick(100)
        pygame.display.update()

您已在事件循环而不是游戏循环中添加了主游戏逻辑。 简而言之,事件循环仅在发生事件时运行,因此球仅在窗口上发生事件时移动(在本例中为鼠标移动)。 要解决此问题,您只需将所有主游戏循环逻辑放在事件循环之外。

# Game loop
while not end:
    # Event loop
    for e in event.get():
        if e.type == QUIT:
            end = True
    # Game logic
    x += dx
    y += dy
    if y < 0 or y > S1 - p_size:
        dy *= -1
    if x < 0 or x > S0 - p_size:
        dx *= -1
    screen.fill(Black)
    draw.ellipse(screen, White, (x, y, p_size, p_size))
    clock.tick(100)
    display.update()

游戏循环将始终运行每一帧,因此球会平稳移动。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM