1. 贪吃蛇

目标:Pygame 经典游戏,掌握游戏循环和事件处理

import pygame
import random

pygame.init()

# 游戏设置
WIDTH, HEIGHT = 600, 400
GRID = 20
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()

# 蛇的初始位置
snake = [(100, 100), (80, 100), (60, 100)]
direction = (20, 0)

# 随机生成食物
food = (random.randrange(0, WIDTH, GRID),
        random.randrange(0, HEIGHT, GRID))

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and direction != (0, 20):
                direction = (0, -20)
            elif event.key == pygame.K_DOWN and direction != (0, -20):
                direction = (0, 20)
            elif event.key == pygame.K_LEFT and direction != (20, 0):
                direction = (-20, 0)
            elif event.key == pygame.K_RIGHT and direction != (-20, 0):
                direction = (20, 0)

    # 移动蛇
    head = (snake[0][0] + direction[0],
            snake[0][1] + direction[1])
    snake.insert(0, head)

    # 检测吃到食物
    if head == food:
        food = (random.randrange(0, WIDTH, GRID),
                random.randrange(0, HEIGHT, GRID))
    else:
        snake.pop()

    # 检测撞墙
    if (head[0] < 0 or head[0] >= WIDTH or
        head[1] < 0 or head[1] >= HEIGHT or
        head in snake[1:]):
        running = False

    # 绘制
    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (29, 209, 161), (*food, GRID, GRID))
    for segment in snake:
        pygame.draw.rect(screen, (255, 107, 107),
                        (*segment, GRID, GRID))
    pygame.display.flip()
    clock.tick(10)

pygame.quit()

知识点:游戏循环、键盘事件处理、列表操作、碰撞检测


2. 打砖块

目标:碰撞检测与反弹物理的实战应用

import pygame
import sys

pygame.init()

WIDTH, HEIGHT = 600, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("打砖块")
clock = pygame.time.Clock()

# 挡板
paddle = pygame.Rect(250, 460, 100, 15)

# 球
ball = pygame.Rect(295, 440, 10, 10)
ball_speed = [4, -4]

# 砖块
colors = [(255, 107, 107), (254, 202, 87), (72, 219, 251),
          (29, 209, 161), (255, 159, 243)]
bricks = []
for row in range(5):
    for col in range(10):
        brick = pygame.Rect(col * 60, row * 30 + 40, 55, 25)
        bricks.append((brick, colors[row]))

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

    # 挡板跟随鼠标
    paddle.x = pygame.mouse.get_pos()[0] - 50

    # 移动球
    ball.x += ball_speed[0]
    ball.y += ball_speed[1]

    # 墙壁反弹
    if ball.left <= 0 or ball.right >= WIDTH:
        ball_speed[0] *= -1
    if ball.top <= 0:
        ball_speed[1] *= -1

    # 挡板反弹
    if ball.colliderect(paddle):
        ball_speed[1] *= -1

    # 砖块碰撞
    for brick, color in bricks[:]:
        if ball.colliderect(brick):
            bricks.remove((brick, color))
            ball_speed[1] *= -1
            break

    # 绘制
    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (84, 160, 255), paddle)
    pygame.draw.ellipse(screen, (255, 255, 255), ball)
    for brick, color in bricks:
        pygame.draw.rect(screen, color, brick, border_radius=4)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

知识点:矩形碰撞检测、物理反弹、鼠标控制、关卡设计


3. 飞机大战

目标:射击游戏基础,掌握精灵管理和射击机制

import pygame
import random

pygame.init()

WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("飞机大战")
clock = pygame.time.Clock()

# 玩家飞机
player = pygame.Rect(175, 520, 50, 40)
player_speed = 5

# 子弹列表
bullets = []

# 敌机列表
enemies = []
enemy_timer = 0

# 分数
score = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bullets.append(
                    pygame.Rect(player.centerx - 2,
                               player.top - 10, 4, 10))

    # 移动玩家
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player.left > 0:
        player.x -= player_speed
    if keys[pygame.K_RIGHT] and player.right < WIDTH:
        player.x += player_speed

    # 移动子弹
    for bullet in bullets[:]:
        bullet.y -= 8
        if bullet.bottom < 0:
            bullets.remove(bullet)

    # 生成敌机
    enemy_timer += 1
    if enemy_timer > 30:
        enemies.append(pygame.Rect(
            random.randint(0, WIDTH - 40),
            -40, 40, 30))
        enemy_timer = 0

    # 移动敌机 & 碰撞检测
    for enemy in enemies[:]:
        enemy.y += 3
        if enemy.top > HEIGHT:
            enemies.remove(enemy)
        for bullet in bullets[:]:
            if bullet.colliderect(enemy):
                if bullet in bullets:
                    bullets.remove(bullet)
                if enemy in enemies:
                    enemies.remove(enemy)
                score += 10
                break

    # 绘制
    screen.fill((30, 30, 46))
    # 玩家
    pygame.draw.polygon(screen, (84, 160, 255),
        [(player.centerx, player.top),
         (player.left, player.bottom),
         (player.right, player.bottom)])
    # 子弹
    for bullet in bullets:
        pygame.draw.rect(screen, (254, 202, 87), bullet)
    # 敌机
    for enemy in enemies:
        pygame.draw.polygon(screen, (255, 107, 107),
            [(enemy.centerx, enemy.bottom),
             (enemy.left, enemy.top),
             (enemy.right, enemy.top)])
    # 分数
    font = pygame.font.SysFont(None, 36)
    text = font.render(f"Score: {score}", True, (255, 255, 255))
    screen.blit(text, (10, 10))

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

