1

This problem has come up before and I didn't really do anything about it. So basically I have a simple program, but it lags A LOT. It's not my computer because my other pygame programs work fine. Anyway please tell me what I'm doing wrong again. Here's the code:

import pygame

pygame.init()

white = (255,255,255)
black = (0,0,0)

window_width = 800
window_height = 600

gameDisplay = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()


def gameLoop():

    characterx = 500
    characterx_change = 0

    charactery = 500
    charactery_change = 0

    while True:
        characterimg = pygame.image.load('Character.png')

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               False
            if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                characterx_change += -20
                charactery_change += 0
            if event.key == pygame.K_RIGHT:
                characterx_change += 20
                charactery_change += 0
            if event.key == pygame.K_UP:
                charactery_change += -20
                characterx_change += 0
            if event.key == pygame.K_DOWN:
                charactery_change += 20
                characterx_change += 0

        characterx += characterx_change
        charactery += charactery_change

        gameDisplay.fill(white)           
        gameDisplay.blit(characterimg, (characterx,charactery))
        pygame.display.update()
        clock.tick(15)

gameLoop()
pygame.quit()
quit()
skrx
  • 19,980
  • 5
  • 34
  • 48
  • 1
    don't load image in `while` loop - you can do it once before `while` – furas Nov 24 '17 at 06:51
  • BTW: always add tag `python`. More people will see questiona and code will be highlighted so it will be more readable. – furas Nov 24 '17 at 06:53
  • BTW: instead of `+= -20` you can use `-= 20` – furas Nov 24 '17 at 06:54
  • 1
    BTW: you could use `tick(25)` - human eye need about 25-30 FPS to see smooth animation. – furas Nov 24 '17 at 06:55
  • BTW: `event.type` can't be `QUIT` and `KEYDOWN at the same time so you can use `elif`. The same with `event.key` - it can't be `K_LEFT` `K_RIGHT`, `K_UP` and `K_DOWN` at the same time so you can use `elif`. – furas Nov 24 '17 at 07:46
  • 1
    In addition to not repeatedly loading the image from file, you probably should probably add a `.convert()` or a `.convert_alpha()` (the former is much faster than the latter, but the latter handles transparency) after loading the image. – CodeSurgeon Nov 24 '17 at 09:31
  • 1
    characterimg = pygame.image.load('Character.png') should be outside of the while loop (do it after pygame is initialised tho) and then also call "convert()" on it: characterimg = pygame.image.load('Character.png').convert_alpha() – Frogboxe Nov 24 '17 at 11:02
  • Thanks it worked! Also I made all the changes you guys suggested, works really well! Thanks! –  Nov 24 '17 at 14:57

0 Answers0