0

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()
bad_coder
  • 11,289
  • 20
  • 44
  • 72
SShield
  • 37
  • 7
  • 1
    This is way off-topic for this site but you can profile your code and see what's taking up the most time and resources: https://stackoverflow.com/questions/582336/how-do-i-profile-a-python-script – Random Davis Oct 27 '22 at 21:35
  • Any energy transfer moves atoms, which generates heat, so yes – Tom McLean Oct 27 '22 at 21:38
  • 1
    You are running the CPU full bore if you have no wait statements. IIRC there is a `pygame.time.wait(1)` or some such call you can have in your loop. Watch CPU usage monitor with and without that statement. – RufusVS Oct 27 '22 at 21:41
  • `pygame.event.wait()` might be a good alternative – erik258 Oct 27 '22 at 22:37

1 Answers1

6

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)

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174