Hi I am a beginner programmer in Python, and I started learning Pygame recently. However I understand the logics of the code, but it starts lagging with simple adjustments. I already changed the resolution and I set the FPS but it's lagging in every occasion.
import pygame, os, sys
#init
pygame.init()
clock = pygame.time.Clock()
#screen
WIDTH, HEIGHT = 1280, 720
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
#vars
LIGHT_GREY = (200, 200, 200)
bg = pygame.Color("grey12")
#images
ball = pygame.Rect(WIDTH / 2 - 15, HEIGHT / 2 - 15, 30,30)
player = pygame.Rect(WIDTH - 20, HEIGHT/2 - 70, 10, 140)
opponent = pygame.Rect(10, HEIGHT/2 - 70, 10, 140)
#vars
ball_speedx = 7
ball_speedy = 7
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
ball.x += ball_speedx
ball.y += ball_speedy
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_speedy *= -1
if ball.left <= 0 or ball.right >= WIDTH:
ball_speedx *= -1
#VISUALS
SCREEN.fill(bg)
pygame.draw.rect(SCREEN, LIGHT_GREY, player)
pygame.draw.rect(SCREEN, LIGHT_GREY, opponent)
pygame.draw.ellipse(SCREEN, LIGHT_GREY, ball)
pygame.draw.aaline(SCREEN, LIGHT_GREY, (WIDTH/2, 0), (WIDTH/2, HEIGHT))
pygame.display.flip()
It is a matter of Indentation . You must update the ball position and draw the scene in the application loop instead of the event loop:
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# INDENTATION
#<--|
ball.x += ball_speedx
ball.y += ball_speedy
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_speedy *= -1
if ball.left <= 0 or ball.right >= WIDTH:
ball_speedx *= -1
#VISUALS
SCREEN.fill(bg)
pygame.draw.rect(SCREEN, LIGHT_GREY, player)
pygame.draw.rect(SCREEN, LIGHT_GREY, opponent)
pygame.draw.ellipse(SCREEN, LIGHT_GREY, ball)
pygame.draw.aaline(SCREEN, LIGHT_GREY, (WIDTH/2, 0), (WIDTH/2, HEIGHT))
pygame.display.flip()