Search code examples
pythonpygamelagpython-3.10

My Program Is Very Laggy. I use Python/Pygame


I'm trying to make a game where a ball bounces off the edges of the window. My problem is it is super laggy. I have no idea why. I am using python3.10 and pygame. Whoever finds the answer thank you so much. Below is the source code to my game. If you fix it please leave the source code to the fixed game because I am new to python and will probally mess up putting it in myself. lol

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()

Solution

  • You have added your main game logic inside the event loop rather than the game loop. In a nutshell, the event loop only runs when there's an event occurring, so the ball only moves when there's an event happening on the window(in this case, movement of the mouse). To fix this all you have to do is put all the main game loop logic outside the event loop.

    # 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()
    

    The game loop will always run every frame, so the ball will move smoothly.