Python 清洁和视觉改善

Python cleaning and visual improvement

我刚开始学习 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()

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