Debian 上用 Python 做游戏的高效入门路线
一 环境准备与工具
sudo apt update && sudo apt install -y python3 python3-pip build-essentialpython3 -m venv game_env && source game_env/bin/activate二 快速上手示例
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My First Game")
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
python main.pyimport pygame, sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
paddle = pygame.Rect(350, 550, 100, 20)
ball = pygame.Rect(400, 300, 20, 20)
ball.velocity = [4, -4]
bricks = pygame.sprite.Group()
for row in range(5):
for col in range(10):
bricks.add(pygame.Rect(col*80+5, row*30+5, 70, 20))
all_sprites = pygame.sprite.Group([paddle, ball] + list(bricks))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and paddle.left > 0:
paddle.x -= 6
if keys[pygame.K_RIGHT] and paddle.right < 800:
paddle.x += 6
ball.x += ball.velocity[0]
ball.y += ball.velocity[1]
if ball.left <= 0 or ball.right >= 800:
ball.velocity[0] = -ball.velocity[0]
if ball.top <= 0:
ball.velocity[1] = -ball.velocity[1]
if ball.colliderect(paddle):
ball.velocity[1] = -ball.velocity[1]
hit_bricks = pygame.sprite.spritecollide(ball, bricks, True)
if hit_bricks:
ball.velocity[1] = -ball.velocity[1]
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)
三 项目结构与常用功能
mygame/
├── main.py
├── assets/
│ ├── images/
│ └── sounds/
├── sprites/
│ ├── __init__.py
│ └── player.py
└── utils/
└── helpers.py
pygame.image.load() 加载图片,blit() 绘制,pygame.Surface 作为画布;精灵与精灵组管理对象、批量绘制与碰撞。pygame.mixer.Sound 加载与播放短音效,pygame.mixer.music 播放背景音乐。pygame.key.get_pressed() 连续按键。pygame.time.Clock().tick(60) 稳定刷新率。四 调试优化与发布
pip install pyinstaller,然后 pyinstaller --onefile main.py(可进一步用 spec 配置资源与图标)。pip install stdeb,然后 python setup.py --command-packages=stdeb.command bdist_deb 生成 .deb(需有合规的 setup.py)。五 进阶方向与常见问题
p4a apk 构建 APK,在 spec 中声明依赖与权限,例如:
p4a apk --private ./mygame --package=com.mycompany.mygame --name "MyGame" --version 1.0 --bootstrap=sdl2 --requirements=python3,kivy,pillow,numpy --icon=./mygame/icon.png --orientation=landscapepip install。