跳到主要内容

游戏开发入门

从零开始制作你的第一款游戏

游戏开发技术栈

游戏引擎
├── Unity (C#) - 最流行
├── Unreal Engine (C++) - 3A大作
├── Godot (GDScript) - 开源免费
└── Pygame (Python) - 学习入门

游戏类型
├── 2D游戏
├── 3D游戏
├── 手机游戏
└── Web游戏

Pygame入门

环境准备

pip install pygame

基础框架

import pygame
import sys

# 初始化
pygame.init()

# 设置窗口
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("我的第一个游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# 时钟控制帧率
clock = pygame.time.Clock()
FPS = 60

# 游戏主循环
running = True
while running:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# 游戏逻辑更新

# 绘制
screen.fill(WHITE)
pygame.draw.rect(screen, BLUE, (350, 250, 100, 100))

# 更新显示
pygame.display.flip()
clock.tick(FPS)

pygame.quit()
sys.exit()

玩家控制

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

# 玩家属性
player = {
'x': 400,
'y': 300,
'width': 50,
'height': 50,
'speed': 5,
'color': (0, 128, 255)
}

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# 键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
player['x'] -= player['speed']
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
player['x'] += player['speed']
if keys[pygame.K_UP] or keys[pygame.K_w]:
player['y'] -= player['speed']
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
player['y'] += player['speed']

# 边界检测
player['x'] = max(0, min(player['x'], 800 - player['width']))
player['y'] = max(0, min(player['y'], 600 - player['height']))

# 绘制
screen.fill((30, 30, 30))
pygame.draw.rect(screen, player['color'],
(player['x'], player['y'], player['width'], player['height']))

pygame.display.flip()
clock.tick(60)

pygame.quit()

完整小游戏:躲避方块

import pygame
import random

pygame.init()

# 设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("躲避方块")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)

# 玩家
class Player:
def __init__(self):
self.width = 40
self.height = 40
self.x = SCREEN_WIDTH // 2
self.y = SCREEN_HEIGHT - 60
self.speed = 6
self.color = (0, 200, 100)

def move(self, keys):
if keys[pygame.K_LEFT] and self.x > 0:
self.x -= self.speed
if keys[pygame.K_RIGHT] and self.x < SCREEN_WIDTH - self.width:
self.x += self.speed

def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height))

def get_rect(self):
return pygame.Rect(self.x, self.y, self.width, self.height)

# 敌人
class Enemy:
def __init__(self):
self.width = 30
self.height = 30
self.x = random.randint(0, SCREEN_WIDTH - self.width)
self.y = -self.height
self.speed = random.randint(3, 7)
self.color = (255, 50, 50)

def update(self):
self.y += self.speed

def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height))

def get_rect(self):
return pygame.Rect(self.x, self.y, self.width, self.height)

def is_off_screen(self):
return self.y > SCREEN_HEIGHT

# 游戏状态
def game():
player = Player()
enemies = []
score = 0
spawn_timer = 0

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False

keys = pygame.key.get_pressed()
player.move(keys)

# 生成敌人
spawn_timer += 1
if spawn_timer >= 30:
enemies.append(Enemy())
spawn_timer = 0

# 更新敌人
for enemy in enemies[:]:
enemy.update()
if enemy.is_off_screen():
enemies.remove(enemy)
score += 10
elif player.get_rect().colliderect(enemy.get_rect()):
return True # 游戏结束

# 绘制
screen.fill((20, 20, 40))
player.draw(screen)
for enemy in enemies:
enemy.draw(screen)

# 显示分数
score_text = font.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(score_text, (10, 10))

pygame.display.flip()
clock.tick(60)

return False

# 主程序
if game():
print("游戏结束!")
pygame.quit()

Unity入门 (C#)

using UnityEngine;

public class PlayerController : MonoBehaviour
{
public float speed = 5f;
public float jumpForce = 10f;
private Rigidbody2D rb;
private bool isGrounded;

void Start()
{
rb = GetComponent<Rigidbody2D>();
}

void Update()
{
// 水平移动
float moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * speed, rb.velocity.y);

// 跳跃
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}
}

void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}

学习路线图

第1阶段:基础 (1-2个月)
├── 选择引擎 (推荐Pygame或Unity)
├── 游戏循环理解
├── 输入处理
└── 基础物理

第2阶段:2D游戏 (2-3个月)
├── 精灵与动画
├── 碰撞检测
├── 音效与音乐
└── UI界面

第3阶段:完整游戏 (2-3个月)
├── 关卡设计
├── 存档系统
├── 游戏发布
└── 性能优化

第4阶段:进阶 (持续)
├── 3D游戏开发
├── 网络多人游戏
├── AI行为树
└── 着色器编程

本章小结

  • 引擎选择:Pygame学习、Unity商业
  • 游戏循环:输入→更新→渲染
  • 核心要素:玩家控制、碰撞检测、得分系统
  • 实践为主:多做小游戏积累经验

→ 继续阅读:41-运维与DevOps