When I run a simple pygame program using PyCharm on my M1 MacBook, I notice that my laptop gets kinda warm after running the program for 5-10 minutes. Is this normal, or does the while loop “tax” the computer. Thanks.
Code below:
import pygame # INITIALIZE pygame.init #CREATE THE SCREEN screen=pygame.display.set_mode((800,600)) #Title and Icon pygame.display.set_caption("First Pygame") #Player playerImg = pygame.image.load("racing-car.png") playerX= 400 playerY=300 playerX_Change=0 playerY_Change=0 def player(x,y): screen.blit(playerImg, (playerX,playerY)) # Game Loop running=True while running: screen.fill((128, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running=False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_Change = -5 if event.key == pygame.K_RIGHT: playerX_Change = 5 if event.key == pygame.K_DOWN: playerY_Change = 5 if event.key == pygame.K_UP: playerY_Change = -5 if event.type == pygame.KEYUP: playerX_Change=0 playerY_Change=0 playerY=playerY+playerY_Change playerX=playerX+playerX_Change player(playerX, playerY) pygame.display.update()
Advertisement
Answer
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
The method tick()
of a pygame.time.Clock
object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick()
:
This method should be called once per frame.
That means that the following loop only runs 60 times per second.
clock = pygame.time.Clock() run = True while run: clock.tick(60) # [...]