简单精灵逻辑

52.7 简单精灵逻辑

用变量存 x,y,speed;每帧更新坐标;边界检测反弹或限制在屏幕内。

边界反弹球

# ========================================
# 示例:移动与边界
# ========================================
import pygame

pygame.init()
W, H = 400, 300
screen = pygame.display.set_mode((W, H))
x, y = 200, 150
vx, vy = 3, 2
clock = pygame.time.Clock()
running = True
while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT: running = False
    x += vx; y += vy
    if x < 20 or x > W-20: vx = -vx
    if y < 20 or y > H-20: vy = -vy
    screen.fill((0, 0, 0))
    pygame.draw.circle(screen, (255, 100, 100), (int(x), int(y)), 20)
    pygame.display.flip()
    clock.tick(60)
pygame.quit()