-1

我刚刚开始学习 python,特别是 pygame,并且正在尝试制作一个简单的跳跃游戏。我做了一个基本的运动脚本作为测试,但动画真的很不稳定。每当方块移动时,都会出现残影,看起来就像它刚刚破裂一样。此外,如果您对清理脚本有任何建议,那就太好了。

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

1 回答 1

0

在 PyGame 中,您必须管理 FPS 以保持游戏不变。例如,如果您有一台非常快的计算机,您将拥有 200 或 300 FPS,并且在像您这样的小场景中,您的播放器每秒将以 200 倍的速度移动,所以这是相当快的,否则您的计算机就是真的很老,你会得到大约 30 FPS,而你的播放器每秒移动的速度只有你的 30 倍,这显然要慢得多。

我想向您解释的是,FPS 是必不可少的,因此您的游戏可以具有恒定的移动和速度。

所以我只添加了配置 FPS 的行,我设置了 60 并将速度更改为 10,但您可以轻松地为您的计算机调整这些值。

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()
于 2021-01-28T22:37:58.023 回答