游戏客户端架构 / 系统课时

实现核心玩法

实现核心玩法

本课把角色行为组织成可运行的玩法闭环:收集目标会增加得分,全部目标完成时判定胜利,生命值归零时判定失败,并通过事件让各组件保持解耦。

学习目标

  • 使用事件传递收集、受伤、得分和结束状态
  • 将目标、计分与失败条件拆分为独立组件
  • 运行测试场景并验证胜利与失败分支

定义玩法闭环

最小玩法闭环需要回答三个问题:玩家要做什么、如何获得反馈、什么时候结束。本例把“收集三个能量核心”设为目标,每收集一个获得 100 分;玩家受到伤害后扣除生命,生命归零则失败。

核心玩法事件流图

事件机制的作用不是增加复杂度,而是避免组件彼此直接调用。例如,可收集物不需要知道计分组件的位置;它只发布 CollectibleCollected,由计分和目标组件分别响应。

设计事件与组件边界

本例使用四类事件:

  • CollectibleCollected:携带目标 ID 与分值。
  • DamageTaken:携带伤害值。
  • ObjectiveCompleted:表示目标已全部完成。
  • HealthDepleted:表示生命值已经归零。

计分组件只处理分值,目标组件只统计已收集数量,生命组件只处理生命值,游戏状态组件只接收结束事件并锁定最终结果。这样增加 UI、音效或存档时,只需新增监听者,不必改动原组件。

完成事件驱动实现

下面的 C++17 示例实现一个同步事件总线,并分别运行胜利和失败场景。示例中的事件在当前帧立即分发,适合演示单线程玩法逻辑。

cpp
#include <functional>
#include <iostream>
#include <string>
#include <typeindex>
#include <unordered_map>
#include <utility>
#include <vector>

class EventBus {
public:
    template <typename Event>
    void subscribe(std::function<void(const Event&)> handler) {
        auto wrapper = [handler = std::move(handler)](const void* event) {
            handler(*static_cast<const Event*>(event));
        };
        handlers_[std::type_index(typeid(Event))].push_back(std::move(wrapper));
    }

    template <typename Event>
    void publish(const Event& event) const {
        const auto it = handlers_.find(std::type_index(typeid(Event)));
        if (it == handlers_.end()) {
            return;
        }
        for (const auto& handler : it->second) {
            handler(&event);
        }
    }

private:
    using Handler = std::function<void(const void*)>;
    std::unordered_map<std::type_index, std::vector<Handler>> handlers_;
};

struct CollectibleCollected {
    int collectibleId;
    int points;
};

struct DamageTaken {
    int amount;
};

struct ObjectiveCompleted {};
struct HealthDepleted {};

class ScoreComponent {
public:
    explicit ScoreComponent(EventBus& bus) {
        bus.subscribe<CollectibleCollected>(
            [this](const CollectibleCollected& event) {
                score_ += event.points;
            }
        );
    }

    int score() const {
        return score_;
    }

private:
    int score_ = 0;
};

class ObjectiveComponent {
public:
    ObjectiveComponent(EventBus& bus, int targetCount)
        : bus_(bus), targetCount_(targetCount) {
        bus_.subscribe<CollectibleCollected>(
            [this](const CollectibleCollected&) {
                if (completed_) {
                    return;
                }
                ++collectedCount_;
                if (collectedCount_ >= targetCount_) {
                    completed_ = true;
                    bus_.publish(ObjectiveCompleted{});
                }
            }
        );
    }

    int collectedCount() const {
        return collectedCount_;
    }

private:
    EventBus& bus_;
    int targetCount_;
    int collectedCount_ = 0;
    bool completed_ = false;
};

class HealthComponent {
public:
    HealthComponent(EventBus& bus, int maxHealth)
        : bus_(bus), health_(maxHealth) {
        bus_.subscribe<DamageTaken>(
            [this](const DamageTaken& event) {
                if (health_ == 0) {
                    return;
                }
                health_ = event.amount >= health_ ? 0 : health_ - event.amount;
                if (health_ == 0) {
                    bus_.publish(HealthDepleted{});
                }
            }
        );
    }

    int health() const {
        return health_;
    }

private:
    EventBus& bus_;
    int health_;
};

class GameStateComponent {
public:
    explicit GameStateComponent(EventBus& bus) {
        bus.subscribe<ObjectiveCompleted>(
            [this](const ObjectiveCompleted&) {
                finish("Victory");
            }
        );
        bus.subscribe<HealthDepleted>(
            [this](const HealthDepleted&) {
                finish("GameOver");
            }
        );
    }

    const std::string& state() const {
        return state_;
    }

private:
    void finish(const std::string& result) {
        // 首个结束条件生效后锁定状态,避免同一帧被另一个事件覆盖。
        if (state_ == "Playing") {
            state_ = result;
        }
    }

    std::string state_ = "Playing";
};

void runVictoryScenario() {
    EventBus bus;
    ScoreComponent score(bus);
    ObjectiveComponent objective(bus, 3);
    HealthComponent health(bus, 100);
    GameStateComponent gameState(bus);

    bus.publish(CollectibleCollected{1, 100});
    bus.publish(CollectibleCollected{2, 100});
    bus.publish(CollectibleCollected{3, 100});

    std::cout << "victory score=" << score.score()
              << " collected=" << objective.collectedCount()
              << " health=" << health.health()
              << " state=" << gameState.state() << '\n';
}

void runFailureScenario() {
    EventBus bus;
    ScoreComponent score(bus);
    ObjectiveComponent objective(bus, 3);
    HealthComponent health(bus, 100);
    GameStateComponent gameState(bus);

    bus.publish(CollectibleCollected{1, 100});
    bus.publish(DamageTaken{40});
    bus.publish(DamageTaken{60});

    std::cout << "failure score=" << score.score()
              << " collected=" << objective.collectedCount()
              << " health=" << health.health()
              << " state=" << gameState.state() << '\n';
}

int main() {
    runVictoryScenario();
    runFailureScenario();
}

预期输出:

text
victory score=300 collected=3 health=100 state=Victory
failure score=100 collected=1 health=0 state=GameOver

胜利场景收集三个目标后发布 ObjectiveCompleted;失败场景累计受到 100 点伤害后发布 HealthDepleted。游戏状态组件只接受第一个结束结果,避免同一帧同时满足条件时状态来回覆盖。

接入场景并处理边界

在真实项目中,可收集物应在确认碰撞后只发布一次事件,并立即标记为失效或进入待销毁队列。否则连续多帧重叠会重复加分。场景切换、UI 和音效可以订阅胜利或失败事件,但不应反向修改计分与目标组件。

还要明确结束优先级。本例采用“先到先得”,即先收到的结束事件锁定结果。若设计要求“死亡优先”或“完成目标优先”,应在帧末统一汇总条件,而不是依赖事件发送顺序。

运行与验收

编译时使用支持 C++17 的编译器。运行后确认胜利场景输出 300 分和 Victory,失败场景保留 100 分并输出 GameOver。再把同一个收集事件重复发送两次,观察分数会重复增加,这能帮助你定位真实项目中必须由可收集物保证幂等的位置。

本课总结

  • 事件总线让收集物、计分、目标、生命和游戏状态彼此解耦
  • 胜利与失败条件应由独立组件判断,并由统一状态组件锁定结果
  • 可收集物必须防止重复触发,结束条件也要有明确优先级

下一课预告

下一课将整理资源、配置与构建产物,完成项目打包、运行验证和发布前检查。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

实现核心玩法

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通