载入中...
搜索中...
未找到
BattleControl.cpp
浏览该文件的文档.
1#include "rpg/BattleControl.h"
2#include <algorithm>
3#include <cctype>
4#include <cmath>
5#include <cstdlib>
6#include <optional>
7#include <random>
8#include <unordered_map>
9#include <unordered_set>
10#include <utility>
11#include "common/Capability.h"
12#include "common/Json.h"
13#include "rpg/AttributeSystem.h"
14#include "rpg/Battle.h"
15#include "rpg/BattleSystem.h"
16#include "rpg/BattleTactics.h"
17#include "rpg/BattleVictory.h"
18#include "rpg/ClassSystem.h"
19#include "rpg/GameState.h"
20#include "rpg/LevelSystem.h"
21#include "rpg/RPGActor.h"
22#include "rpg/Skill.h"
23#include "rpg/Tracker.h"
24#include "rpg/TraitSystem.h"
25#include "rpg/WorldState.h"
26
27// BattleControl.cpp
28namespace eve::rpg {
29namespace {
30
31LogicalId gameplayId(std::string_view value) { return LogicalId::parse(value).value(); }
32
33Result<std::string> stringParameter(const Value &parameters, std::string_view name, bool optional = false) {
34 const auto *object = parameters.getIf<Value::Object>();
35 if (!object)
37 DiagnosticCode::InvalidArgument, "RPG gameplay parameters must be an object", "parameters"));
38 const auto found = object->find(std::string(name));
39 if (found == object->end() && optional) return Result<std::string>::success({});
40 if (found == object->end() || !found->second.isString())
42 "RPG gameplay parameter must be a string",
43 "parameters." + std::string(name)));
44 return Result<std::string>::success(found->second.asString());
45}
46
47} // namespace
48
49BattleControl::BattleControl(Battle &battle, SubjectRef instance) : battle_(battle), instance_(instance) {
50 cap::addListener<IGameplayControlProvider>(this);
51 cap::addListener<IGameplayInstanceCatalog>(this);
52}
53
55 cap::removeListener<IGameplayInstanceCatalog>(this);
56 cap::removeListener<IGameplayControlProvider>(this);
57}
58
60 if (!instance_.isValid() || !subject.isValid() || !actor)
62 DiagnosticCode::InvalidArgument, "battle, subject, and actor identities must be valid", "participant"));
63 bool participant = false;
64 for (int index = 0; index < battle_.getActorCount(); ++index)
65 if (battle_.getActor(index) == actor) participant = true;
66 if (!participant)
68 Diagnostic::error(DiagnosticCode::NotFound, "actor is not a participant in the adapted battle", "actor"));
69 const auto existing = actors_.find(subject);
70 if (existing != actors_.end() && existing->second != actor)
72 Diagnostic::error(DiagnosticCode::Conflict, "subject is already bound to another participant", "subject"));
73 if (const auto reverse = subjectOf(actor); reverse.isValid() && reverse != subject)
75 Diagnostic::error(DiagnosticCode::Conflict, "actor is already bound to another subject", "actor"));
76 actors_[subject] = actor;
77 ++revision_;
79}
80
81std::string_view BattleControl::gameplayDomain() const noexcept { return "rpg.battle"; }
82
83std::vector<SubjectRef> BattleControl::gameplayInstances() const {
84 // This adapter serves exactly one instance: the identity it was constructed
85 // with is the only one it can answer for.
86 if (!instance_.isValid()) return {};
87 return {instance_};
88}
89
90bool BattleControl::controls(const GameplaySession &session, SubjectRef subject) const {
92 std::find(session.controlledSubjects.begin(), session.controlledSubjects.end(), subject) !=
93 session.controlledSubjects.end();
94}
95
96RPGActor *BattleControl::resolve(SubjectRef subject) const {
97 const auto found = actors_.find(subject);
98 return found == actors_.end() ? nullptr : found->second;
99}
100
101SubjectRef BattleControl::subjectOf(RPGActor *actor) const {
102 for (const auto &[subject, candidate] : actors_)
103 if (candidate == actor) return subject;
104 return SubjectRef::nil();
105}
106
108 if (instance != instance_ || !instance_.isValid())
110 Diagnostic::error(DiagnosticCode::NotFound, "RPG battle gameplay instance was not found", "instance"));
111 bool ownsParticipant = false;
112 Value::Array participants;
113 for (int index = 0; index < battle_.getActorCount(); ++index) {
114 RPGActor *actor = battle_.getActor(index);
115 const auto subject = subjectOf(actor);
116 if (!subject.isValid()) continue;
117 const bool controlled = controls(session, subject);
118 ownsParticipant = ownsParticipant || controlled;
119 participants.emplace_back(Value::Object{
120 {"alive", Value(battle_.isActorAlive(actor))},
121 {"controlled", Value(controlled)},
122 {"hp", Value(actor->getCurrent("hp"))},
123 {"maxHp", Value(actor->getMax("hp"))},
124 {"side", Value(battle_.getSide(index))},
125 {"subject", Value(subject.format())},
126 });
127 }
128 if (session.access == GameplayAccess::PlayerEquivalent && !ownsParticipant)
131 "session controls no participant in this RPG battle", "session.controlledSubjects"));
132 GameplayObservation observation;
133 observation.domain = gameplayId("gameplay:rpg-battle");
134 observation.instance = instance_;
135 observation.tick = tick_;
136 observation.revision = revision_;
137 observation.state = Value(Value::Object{
138 {"defeat", Value(battle_.isDefeat())},
139 {"finished", Value(battle_.isFinished())},
140 {"participants", Value(std::move(participants))},
141 {"turn", Value(battle_.getTurn())},
142 {"victory", Value(battle_.isVictory())},
143 });
144 return Result<GameplayObservation>::success(std::move(observation));
145}
146
148 SubjectRef instance,
149 SubjectRef subject) const {
150 if (instance != instance_)
152 Diagnostic::error(DiagnosticCode::NotFound, "RPG battle gameplay instance was not found", "instance"));
153 RPGActor *actor = resolve(subject);
154 if (!actor)
156 Diagnostic::error(DiagnosticCode::NotFound, "RPG battle participant was not found", "subject"));
157 if (!controls(session, subject))
159 DiagnosticCode::PreconditionViolation, "session does not control this RPG participant", "subject"));
160 if (!battle_.isActorAlive(actor) || battle_.isFinished())
162 const Value targetSchema(Value::Object{{"type", Value("subject")}});
163 const Value skillSchema(
164 Value::Object{{"skillId", Value(Value::Object{{"type", Value("string")}})}, {"target", targetSchema}});
166 {gameplayId("rpg:attack"), Value(Value::Object{{"target", targetSchema}})},
167 {gameplayId("rpg:skill"), skillSchema},
168 });
169}
170
172 const GameplayCommand &command) {
173 if (instance != instance_)
175 Diagnostic::error(DiagnosticCode::NotFound, "RPG battle gameplay instance was not found", "instance"));
176 RPGActor *actor = resolve(command.subject);
177 if (!actor)
179 Diagnostic::error(DiagnosticCode::NotFound, "RPG battle participant was not found", "command.subject"));
180 if (!controls(session, command.subject))
182 DiagnosticCode::PreconditionViolation, "session does not control this RPG participant", "command.subject"));
183 if (command.id.empty())
185 Diagnostic::error(DiagnosticCode::InvalidArgument, "command id must not be empty", "command.id"));
186 if (command.observedTick != tick_ || command.expectedRevision != revision_)
188 DiagnosticCode::Conflict, "RPG command was based on a stale observation", "command.expectedRevision"));
189 auto targetText = stringParameter(command.parameters, "target");
190 if (!targetText) return Result<GameplayCommandReceipt>::failure(targetText.status());
191 const auto targetId = PersistentId::parse(targetText.value());
193 if (!target)
195 Diagnostic::error(DiagnosticCode::NotFound, "RPG command target was not found", "parameters.target"));
196 std::string skillId;
197 if (command.action == gameplayId("rpg:skill")) {
198 auto skill = stringParameter(command.parameters, "skillId");
199 if (!skill) return Result<GameplayCommandReceipt>::failure(skill.status());
200 skillId = std::move(skill).takeValue();
201 } else if (command.action != gameplayId("rpg:attack")) {
203 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported RPG gameplay action", "command.action"));
204 }
205 auto queued = battle_.setActionChecked(actor, skillId, target);
207 ++revision_;
208 lastCommandByActor_[actor] = command.id;
209 GameplayEvent accepted;
210 accepted.sequence = nextEventSequence_++;
211 accepted.tick = tick_;
212 accepted.type = "rpg.command.accepted";
213 accepted.subject = command.subject;
214 accepted.causationCommandId = command.id;
215 accepted.correlationId = command.id;
216 accepted.payload = Value(Value::Object{{"action", Value(command.action.format())}});
217 events_.push_back(std::move(accepted));
218
220 receipt.commandId = command.id;
221 receipt.executionId = "rpg-round-" + std::to_string(battle_.getTurn() + 1);
222 receipt.acceptedTick = tick_;
223 receipt.resultingRevision = revision_;
224 receipt.details = Value(Value::Object{{"skillId", Value(skillId)}, {"target", Value(targetText.value())}});
226}
227
229 const SimulationStep &step) {
230 if (instance != instance_)
232 Diagnostic::error(DiagnosticCode::NotFound, "RPG battle gameplay instance was not found", "instance"));
233 if (step.tick <= tick_)
235 Diagnostic::error(DiagnosticCode::Conflict, "RPG simulation tick must increase", "step.tick"));
236 auto authorized = observeGameplay(session, instance);
237 if (!authorized) return Result<GameplayObservation>::failure(authorized.status());
238 std::move(authorized).takeValue();
239 battle_.autoEnemyActions();
240 battle_.startRound();
241 while (battle_.executeNextAction() && !battle_.isFinished()) {
242 }
243 battle_.pollEvents();
244 tick_ = step.tick;
245 ++revision_;
246 for (int index = 0; index < battle_.getEventCount(); ++index) {
247 RPGActor *caster = battle_.getEventCaster(index);
248 GameplayEvent event;
249 event.sequence = nextEventSequence_++;
250 event.tick = tick_;
251 event.type = "rpg.battle." + battle_.getEventAction(index);
252 event.subject = subjectOf(caster ? caster : battle_.getEventTarget(index));
253 if (const auto found = lastCommandByActor_.find(caster); found != lastCommandByActor_.end()) {
254 event.causationCommandId = found->second;
255 event.correlationId = found->second;
256 }
257 event.payload = Value(Value::Object{
258 {"amount", Value(battle_.getEventAmount(index))},
259 {"critical", Value(battle_.getEventCrit(index))},
260 {"skillId", Value(battle_.getEventSkillId(index))},
261 {"target", Value(subjectOf(battle_.getEventTarget(index)).format())},
262 });
263 events_.push_back(std::move(event));
264 }
265 return observeGameplay(session, instance);
266}
267
269 std::uint64_t afterSequence) const {
270 auto authorized = observeGameplay(session, instance);
271 if (!authorized) return Result<std::vector<GameplayEvent>>::failure(authorized.status());
272 std::move(authorized).takeValue();
273 std::vector<GameplayEvent> result;
274 for (const auto &event : events_)
275 if (event.sequence > afterSequence) result.push_back(event);
276 const bool empty = result.empty();
277 return Result<std::vector<GameplayEvent>>::success(std::move(result),
279}
280
281} // namespace eve::rpg
282
283// BattleSystem.cpp
284namespace eve::rpg {
285
286namespace {
287
288std::unordered_map<std::string, SkillDamageSpec> &skillDamageTable() {
289 static std::unordered_map<std::string, SkillDamageSpec> t;
290 return t;
291}
292
293eve::Result<double> parseFormula(const std::string &formula, RPGActor *attacker, RPGActor *target, bool validateOnly);
294
295} // namespace
296
298 if (skillId.empty())
300 "skill damage id must not be empty", "skillId"));
301 if (!spec.formula.empty()) {
302 auto formula = parseFormula(spec.formula, nullptr, nullptr, true);
303 if (!formula) return eve::Result<void>::failure(formula.status());
304 }
305 skillDamageTable()[skillId] = spec;
307}
308
309void BattleSystem::registerSkillDamage(const std::string &skillId, const SkillDamageSpec &spec) {
310 registerSkillDamageChecked(skillId, spec).ignore("legacy RPG damage registration facade");
311}
312
313const SkillDamageSpec *BattleSystem::findSkillDamage(const std::string &skillId) {
314 auto &t = skillDamageTable();
315 auto it = t.find(skillId);
316 return it == t.end() ? nullptr : &it->second;
317}
318
319void BattleSystem::clearSkillDamage() { skillDamageTable().clear(); }
320
321namespace {
322
323// ---- 极简表达式求值器:支持数字、a.<param>、b.<param>、+ - * / ( ) ----
324struct FormulaParser {
325 const std::string &s;
326 size_t pos = 0;
327 RPGActor *a;
328 RPGActor *b;
330 std::optional<eve::Diagnostic> error;
331
332 FormulaParser(const std::string &str, RPGActor *atk, RPGActor *tgt, bool syntaxOnly)
333 : s(str), a(atk), b(tgt), validateOnly(syntaxOnly) {}
334
335 void skipSpace() {
336 while (pos < s.size() && std::isspace(static_cast<unsigned char>(s[pos]))) ++pos;
337 }
338
339 double parseExpression() {
340 double lhs = parseTerm();
341 while (true) {
342 skipSpace();
343 if (pos >= s.size()) break;
344 const char c = s[pos];
345 if (c == '+') {
346 ++pos;
347 lhs += parseTerm();
348 } else if (c == '-') {
349 ++pos;
350 lhs -= parseTerm();
351 } else {
352 break;
353 }
354 }
355 return lhs;
356 }
357
358 double parseTerm() {
359 double lhs = parseFactor();
360 while (true) {
361 skipSpace();
362 if (pos >= s.size()) break;
363 const char c = s[pos];
364 if (c == '*') {
365 ++pos;
366 lhs *= parseFactor();
367 } else if (c == '/') {
368 ++pos;
369 const double rhs = parseFactor();
370 if (validateOnly) {
371 lhs = 1.0;
372 } else if (rhs == 0.0) {
373 if (!error)
375 "damage formula cannot divide by zero",
376 "formula[" + std::to_string(pos) + "]");
377 lhs = 0.0;
378 } else {
379 lhs /= rhs;
380 }
381 } else {
382 break;
383 }
384 }
385 return lhs;
386 }
387
388 double parseFactor() {
389 skipSpace();
390 if (pos < s.size() && (s[pos] == '+' || s[pos] == '-')) {
391 const bool negate = s[pos++] == '-';
392 const double value = parseFactor();
393 return negate ? -value : value;
394 }
395 if (pos < s.size() && s[pos] == '(') {
396 ++pos;
397 double v = parseExpression();
398 skipSpace();
399 if (pos >= s.size() || s[pos] != ')') {
400 fail("damage formula is missing a closing parenthesis");
401 return 0.0;
402 }
403 ++pos;
404 return v;
405 }
406 if (pos < s.size() && (s[pos] == 'a' || s[pos] == 'b') && pos + 1 < s.size() && s[pos + 1] == '.') {
407 const bool isA = s[pos] == 'a';
408 pos += 2;
409 std::string name;
410 while (pos < s.size() && (std::isalnum(static_cast<unsigned char>(s[pos])) || s[pos] == '_')) {
411 name.push_back(s[pos++]);
412 }
413 if (name.empty()) {
414 fail("damage formula attribute name must not be empty");
415 return 0.0;
416 }
417 RPGActor *actor = isA ? a : b;
418 return actor ? AttributeSystem::getFinal(actor, name) : 0.0;
419 }
420 if (pos < s.size() && (std::isdigit(static_cast<unsigned char>(s[pos])) || s[pos] == '.')) {
421 std::string num;
422 while (pos < s.size() && (std::isdigit(static_cast<unsigned char>(s[pos])) || s[pos] == '.')) {
423 num.push_back(s[pos++]);
424 }
425 char *end = nullptr;
426 const double value = std::strtod(num.c_str(), &end);
427 if (end == num.c_str() || *end != '\0' || !std::isfinite(value)) {
428 fail("damage formula contains an invalid number");
429 return 0.0;
430 }
431 return value;
432 }
433 fail("damage formula expected a number, attribute, unary sign, or parenthesized expression");
434 return 0.0;
435 }
436
437 void fail(std::string message) {
438 if (error) return;
440 "formula[" + std::to_string(pos) + "]");
441 }
442};
443
444eve::Result<double> parseFormula(const std::string &formula, RPGActor *attacker, RPGActor *target, bool validateOnly) {
445 if (formula.empty())
447 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "damage formula must not be empty", "formula"));
448 FormulaParser parser(formula, attacker, target, validateOnly);
449 const double value = parser.parseExpression();
450 parser.skipSpace();
451 if (parser.error) return eve::Result<double>::failure(std::move(*parser.error));
452 if (parser.pos != formula.size())
454 "damage formula contains trailing input",
455 "formula[" + std::to_string(parser.pos) + "]"));
456 if (!std::isfinite(value))
458 "damage formula result must be finite", "formula"));
460}
461
462} // namespace
463
464double BattleSystem::evaluateFormula(const std::string &formula, RPGActor *attacker, RPGActor *target) {
465 return std::move(evaluateFormulaChecked(formula, attacker, target)).valueOr(0.0);
466}
467
469 RPGActor *target) {
470 return parseFormula(formula, attacker, target, false);
471}
472
474 unsigned seed) {
476 if (!attacker || !target) return result;
477 std::mt19937 rng(seed);
478 std::uniform_real_distribution<double> dist(0.0, 1.0);
479
480 // 命中判定:攻击方 hit + (100 - 目标 evasion)
481 double attackerHit = 100.0 + TraitSystem::getExParam(attacker, "hit");
482 double targetEvasion = TraitSystem::getExParam(target, "evasion");
483 double hitChance = spec.hitChance + attackerHit - targetEvasion;
484 if (dist(rng) * 100.0 >= hitChance) {
485 result.hit = false;
486 return result;
487 }
488
489 // 公式(默认物理:a.atk - b.def,至少 1)
490 double amount;
491 if (spec.formula.empty()) {
492 amount = AttributeSystem::getFinal(attacker, "attack") - AttributeSystem::getFinal(target, "defense");
493 } else {
494 amount = evaluateFormula(spec.formula, attacker, target);
495 }
496 if (amount <= 0.0) amount = 1.0;
497
498 // 元素耐性
499 if (!spec.element.empty()) {
501 amount *= result.elementRate;
502 }
503
504 // 暴击(RPG Maker 默认 3x)
505 double critChance = spec.critChance + TraitSystem::getExParam(attacker, "critRate");
506 if (critChance > 0.0 && dist(rng) < critChance) {
507 result.crit = true;
508 amount *= 3.0;
509 }
510
511 result.amount = amount;
512 return result;
513}
514
515} // namespace eve::rpg
516
517// BattleTactics.cpp
518namespace eve::rpg {
519namespace {
520
521std::unordered_map<std::string, BattleTacticsDefinition> &definitions() {
522 static std::unordered_map<std::string, BattleTacticsDefinition> value;
523 return value;
524}
525
526bool validId(const std::string &value, bool allowEmpty = false) {
527 if (value.empty()) return allowEmpty;
528 if (value.size() > 256) return false;
529 for (unsigned char ch : value)
530 if (ch < 0x20 || ch == 0x7f) return false;
531 return true;
532}
533
534bool parsePolicy(const std::string &value, BattleTargetPolicy &policy) {
535 if (value == "auto")
537 else if (value == "self")
539 else if (value == "lowestHealthAlly")
541 else if (value == "lowestHealthEnemy")
543 else
544 return false;
545 return true;
546}
547
548bool policyMatchesTargetType(BattleTargetPolicy policy, const std::string &targetType) {
549 if (policy == BattleTargetPolicy::Auto) return true;
550 if (targetType == "self") return policy == BattleTargetPolicy::Self;
551 if (targetType == "allySingle") return policy == BattleTargetPolicy::LowestHealthAlly;
553}
554
555} // namespace
556
558 std::string parseError;
559 const auto document = eve::json::Document::parse(json, &parseError);
560 if (!document.valid())
562 parseError.empty() ? "invalid JSON" : parseError, "$",
563 {}, "rpg.battle-tactics"));
564 const auto root = document.root();
565 if (!root.isArray() || root.size() == 0)
567 "battle tactics catalogue must be a non-empty array",
568 "$", {}, "rpg.battle-tactics"));
569 const std::unordered_set<std::string> definitionFields = {"id", "rules"};
570 const std::unordered_set<std::string> ruleFields = {"skillId", "targetPolicy", "conditionResource", "belowRatio"};
571 std::unordered_map<std::string, BattleTacticsDefinition> proposed;
572 for (std::size_t index = 0; index < root.size(); ++index) {
573 const auto object = root.at(index);
574 const std::string path = "$[" + std::to_string(index) + "]";
575 if (!object.isObject())
577 "battle tactics definition must be an object", path,
578 {}, "rpg.battle-tactics"));
579 for (const auto &key : object.keys())
580 if (!definitionFields.contains(key))
582 eve::DiagnosticCode::InvalidArgument, "battle tactics definition contains an unknown field",
583 path + "." + key, {}, "rpg.battle-tactics"));
584 const auto id = object.get("id");
585 const auto rules = object.get("rules");
586 if (!id.isString() || !validId(id.asString()))
588 "battle tactics id must be a stable non-empty id",
589 path + ".id", {}, "rpg.battle-tactics"));
590 if (proposed.contains(id.asString()))
592 "duplicate battle tactics id", path + ".id", {},
593 "rpg.battle-tactics"));
594 if (!rules.isArray() || rules.size() == 0 || rules.size() > 16)
596 "rules must contain between 1 and 16 entries",
597 path + ".rules", {}, "rpg.battle-tactics"));
598 BattleTacticsDefinition definition;
599 definition.id = id.asString();
600 for (std::size_t ruleIndex = 0; ruleIndex < rules.size(); ++ruleIndex) {
601 const auto rule = rules.at(ruleIndex);
602 const std::string rulePath = path + ".rules[" + std::to_string(ruleIndex) + "]";
603 if (!rule.isObject())
605 "battle tactic rule must be an object",
606 rulePath, {}, "rpg.battle-tactics"));
607 for (const auto &key : rule.keys())
608 if (!ruleFields.contains(key))
610 eve::DiagnosticCode::InvalidArgument, "battle tactic rule contains an unknown field",
611 rulePath + "." + key, {}, "rpg.battle-tactics"));
612 const auto skillId = rule.get("skillId");
613 const auto targetPolicy = rule.get("targetPolicy");
614 const auto conditionResource = rule.get("conditionResource");
615 const auto belowRatio = rule.get("belowRatio");
616 if (!skillId.isString() || !validId(skillId.asString(), true) ||
617 (!skillId.asString().empty() && !SkillRegistry::find(skillId.asString())))
619 eve::DiagnosticCode::NotFound, "skillId must be empty or reference a registered skill",
620 rulePath + ".skillId", {}, "rpg.battle-tactics"));
622 if (!targetPolicy.isString() || !parsePolicy(targetPolicy.asString(), parsedPolicy))
625 rulePath + ".targetPolicy", {}, "rpg.battle-tactics"));
626 const std::string targetType =
627 skillId.asString().empty() ? "enemySingle" : SkillRegistry::find(skillId.asString())->targetType;
628 if (!policyMatchesTargetType(parsedPolicy, targetType))
630 eve::DiagnosticCode::InvalidArgument, "targetPolicy does not match the skill target type",
631 rulePath + ".targetPolicy", {}, "rpg.battle-tactics"));
632 if (!conditionResource.isString() || !validId(conditionResource.asString(), true) ||
633 !belowRatio.isNumber() || !std::isfinite(belowRatio.asDouble()) || belowRatio.asDouble() < 0.0 ||
634 belowRatio.asDouble() > 1.0)
636 "conditionResource and belowRatio are invalid",
637 rulePath, {}, "rpg.battle-tactics"));
638 if (parsedPolicy == BattleTargetPolicy::Auto && !conditionResource.asString().empty())
640 eve::DiagnosticCode::InvalidArgument, "conditional rules require an explicit target policy",
641 rulePath, {}, "rpg.battle-tactics"));
642 BattleTacticRule parsed;
643 parsed.skillId = skillId.asString();
644 parsed.targetPolicy = parsedPolicy;
645 parsed.conditionResource = conditionResource.asString();
646 parsed.belowRatio = belowRatio.asDouble();
647 definition.rules.push_back(std::move(parsed));
648 }
649 if (!definition.rules.back().conditionResource.empty())
651 eve::DiagnosticCode::InvalidArgument, "the final battle tactic rule must be unconditional",
652 path + ".rules", {}, "rpg.battle-tactics"));
653 proposed.emplace(definition.id, std::move(definition));
654 }
655 definitions() = std::move(proposed);
656 return eve::Result<int>::success(static_cast<int>(definitions().size()));
657}
658
660int BattleTacticsCatalogue::count() { return static_cast<int>(definitions().size()); }
661
663 const std::string &tacticsId) {
664 if (!battle || !actor)
666 "battle and actor must not be null", "battle",
667 {}, "rpg.battle-tactics"));
668 const auto found = definitions().find(tacticsId);
669 if (found == definitions().end())
671 "battle tactics id is not registered",
672 "tacticsId", {}, "rpg.battle-tactics"));
673 for (const auto &rule : found->second.rules) {
674 if (!rule.conditionResource.empty()) {
675 const int side = battle->sideOf(actor);
677 rule.targetPolicy == BattleTargetPolicy::Self
678 ? actor
679 : battle->lowestHealthTarget(side, rule.targetPolicy == BattleTargetPolicy::LowestHealthAlly);
680 if (!target) continue;
681 const double maximum = target->getMax(rule.conditionResource);
682 if (maximum <= 0.0 || target->getCurrent(rule.conditionResource) / maximum >= rule.belowRatio) continue;
683 }
684 auto queued = battle->setActionByPolicyChecked(actor, rule.skillId, rule.targetPolicy);
685 if (!queued.ok()) return eve::Result<std::string>::failure(queued.status());
686 return eve::Result<std::string>::success(rule.skillId);
687 }
689 "battle tactics has no applicable default rule",
690 "rules", {}, "rpg.battle-tactics"));
691}
692
693} // namespace eve::rpg
694
695// BattleVictory.cpp
696namespace eve::rpg {
697namespace {
698
699eve::Result<BattleVictoryReceipt> victoryFailure(eve::DiagnosticCode code, std::string message, std::string path,
700 const BattleVictoryRequest &request) {
702 eve::Diagnostic::error(code, std::move(message), std::move(path),
703 {{"mapId", request.mapId}, {"objectId", request.objectId}}, "rpg.battle-victory"));
704}
705
706struct TrackerRollback {
707 std::unordered_map<std::string, QuestRuntime> entries;
708 std::vector<std::string> order;
709 std::vector<QuestEvent> pending;
710 std::vector<QuestEvent> polled;
711};
712
713void restoreTracker(Tracker &tracker, TrackerRollback rollback) {
714 tracker.entries = std::move(rollback.entries);
715 tracker.order = std::move(rollback.order);
716 tracker.pending = std::move(rollback.pending);
717 tracker.polled = std::move(rollback.polled);
718}
719
720bool finiteAddition(const GameState &state, const std::string &id, double amount) {
721 return id.empty() ? amount == 0.0 : std::isfinite(amount) && std::isfinite(state.getVariable(id) + amount);
722}
723
724} // namespace
725
728 if (!request.requiredQuestId.empty() && tracker.getState(request.requiredQuestId) != "active")
729 return victoryFailure(eve::DiagnosticCode::PreconditionViolation,
730 "required quest must be active before victory settlement", "requiredQuestId", request);
731 if (request.notifyTopic.empty() || request.notifyTarget.empty() || request.notifyAmount <= 0)
732 return victoryFailure(eve::DiagnosticCode::InvalidArgument,
733 "victory quest notification must be complete and positive", "notification", request);
734 if (request.attributeId.empty() || !std::isfinite(request.attributeAmount) || request.attributeAmount < 0.0 ||
735 !finiteAddition(gameState, request.attributeId, request.attributeAmount))
736 return victoryFailure(eve::DiagnosticCode::InvalidArgument, "victory attribute reward is invalid or non-finite",
737 "attribute", request);
738 if (request.defeatCounterId.empty() || request.defeatCounterAmount <= 0 ||
739 !finiteAddition(gameState, request.defeatCounterId, static_cast<double>(request.defeatCounterAmount)))
740 return victoryFailure(eve::DiagnosticCode::InvalidArgument, "victory counter increment is invalid",
741 "defeatCounter", request);
742 if (request.levelPointAttributeId.empty() || request.pointsPerLevel < 0)
743 return victoryFailure(eve::DiagnosticCode::InvalidArgument, "level-point reward configuration is invalid",
744 "levelPoints", request);
745
746 auto preparedXp = LevelSystem::prepareGainXp(&actor, request.xpAmount, request.xpGrowth);
747 if (!preparedXp.ok()) return eve::Result<BattleVictoryReceipt>::failure(preparedXp.status());
748 PreparedProgressionGain xp = std::move(preparedXp).takeValue();
749 const int levelsGained = xp.levelsGained();
750 const double levelPoints = static_cast<double>(levelsGained) * request.pointsPerLevel;
751 if (!finiteAddition(gameState, request.levelPointAttributeId, levelPoints))
752 return victoryFailure(eve::DiagnosticCode::InvalidArgument,
753 "level-point reward would produce a non-finite value", "levelPoints", request);
754
755 auto gameStateBefore = gameState.snapshotJson();
756 if (!gameStateBefore.ok()) return eve::Result<BattleVictoryReceipt>::failure(gameStateBefore.status());
757 std::string gameStateSnapshot = std::move(gameStateBefore).takeValue();
758 GameState candidateState;
759 auto candidateRestore = candidateState.restoreSnapshotJson(gameStateSnapshot);
760 if (!candidateRestore.ok()) return eve::Result<BattleVictoryReceipt>::failure(candidateRestore.status());
761 WorldState candidateWorld(candidateState);
762 if (candidateWorld.isObjectConsumed(request.mapId, request.objectId))
763 return victoryFailure(eve::DiagnosticCode::Conflict, "encounter was already consumed", "objectId", request);
764 auto candidateConsume = candidateWorld.consumeObject(request.mapId, request.objectId);
765 if (!candidateConsume.ok()) return eve::Result<BattleVictoryReceipt>::failure(candidateConsume.status());
766
767 TrackerRollback trackerBefore{tracker.entries, tracker.order, tracker.pending, tracker.polled};
768 gameState.addVariable(request.attributeId, request.attributeAmount);
769 gameState.addVariable(request.defeatCounterId, request.defeatCounterAmount);
770 if (levelPoints > 0.0) gameState.addVariable(request.levelPointAttributeId, levelPoints);
771 tracker.notify(request.notifyTopic, request.notifyTarget, request.notifyAmount);
772 WorldState world(gameState);
773 auto consumed = world.consumeObject(request.mapId, request.objectId);
774 if (!consumed.ok() || consumed.code() != eve::StatusCode::Applied) {
775 auto restored = gameState.restoreSnapshotJson(gameStateSnapshot);
776 const bool restoredOk = restored.ok();
777 restoreTracker(tracker, std::move(trackerBefore));
778 if (!restoredOk)
779 return victoryFailure(eve::DiagnosticCode::InvariantViolation,
780 "victory rollback could not restore GameState", "rollback", request);
781 return victoryFailure(eve::DiagnosticCode::Conflict, "encounter changed before victory commit", "objectId",
782 request);
783 }
784
785 auto committedXp = LevelSystem::commitGainXp(std::move(xp));
786 if (!committedXp.ok()) {
787 auto restored = gameState.restoreSnapshotJson(gameStateSnapshot);
788 const bool restoredOk = restored.ok();
789 restoreTracker(tracker, std::move(trackerBefore));
790 if (!restoredOk)
791 return victoryFailure(eve::DiagnosticCode::InvariantViolation,
792 "victory rollback could not restore GameState", "rollback", request);
793 return eve::Result<BattleVictoryReceipt>::failure(committedXp.status());
794 }
795
796 BattleVictoryReceipt receipt;
797 receipt.levelsGained = std::move(committedXp).takeValue();
799 return eve::Result<BattleVictoryReceipt>::success(std::move(receipt),
801}
802
803} // namespace eve::rpg
LogicalId target
int root
Definition AnimSmr.cpp:119
int subject
Definition AnimSmr.cpp:163
RPG's thin compatibility facade over the attributes module.
std::vector< QuestEvent > pending
const std::string & s
std::unordered_map< std::string, QuestRuntime > entries
std::vector< QuestEvent > polled
bool validateOnly
Player-equivalent, host-neutral control adapter for one RPG Battle.
伤害公式 DSL 与技能伤害注册。
Strict ordered battle-action policies for companions and AI.
Atomic post-battle progression and persistent-world settlement.
回合制战斗对象:参战者、行动顺序、目标选取、行动执行。
职业系统:设定职业、施加职业基础特征、按等级自动学习技能。
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
全局游戏状态:开关(bool)、变量(数字)、独立变量(按作用域)。
std::string message
DiagnosticCode code
float maximum[3]
const GltfImportRequest & request
float v
std::int32_t c
std::map< unsigned, Colour > definitions
角色成长:等级 / 经验 / 升级。
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::int32_t > order
size_t queued
Definition OnnxGpgpu.cpp:60
std::string error
Definition Package.cpp:174
std::array< uint32_t, 9 > parameters
std::string path
Definition PlayHost.cpp:111
std::uint32_t targetId
Object::Ptr value
float t
bool found
size_t end
std::optional< InteractionSession > session
Definition Tactics.cpp:39
Json object
目标追踪器运行时实例(玩家日志 / 成就 / 教程可各建一份)。
特征系统:施加/移除运行时特征,并提供耐性/特殊参数/攻击附加等查询。
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
const std::string & format() const noexcept
Returns the canonical namespace:name representation.
Definition Identity.h:439
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
static SubjectRef fromPersistentId(PersistentId id) noexcept
Wrap a persistent identity without changing its bytes.
Definition SubjectRef.h:32
static SubjectRef nil() noexcept
Return the invalid nil reference.
Definition SubjectRef.h:35
std::string format() const
Return the canonical lower-case UUID spelling.
Definition SubjectRef.h:44
bool isValid() const noexcept
Return whether this reference is valid and non-nil.
Definition SubjectRef.h:38
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
static double getFinal(RPGActor *actor, const std::string &attribute)
Compute the final value through the canonical attributes engine.
BattleControl(Battle &battle, SubjectRef instance)
Construct an adapter over a borrowed battle and stable instance identity.
std::vector< SubjectRef > gameplayInstances() const override
Instances currently served, in publication order.
Result< void > bindParticipant(SubjectRef subject, RPGActor *actor)
Bind a stable subject to an existing battle participant.
Result< GameplayObservation > observeGameplay(const GameplaySession &session, SubjectRef instance) const override
Observe one provider-owned gameplay instance without mutation.
Result< GameplayObservation > advanceGameplay(const GameplaySession &session, SubjectRef instance, const SimulationStep &step) override
Advance one provider-owned instance using injected deterministic time.
~BattleControl() override
Unpublish the capability without destroying the borrowed battle.
std::string_view gameplayDomain() const noexcept override
Stable provider domain used for discovery and routing.
Result< std::vector< GameplayEvent > > gameplayEvents(const GameplaySession &session, SubjectRef instance, std::uint64_t afterSequence) const override
Return events strictly newer than an instance-local sequence cursor.
Result< GameplayCommandReceipt > submitGameplay(const GameplaySession &session, SubjectRef instance, const GameplayCommand &command) override
Validate authority and atomically submit one domain command.
Result< std::vector< GameplayActionDescriptor > > availableGameplayActions(const GameplaySession &session, SubjectRef instance, SubjectRef subject) const override
Discover currently legal player-semantic actions for one subject.
static DamageResult resolveHit(RPGActor *attacker, RPGActor *target, const SkillDamageSpec &spec, unsigned seed)
结算一次命中:命中判定、公式、元素耐性、暴击。
static void clearSkillDamage()
Clears skill damage.
static eve::Result< double > evaluateFormulaChecked(const std::string &formula, RPGActor *attacker, RPGActor *target)
Strictly parse and evaluate a damage formula.
static double evaluateFormula(const std::string &formula, RPGActor *attacker, RPGActor *target)
求值伤害公式。
static void registerSkillDamage(const std::string &skillId, const SkillDamageSpec &spec)
Compatibility facade; invalid definitions are ignored.
static eve::Result< void > registerSkillDamageChecked(const std::string &skillId, const SkillDamageSpec &spec)
Validate and publish one skill damage definition atomically.
static const SkillDamageSpec * findSkillDamage(const std::string &skillId)
Finds skill damage.
static int count()
Returns the number of .
static eve::Result< std::string > queueAction(Battle *battle, RPGActor *actor, const std::string &tacticsId)
Select the first matching rule and queue it through Battle's canonical checked API.
static eve::Result< int > replaceFromJsonStrict(const std::string &json)
Validate and atomically replace all tactic definitions.
static eve::Result< BattleVictoryReceipt > settle(RPGActor &actor, GameState &gameState, Tracker &tracker, const BattleVictoryRequest &request)
Atomically settle XP, derived class skills, attributes, quest progress, and encounter consumption.
一场回合制战斗(任意阵营数)。 @ownership 由调用方创建/销毁;Battle 不持有参与者的所有权(参与者为借用 ECS actor)。 @thread 在单一模拟线程上驱动整场战斗。
Definition Battle.h:54
RPGActor * getActor(int index) const
Return a participant actor by index, or null when out of range.
Definition Battle.cpp:487
void startRound()
结算所有已设行动:先攻排序、清空待行动,回合数 +1。
Definition Battle.cpp:298
void autoEnemyActions()
未设行动的 AI 侧自动选一个随机已学技能(或普攻)打随机存活敌对目标。
Definition Battle.cpp:272
bool getEventCrit(int index) const
Returns the event crit.
Definition Battle.cpp:526
double getEventAmount(int index) const
Returns the event amount.
Definition Battle.cpp:522
int getSide(int index) const
Returns the side.
Definition Battle.cpp:491
std::string getEventSkillId(int index) const
Returns the event skill id.
Definition Battle.cpp:510
RPGActor * getEventCaster(int index) const
Return the caster of a polled event, or null when out of range.
Definition Battle.cpp:514
RPGActor * getEventTarget(int index) const
Return the target of a polled event, or null when out of range.
Definition Battle.cpp:518
std::string getEventAction(int index) const
Returns the event action.
Definition Battle.cpp:506
int getTurn() const
当前回合数(1 起)。
Definition Battle.cpp:192
bool isActorAlive(RPGActor *actor) const
True when actor alive.
Definition Battle.cpp:138
eve::Result< void > setActionChecked(RPGActor *actor, const std::string &skillId, RPGActor *target=nullptr)
Validate and queue exactly one action for a living participant this round.
Definition Battle.cpp:214
void pollEvents()
Polls events.
Definition Battle.cpp:501
int getActorCount() const
Returns the actor count.
Definition Battle.cpp:486
eve::Result< void > setActionByPolicyChecked(RPGActor *actor, const std::string &skillId, BattleTargetPolicy policy)
Resolve a deterministic target policy and queue one checked action atomically.
Definition Battle.cpp:254
bool executeNextAction()
执行下一条行动(compatibility facade (脚本兼容门面));返回是否执行了一条。
Definition Battle.cpp:316
bool isDefeat() const
是否战败:已结束且获胜方 != 玩家侧。
Definition Battle.cpp:190
int getEventCount() const
Returns the event count.
Definition Battle.cpp:496
bool isFinished() const
战斗是否已结束(仅剩一方存活 / 双方全灭)。
Definition Battle.cpp:188
bool isVictory() const
是否胜利:获胜方 == 玩家侧。
Definition Battle.cpp:189
static int checkLevelSkills(RPGActor *actor)
按当前等级补学尚未学过的升级技能。
Definition Class.cpp:123
一份游戏状态(开关/变量/独立变量)。
Definition GameState.h:26
void addVariable(const std::string &name, double delta)
Adds variable.
Definition GameState.cpp:70
eve::Result< void > restoreSnapshotJson(std::string_view json)
Validate and atomically restore a canonical RPG game-state JSON document.
eve::Result< std::string > snapshotJson() const
Serialize this state as the canonical versioned RPG game-state JSON document.
static eve::Result< PreparedProgressionGain > prepareGainXp(RPGActor *actor, double amount, double xpGrowth=1.2)
Validate an XP gain and calculate its complete progression candidate without mutation/events.
Definition Class.cpp:226
static eve::Result< int > commitGainXp(PreparedProgressionGain prepared)
Commit a prepared XP gain if actor progression is still unchanged.
Definition Class.cpp:271
Move-only progression gain prepared against one actor revision.
Definition LevelSystem.h:25
int levelsGained() const noexcept
Number of level transitions contained in this prepared candidate.
Definition LevelSystem.h:30
属性 / 状态 / 技能三表合一的 ECS 实体。
Definition RPGActor.h:34
double getCurrent(const std::string &resource)
生命等当前资源(VitalsSystem 的薄转发,max 取同名最终属性)。
Definition RPGActor.cpp:229
double getMax(const std::string &resource)
Definition RPGActor.cpp:233
static const SkillDefinition * find(const std::string &id)
Find a registered skill definition by id.
Definition Skill.cpp:98
一份任务进度 + 本实例事件队列。
Definition Tracker.h:26
std::unordered_map< std::string, QuestRuntime > entries
运行时条目(QuestSystem 读写;公开以便测试与脚本查询)。
Definition Tracker.h:148
std::vector< std::string > order
Definition Tracker.h:149
std::vector< QuestEvent > pending
Definition Tracker.h:150
void notify(const std::string &topic, const std::string &target, int amount)
Notify.
Definition Tracker.cpp:26
std::string getState(const std::string &id) const
Returns the state.
Definition Tracker.cpp:202
std::vector< QuestEvent > polled
Definition Tracker.h:151
static double getElementRate(RPGActor *actor, const std::string &element)
元素耐性乘积(1 = 无修正,0.5 = 减半)。
Definition Trait.cpp:206
static double getExParam(RPGActor *actor, const std::string &exParam)
特殊参数加值(hit/evasion/critRate/critEvade/magicEvade/magicReflect/...)。
Definition Trait.cpp:244
Non-owning typed adapter for persistent per-map object lifecycle state.
Definition WorldState.h:19
bool isObjectConsumed(std::string_view mapId, std::string_view objectId) const
Query whether a stable object has been consumed in one map.
eve::Result< void > consumeObject(std::string_view mapId, std::string_view objectId)
Idempotently publish the consumed fact for one stable map object.
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
bool parsePolicy(const std::string &name, StackPolicy &policy)
Parses a lowercase legacy stack policy name.
RPG 模块的基础实体:把属性 / 状态 / 技能三张表挂到一个 ECS 实体上。
BattleTargetPolicy
Deterministic target-selection policies for queued battle actions.
Definition Battle.h:36
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Owning evidence that a gameplay authority accepted one command.
One player-semantic command submitted to a domain authority.
std::uint64_t expectedRevision
SimulationTick observedTick
Owning event projection safe across frames and process boundaries.
std::uint64_t sequence
Immutable owning observation of one authoritative gameplay instance.
Owning authorization context shared by player, script and automation adapters.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
One ordered tactic rule; an empty condition resource is an unconditional default.
BattleTargetPolicy targetPolicy
One immutable ordered tactic definition.
Observable summary returned after a complete victory settlement.
Complete data needed to settle one victorious persistent encounter.
一次命中结算结果。
一次技能命中的伤害规格。
double critChance
追加到攻击方 critRate 的暴击率
int hitChance
命中率(百分比)
std::string formula
公式字符串,如 "a.atk * 4 - b.def * 2";空则对 hp 用默认物理公式。
std::string element
元素("" = 无);伤害乘目标对应元素耐性。
std::string targetType
Definition Skill.h:33
bool consumed
Definition Graphics.cpp:201