Hot to show the frame rate fps or any text with pygame in Python

Python can use pygame to make games. Frame rate is the number of update of the screen (let’s say how many frames) for every second. So, if you do not want to update the screen to many times (it would stress the pc), you can put the max frame rate to 60. When there are too many things happening on the screen the frame rate can slow down. To be aware of the amount of frames that the computer is able to show, you can show the fps (frames per seconds) on the screen. How? Watch the video and the code below.

Frame rate per seconds on the screen
import pygame


def show_fps():
	fps_text = str(int(clock.get_fps()))
	fps_surface = fps_font.render(fps_text, 1, pygame.Color("black"))
	# show the bg
	screen.blit(fps_bg, (0, 0))
	screen.blit(fps_surface, (0, 0))


def mainloop():
	''' happens every frame '''
	while True:
		show_fps()
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
		clock.tick(60)
		pygame.display.update()


pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
fps_bg = pygame.Surface((25, 25))
fps_bg.fill((255,255,255))
fps_font = pygame.font.SysFont("Arial", 20)
mainloop()

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.