python - 我的简单 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()
解决方案
这是一个缩进的问题 。您必须在应用程序循环而不是事件循环中更新球的位置并绘制场景:
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()
推荐阅读
- python - 将大小不等的 2D 列表的行与 try catch 进行比较会导致程序不规则地跳转
- c# - 保存字节数组列表(List
我想使用 Entity Framework 保存位图图像列表。我读到我会将它们转换为字节数组,所以我做了相应的操作。
该类如下所示:
public class ShootingLocation : LocationBase { #region attributes public Park
- python - 为什么“while True:”之外的“sock.recv(1024)”会返回端口上运行的服务,就像 nmap 一样?
- c++ - C++ 程序在 VS 上运行顺畅,但在 Linux Mint 上运行不畅
- c++ - c++ netplan ubuntu yaml 读取和创建
- ruby - 如何从logstash中的netdata聚合指标?
- c# - 如何获得一组数字的所有组合,这些组合将加起来或仅略超过一组数字?
- jquery - 如何在 jQuery 函数中调用数据样式
- python - 如何使用 pdfrw 库编辑可编辑的 pdf?
- bash - 无法通过 Jenkinsfile 在 Bash 脚本中执行 AWS CLI