Search code examples
pythonvisual-studio-codepygamepylance

Python cleaning and visual improvement


I'm just starting to learn python, specifically pygame, and am trying to make a simple jumping game. I made a basic movement script as a test, but the animations are really choppy. Whenever the block moves, there's an afterimage, and it looks like its just breaking down. Also, if you have any suggestions for cleaning up the script, that'd be great.

import pygame
from pygame.locals import *

SIZE = 800, 600
RED = (255, 0, 0)
GRAY = (150, 150, 150)
x = 50
y = 50

pygame.init()
screen = pygame.display.set_mode(SIZE)

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    pressed = pygame.key.get_pressed()

    if pressed[pygame.K_RIGHT]:
        x += 3
    if pressed[pygame.K_LEFT]:
        x -= 3
    if pressed[pygame.K_UP]:
        y -= 3
    if pressed[pygame.K_DOWN]:
        y += 3

    rect = Rect(x, y, 50, 50)

    screen.fill(GRAY)
    pygame.draw.rect(screen, RED, rect)
    pygame.display.flip()

pygame.quit()

Solution

  • In PyGame, you have to manage FPS in order to keep your game constant. For example, if you have a really fast computer you will have like 200 or 300 FPS and on a little scene like you did, every second your player will move by 200 times the speed, so this is quite fast, otherwise your computer is a really old one, you'll get like 30 FPS, and your player will move by only 30 times your speed every second, and that's obviously way slower.

    What I want to explain to you is that FPS are essential so your game can have constant moves and velocity.

    So I added just to lines to configure FPS, I set 60 and changed the speed to 10 but you can easily adapt these values for your computer.

    import pygame
    from pygame.locals import *
    
    SIZE = 800, 600
    RED = (255, 0, 0)
    GRAY = (150, 150, 150)
    x = 50
    y = 50
    
    pygame.init()
    screen = pygame.display.set_mode(SIZE)
    
    # creating a clock
    clock = pygame.time.Clock()
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
    
        pressed = pygame.key.get_pressed()
    
        if pressed[pygame.K_RIGHT]:
            x += 10
        if pressed[pygame.K_LEFT]:
            x -= 10
        if pressed[pygame.K_UP]:
            y -= 10
        if pressed[pygame.K_DOWN]:
            y += 10
    
        rect = Rect(x, y, 50, 50)
    
        screen.fill(GRAY)
        pygame.draw.rect(screen, RED, rect)
    
        # setting the fps to 60, depending on your machine, 60 fps is great in my opinion
        clock.tick(60)
        pygame.display.flip()
    
    pygame.quit()