pygame中渲染文本会导致延迟 [英] Rendering text in pygame causes lag

查看:88
本文介绍了pygame中渲染文本会导致延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的功能模块中有write个功能,看起来像这样

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)

只要我不将print_stats()放在主循环中,游戏就可以完美运行,但是,一旦我尝试运行此功能,它就会严重降低FPS.我没有在代码中看到任何可能导致延迟的内容,我在做什么错呢?谢谢

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

不知道这是否是relevnet,但我忘了提及我将pygame.init()放在我从中导入的所有模块中,因为这是我第一次使用模块,因此我不确定.

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.

推荐答案

避免在每个帧中创建字体对象.
在应用程序循环之前,根据字体大小创建字体.例如:

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)


这不能解决问题,因为文本在每个帧中都呈现.如果仍然滞后,则分别更改player1.hpplayer2.hp时,必须渲染一次文字表面.例如:


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

这篇关于pygame中渲染文本会导致延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