Home > Net >  Pygame runs slower after splitting the game into different files
Pygame runs slower after splitting the game into different files

Time:04-07

I've written a simple game in pygame. It used to be all in one file, but I decided to keep it clean, so I separated the code into different scripts. After doing so, the game runs much slower than before. I believe the lag is caused by refering to imported variables and functions every frame, but yet still don't know how to fix the issue. Here's the code, hope you can help:

main.py

import pygame
import player
import window

def main():
    pygame.init()

    running = True

    clock = pygame.time.Clock()

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

        window.refresh()
        player.run()

        clock.tick(window.FPS)
        print(clock.get_fps())
        pygame.display.update()

    pygame.quit()

if __name__ == "__main__":
    main()

player.py

import pygame
from math import sqrt
from window import WIDTH, HEIGHT, WIN
from classes import *

player = Obj(50, 50, 50, 10)

def normalize(x, y):
    if x != 0 and y != 0:
        return (x / sqrt(2), y / sqrt(2))
    return (x, y)


def movement(obj: Obj):
    keys = pygame.key.get_pressed()

    startx = obj.x
    starty = obj.y

    x = 0
    y = 0

    if keys[pygame.K_w]:
        y -= obj.vel
    if keys[pygame.K_d]:
        x  = obj.vel
    if keys[pygame.K_a]:
        x -= obj.vel
    if keys[pygame.K_s]:
        y  = obj.vel

    pos = normalize(x, y)

    obj.x  = pos[0]
    obj.y  = pos[1]

    speed = abs(sqrt((obj.x - startx) ** 2   (obj.y - starty) ** 2))
    # print(speed)


def on_track(obj: Obj):
    if obj.x >= WIDTH - obj.size:
        obj.x = WIDTH - obj.size
    if obj.x <= 0:
        obj.x = 0
    if obj.y >= HEIGHT - obj.size:
        obj.y = HEIGHT - obj.size
    if obj.y <= 0:
        obj.y = 0


def run():
    pygame.draw.rect(WIN, (Color.black), (player.x, player.y, player.size, player.size))
    movement(player)
    on_track(player)
    pygame.display.update()

window.py

from classes import *
import pygame

WIDTH, HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game")
FPS = 60


def refresh():
    WIN.fill(Color.white)

classes.py

class Color(): 
    white = (255, 255, 255)
    black = (0, 0, 0)
    blue = (0, 0, 255)
    red = (255, 0, 0)
    green = (0, 255, 0)


class Obj():
    def __init__(self, x, y, size, vel):
        self.x = x
        self.y = y
        self.size = size
        self.vel = vel

Thank you in advance!

CodePudding user response:

You call pygame.display.update twice (in player.run and main.main). Removing it from player.run solves the problem.

  • Related