首页 > 解决方案 > 我的简单 pygame pong 游戏滞后(python)

问题描述

嗨,我是 Python 初学者,最近开始学习 Pygame。但是我理解代码的逻辑,但它开始滞后于简单的调整。我已经更改了分辨率并设置了 FPS,但它在每种情况下都滞后。

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()

标签: pythonpygamelagpong

解决方案


这是一个缩进的问题 。您必须在应用程序循环而不是事件循环中更新球的位置并绘制场景:

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()

推荐阅读