user12291970
user12291970

Reputation:

Rendering text in pygame causes lag

I have write function in my functions module which looks like this

def write(size, writing, color, x,  y):
    font = pygame.font.SysFont("corbel", size)
    text = font.render(writing,  True, color)
    D.blit(text, (x, y))

I imported this to my main module and created a function as follows in the main module

def print_stats():
    write(30, f"Red player's hp {player2.hp}", (200, 50, 50),10, 10)
    write(30, f"Green player's hp {player1.hp}", (50, 200, 50),10, 60)

As long as i dont put print_stats() in the main loop, the game runs perfectly fine, however, as soon i i try to run this function, it heavily drops FPS. I dont see anything in the code that could cause lag, what am i doing wrong? Thanks

Edit: Dont know if this is relevnet but i forgot to mention that i put pygame.init() in all the modules i have imported from as this is my first time using modules and i was unsure.

Upvotes: 1

Views: 972

Answers (1)

Rabbid76
Rabbid76

Reputation: 210890

Avoid to create the font object in every frame.
Create a font dependent on the size before the application loop. e.g:

font30 = pygame.font.SysFont("corbel", 30)  
def write(font, writing, color, x, y):
    text = font.render(writing,  True, color)
    D.blit(text, (x, y))
def print_stats():
    write(font30, f"Red player's hp {player2.hp}", (200, 50, 50), 10, 10)
    write(font30; f"Green player's hp {player1.hp}", (50, 200, 50), 10, 60)

That doesn't solve the issue, that the text is rendered in every frame. If it is still lags, then you have to render the text surface once, when player1.hp respectively player2.hp is changed. e.g:

class Player:
    def __init__(self, color, name):
        self.color = color
        self.name = name
        # [...]

    def ChangeHp(self, val):
        self.hp += val
        self.hptext = font30.render(f"{self.name} player's hp {self.hp}", True, self.color)
D.blit(player1.hptext, (10, 60))

Upvotes: 3

Related Questions