Show FPS in Pygame

Question:

I’m working on a project with my friend in python with pygame. We try to show FPS in our game but we just fail. The fps counter are always at zero. Here is the code:

#Create Text
def Render_Text(what, color, where):
    font = pygame.font.Font('assets/Roboto.ttf', 30)
    text = font.render(what, 1, pygame.Color(color))
    window.blit(text, where)
#Show FPS
    Render_Text(str(int(clock.get_fps())), (255,0,0), (0,0))
    print("FPS:", int(clock.get_fps()))
Asked By: Bla0

||

Answers:

get_fps() only gives a correct result, when you call tick() once per frame:

clock = pygame.time.Clock()
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          

    clock.tick()
    print(clock.get_fps())

    # [...]

See the documentation of get_fps()

get_fps() compute the clock framerate

get_fps() -> float

Compute your game’s framerate (in frames per second). It is computed by averaging the last ten calls to Clock.tick().

Answered By: Rabbid76

Initialize your clock

clock = pygame.time.Clock()

Add your font

font = pygame.font.SysFont("Arial" , 18 , bold = True)

And your fps function

def fps_counter():
    fps = str(int(clock.get_fps()))
    fps_t = font.render(fps , 1, pygame.Color("RED"))
    window.blit(fps_t,(0,0))

Call your function in loop

fps_counter()
#dont forget to add tick(60) to run 60 frame per sec
Answered By: R4GE J4X
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.