pygame.quit()

知识点:精灵管理、键盘连续按键、射击系统、碰撞销毁、计分系统


4. 井字棋对战

目标:实现双人对战的井字棋游戏

def print_board(board):
    for row in board:
        print(' | '.join(row))
        print('-' * 9)

def check_winner(board):
    # 检查行、列、对角线
    for i in range(3):
        if board[i][0] == board[i][1] == board[i][2] != ' ':
            return board[i][0]
        if board[0][i] == board[1][i] == board[2][i] != ' ':
            return board[0][i]
    if board[0][0] == board[1][1] == board[2][2] != ' ':
        return board[0][0]
    if board[0][2] == board[1][1] == board[2][0] != ' ':
        return board[0][2]
    return None

def tic_tac_toe():
    board = [[' ']*3 for _ in range(3)]
    player = 'X'

    for turn in range(9):
        print_board(board)
        row, col = map(int, input(f"玩家 {player},输入行和列(0-2): ").split())

        if board[row][col] == ' ':
            board[row][col] = player
        else:
            print("该位置已占用!")
            continue

        winner = check_winner(board)
        if winner:
            print_board(board)
            print(f"玩家 {winner} 获胜!")
            return

        player = 'O' if player == 'X' else 'X'

    print_board(board)
    print("平局!")

tic_tac_toe()

知识点:二维列表、循环控制、胜负判断逻辑


5. 2048 游戏(文字版)

目标:实现 2048 核心逻辑

import random

def new_board():
    board = [[0]*4 for _ in range(4)]
    add_random(board)
    add_random(board)
    return board

def add_random(board):
    empty = [(r, c) for r in range(4) for c in range(4) if board[r][c] == 0]
    if empty:
        r, c = random.choice(empty)
        board[r][c] = 4 if random.random() < 0.1 else 2

def slide_left(board):
    new_board = []
    for row in board:
        nums = [n for n in row if n != 0]
        merged = []
        i = 0
        while i < len(nums):
            if i + 1 < len(nums) and nums[i] == nums[i+1]:
                merged.append(nums[i] * 2)
                i += 2
            else:
                merged.append(nums[i])
                i += 1
        merged += [0] * (4 - len(merged))
        new_board.append(merged)
    return new_board

def print_board(board):
    for row in board:
        print(f"|{row[0]:>5}|{row[1]:>5}|{row[2]:>5}|{row[3]:>5}|")
    print('-' * 22)

# 简化版:只实现左移
board = new_board()
print_board(board)
board = slide_left(board)
print("左移后:")
print_board(board)

知识点:二维数组操作、滑动合并逻辑、随机生成


6. 猜单词游戏

目标:实现类似 Hangman 的猜单词游戏

import random

WORD_LIST = ['python', 'programming', 'algorithm', 'function', 'variable',
             'database', 'network', 'security', 'interface', 'framework']

def hangman():
    word = random.choice(WORD_LIST)
    guessed = set()
    attempts = 6

    while attempts > 0:
        display = ''.join(c if c in guessed else '_' for c in word)
        print(f"\n单词: {display}")
        print(f"剩余次数: {'❤' * attempts}{'♡' * (6 - attempts)}")
        print(f"已猜字母: {', '.join(sorted(guessed)) if guessed else '无'}")

        if all(c in guessed for c in word):
            print(f"\n恭喜!你猜对了: {word}")
            return

        guess = input("猜一个字母: ").lower()
        if guess in guessed:
            print("已经猜过这个字母了!")
            continue

        guessed.add(guess)
        if guess not in word:
            attempts -= 1
            print(f"'{guess}' 不在单词中!")
        else:
            print(f"'{guess}' 猜对了!")

    print(f"\n游戏结束!正确答案: {word}")

hangman()

知识点:集合操作、字符串处理、游戏状态管理