载入中...
搜索中...
未找到
ShopCatalogue.cpp
浏览该文件的文档.
1#include "rpg/ShopCatalogue.h"
2#include <climits>
3#include <cmath>
4#include <unordered_map>
5#include <unordered_set>
6#include <utility>
7#include <vector>
8#include "common/Json.h"
10#include "inventory/Item.h"
11#include "rpg/GameState.h"
12#include "rpg/ShopTransaction.h"
13
14// ShopCatalogue.cpp
15namespace eve::rpg {
16namespace {
17
18std::vector<ShopOffer> &offers() {
19 static std::vector<ShopOffer> value;
20 return value;
21}
22
23std::unordered_map<std::string, std::size_t> &offerIndex() {
24 static std::unordered_map<std::string, std::size_t> value;
25 return value;
26}
27
28bool validId(const std::string &value) {
29 if (value.empty() || value.size() > 256) return false;
30 for (unsigned char ch : value)
31 if (ch < 0x20 || ch == 0x7f) return false;
32 return true;
33}
34
35eve::Result<int> failure(std::string message, std::string path) {
37 std::move(path), {}, "rpg.shop-catalogue"));
38}
39
40bool onlyKnownFields(const eve::json::Value &object) {
41 static const std::unordered_set<std::string> known = {"id", "itemId", "name", "desc", "buyPrice", "sellPrice"};
42 for (const auto &key : object.keys())
43 if (known.count(key) == 0) return false;
44 return true;
45}
46
47} // namespace
48
50 std::string parseError;
51 const auto document = eve::json::Document::parse(json, &parseError);
52 if (!document.valid()) return failure(parseError.empty() ? "invalid JSON" : parseError, "$");
53 const auto root = document.root();
54 if (!root.isArray() || root.size() == 0) return failure("shop catalogue must be a non-empty array", "$");
55
56 std::vector<ShopOffer> proposed;
57 std::unordered_map<std::string, std::size_t> proposedIndex;
58 proposed.reserve(root.size());
59 for (std::size_t index = 0; index < root.size(); ++index) {
60 const auto object = root.at(index);
61 const std::string path = "$[" + std::to_string(index) + "]";
62 if (!object.isObject()) return failure("shop offer must be an object", path);
63 if (!onlyKnownFields(object)) return failure("shop offer contains an unknown field", path);
64 const auto id = object.get("id");
65 const auto itemIdValue = object.get("itemId");
66 const auto name = object.get("name");
67 const auto description = object.get("desc");
68 const auto buyPrice = object.get("buyPrice");
69 const auto sellPrice = object.get("sellPrice");
70 if (!id.isString() || !validId(id.asString()))
71 return failure("offer id must be a stable non-empty id", path + ".id");
72 const std::string itemId = itemIdValue.isString() ? itemIdValue.asString() : std::string{};
73 if (!validId(itemId)) return failure("itemId must be a stable non-empty id", path + ".itemId");
75 return failure("shop offer references an unknown inventory item", path + ".itemId");
76 if (!name.isString() || name.asString().empty() || name.asString().size() > 512)
77 return failure("name must be a non-empty string of at most 512 bytes", path + ".name");
78 if (!description.isString() || description.asString().size() > 2048)
79 return failure("desc must be a string of at most 2048 bytes", path + ".desc");
80 if (!buyPrice.isInt64() || buyPrice.asInt64() < 0 || buyPrice.asInt64() > INT_MAX)
81 return failure("buyPrice must be a non-negative integer", path + ".buyPrice");
82 if (!sellPrice.isInt64() || sellPrice.asInt64() < 0 || sellPrice.asInt64() > buyPrice.asInt64())
83 return failure("sellPrice must be a non-negative integer no greater than buyPrice", path + ".sellPrice");
84 if (proposedIndex.count(id.asString()) != 0) return failure("duplicate offer id", path + ".id");
85 ShopOffer offer;
86 offer.id = id.asString();
87 offer.itemId = itemId;
88 offer.displayName = name.asString();
89 offer.description = description.asString();
90 offer.buyPrice = static_cast<int>(buyPrice.asInt64());
91 offer.sellPrice = static_cast<int>(sellPrice.asInt64());
92 proposedIndex.emplace(offer.id, proposed.size());
93 proposed.push_back(std::move(offer));
94 }
95 offers() = std::move(proposed);
96 offerIndex() = std::move(proposedIndex);
97 return eve::Result<int>::success(static_cast<int>(offers().size()));
98}
99
101 offers().clear();
102 offerIndex().clear();
103}
104
105int ShopCatalogue::count() { return static_cast<int>(offers().size()); }
106
107const ShopOffer *ShopCatalogue::find(const std::string &id) {
108 const auto found = offerIndex().find(id);
109 return found == offerIndex().end() ? nullptr : &offers()[found->second];
110}
111
113 return index < 0 || index >= count() ? nullptr : &offers()[static_cast<std::size_t>(index)];
114}
115
116} // namespace eve::rpg
117
118// ShopTransaction.cpp
119namespace eve::rpg {
120namespace {
121
122eve::Result<int> tradeFailure(eve::DiagnosticCode code, std::string message, std::string path,
123 const std::string &itemId) {
125 {{"itemId", itemId}}, "rpg.shop-transaction"));
126}
127
128eve::Result<double> validateTrade(const GameState &gameState, const std::string &currencyId, const std::string &itemId,
129 int quantity, double unitPrice, bool purchase) {
130 if (currencyId.empty() || itemId.empty() || quantity <= 0 || !std::isfinite(unitPrice) || unitPrice < 0.0)
133 "shop trade requires currency/item ids, positive quantity, and finite non-negative unit price", "trade",
134 {{"itemId", itemId}}, "rpg.shop-transaction"));
135 const double total = unitPrice * static_cast<double>(quantity);
136 const double balance = gameState.getVariable(currencyId);
137 const double result = purchase ? balance - total : balance + total;
138 if (!std::isfinite(total) || !std::isfinite(balance) || !std::isfinite(result))
140 eve::DiagnosticCode::InvalidArgument, "shop trade would produce a non-finite currency value", "unitPrice",
141 {{"itemId", itemId}}, "rpg.shop-transaction"));
142 if (purchase && balance < total)
144 eve::DiagnosticCode::PreconditionViolation, "shop purchase has insufficient currency", "currency",
145 {{"itemId", itemId}}, "rpg.shop-transaction"));
146 return eve::Result<double>::success(total);
147}
148
149eve::Result<int> rollbackFailure(GameState &gameState, const std::string &snapshot, const eve::Status &commitStatus,
150 const std::string &itemId) {
151 auto restored = gameState.restoreSnapshotJson(snapshot);
152 if (!restored.ok())
153 return tradeFailure(eve::DiagnosticCode::InvariantViolation, "shop trade rollback could not restore GameState",
154 "rollback", itemId);
155 return eve::Result<int>::failure(commitStatus);
156}
157
158} // namespace
159
160eve::Result<int> ShopTransaction::buyOffer(GameState &gameState, inventory::Bag &bag, const std::string &currencyId,
161 const std::string &offerId, int quantity) {
162 const ShopOffer *offer = ShopCatalogue::find(offerId);
163 if (!offer)
164 return tradeFailure(eve::DiagnosticCode::NotFound, "shop purchase references an unknown offer", "offerId",
165 offerId);
166 return buy(gameState, bag, currencyId, offer->itemId, quantity, static_cast<double>(offer->buyPrice));
167}
168
169eve::Result<int> ShopTransaction::sellOffer(GameState &gameState, inventory::Bag &bag, const std::string &currencyId,
170 const std::string &offerId, int quantity) {
171 const ShopOffer *offer = ShopCatalogue::find(offerId);
172 if (!offer)
173 return tradeFailure(eve::DiagnosticCode::NotFound, "shop sale references an unknown offer", "offerId", offerId);
174 return sell(gameState, bag, currencyId, offer->itemId, quantity, static_cast<double>(offer->sellPrice));
175}
176
177eve::Result<int> ShopTransaction::buy(GameState &gameState, inventory::Bag &bag, const std::string &currencyId,
178 const std::string &itemId, int quantity, double unitPrice) {
179 auto validated = validateTrade(gameState, currencyId, itemId, quantity, unitPrice, true);
180 if (!validated.ok()) return eve::Result<int>::failure(validated.status());
181 const double total = std::move(validated).takeValue();
182 auto prepared = inventory::InventorySystem::prepareAddBatch(&bag, {{itemId, quantity}});
183 if (!prepared.ok()) return eve::Result<int>::failure(prepared.status());
184 auto before = gameState.snapshotJson();
185 if (!before.ok()) return eve::Result<int>::failure(before.status());
186 std::string snapshot = std::move(before).takeValue();
187
188 gameState.addVariable(currencyId, -total);
189 auto committed = inventory::InventorySystem::commitAddBatch(std::move(prepared).takeValue());
190 if (!committed.ok()) return rollbackFailure(gameState, snapshot, committed.status(), itemId);
191 return committed;
192}
193
194eve::Result<int> ShopTransaction::sell(GameState &gameState, inventory::Bag &bag, const std::string &currencyId,
195 const std::string &itemId, int quantity, double unitPrice) {
196 auto validated = validateTrade(gameState, currencyId, itemId, quantity, unitPrice, false);
197 if (!validated.ok()) return eve::Result<int>::failure(validated.status());
198 const double total = std::move(validated).takeValue();
199 auto prepared = inventory::InventorySystem::prepareRemove(&bag, itemId, quantity);
200 if (!prepared.ok()) return eve::Result<int>::failure(prepared.status());
201 auto before = gameState.snapshotJson();
202 if (!before.ok()) return eve::Result<int>::failure(before.status());
203 std::string snapshot = std::move(before).takeValue();
204
205 gameState.addVariable(currencyId, total);
206 auto committed = inventory::InventorySystem::commitRemove(std::move(prepared).takeValue());
207 if (!committed.ok()) return rollbackFailure(gameState, snapshot, committed.status(), itemId);
208 return committed;
209}
210
211} // namespace eve::rpg
LogicalId itemId
int root
Definition AnimSmr.cpp:119
bool committed
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
全局游戏状态:开关(bool)、变量(数字)、独立变量(按作用域)。
std::string message
DiagnosticCode code
Poco::JSON::Object::Ptr result
Snapshot snapshot
const char * description
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
bool found
Strict, atomically replaceable RPG shop content.
Atomic RPG currency and inventory purchase/sale orchestration.
int count
Json object
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.
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
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
格子型物品容器(脚本可直接操作)。
Definition Bag.h:22
static eve::Result< int > commitRemove(PreparedInventoryRemove prepared)
Commit a prepared removal and publish its event after the no-fail slot swap.
static eve::Result< int > commitAddBatch(PreparedInventoryAdd prepared)
Commit one prepared addition and then publish its change events.
static eve::Result< PreparedInventoryAdd > prepareAddBatch(Bag *bag, const std::vector< InventoryItemGrant > &grants)
Validate a multi-item addition against a private candidate Bag.
static eve::Result< PreparedInventoryRemove > prepareRemove(Bag *bag, const std::string &itemId, int quantity)
Prepare removal of one exact item quantity without mutation or events.
static const ItemDefinition * find(const std::string &id)
Finds find.
Definition Item.cpp:53
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
一份游戏状态(开关/变量/独立变量)。
Definition GameState.h:26
void addVariable(const std::string &name, double delta)
Adds variable.
Definition GameState.cpp:70
eve::Result< std::string > snapshotJson() const
Serialize this state as the canonical versioned RPG game-state JSON document.
static eve::Result< int > replaceFromJsonStrict(const std::string &json)
Strictly validate and atomically replace the entire offer catalogue.
static const ShopOffer * find(const std::string &id)
Find an offer by stable offer id, or null when absent.
static const ShopOffer * at(int index)
Return an offer by deterministic source index, or null when out of range.
static void clear()
Remove all offers. Intended for teardown and isolated tests.
static int count()
Return the number of committed offers in deterministic source order.
static eve::Result< int > sell(GameState &gameState, inventory::Bag &bag, const std::string &currencyId, const std::string &itemId, int quantity, double unitPrice)
Atomically remove an item quantity and credit its sale proceeds.
static eve::Result< int > sellOffer(GameState &gameState, inventory::Bag &bag, const std::string &currencyId, const std::string &offerId, int quantity)
Sell a quantity using the authoritative price and item in ShopCatalogue.
static eve::Result< int > buyOffer(GameState &gameState, inventory::Bag &bag, const std::string &currencyId, const std::string &offerId, int quantity)
Buy a quantity using the authoritative price and item in ShopCatalogue.
static eve::Result< int > buy(GameState &gameState, inventory::Bag &bag, const std::string &currencyId, const std::string &itemId, int quantity, double unitPrice)
Atomically debit currency and add the purchased item quantity.
void keys(const Value &value, std::initializer_list< const char * > names)
RPG 模块的基础实体:把属性 / 状态 / 技能三张表挂到一个 ECS 实体上。
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
One immutable offer in the process-local shop catalogue.
std::string description
std::string displayName