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:
JavaScript
x
46
46
1
import pygame
2
# INITIALIZE
3
pygame.init
4
#CREATE THE SCREEN
5
screen=pygame.display.set_mode((800,600))
6
7
#Title and Icon
8
9
pygame.display.set_caption("First Pygame")
10
11
#Player
12
13
playerImg = pygame.image.load("racing-car.png")
14
playerX= 400
15
playerY=300
16
playerX_Change=0
17
playerY_Change=0
18
19
def player(x,y):
20
screen.blit(playerImg, (playerX,playerY))
21
22
# Game Loop
23
running=True
24
while running:
25
screen.fill((128, 0, 0))
26
for event in pygame.event.get():
27
if event.type == pygame.QUIT:
28
running=False
29
if event.type == pygame.KEYDOWN:
30
if event.key == pygame.K_LEFT:
31
playerX_Change = -5
32
if event.key == pygame.K_RIGHT:
33
playerX_Change = 5
34
if event.key == pygame.K_DOWN:
35
playerY_Change = 5
36
if event.key == pygame.K_UP:
37
playerY_Change = -5
38
39
if event.type == pygame.KEYUP:
40
playerX_Change=0
41
playerY_Change=0
42
playerY=playerY+playerY_Change
43
playerX=playerX+playerX_Change
44
player(playerX, playerY)
45
pygame.display.update()
46
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.
JavaScript
1
7
1
clock = pygame.time.Clock()
2
run = True
3
while run:
4
clock.tick(60)
5
6
# [...]
7