我的简单 pygame 乒乓球游戏滞后(python)

时间:2021-02-23 09:18:39

标签: python pygame lag pong

您好,我是 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()

1 个答案:

答案 0 :(得分:1)

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

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