@energy8platform/platform-core 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +482 -0
- package/bin/simulate.ts +139 -0
- package/dist/dev-bridge.cjs.js +237 -0
- package/dist/dev-bridge.cjs.js.map +1 -0
- package/dist/dev-bridge.d.ts +141 -0
- package/dist/dev-bridge.esm.js +235 -0
- package/dist/dev-bridge.esm.js.map +1 -0
- package/dist/index.cjs.js +569 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +439 -0
- package/dist/index.esm.js +560 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/loading.cjs.js +190 -0
- package/dist/loading.cjs.js.map +1 -0
- package/dist/loading.d.ts +86 -0
- package/dist/loading.esm.js +185 -0
- package/dist/loading.esm.js.map +1 -0
- package/dist/lua.cjs.js +1129 -0
- package/dist/lua.cjs.js.map +1 -0
- package/dist/lua.d.ts +319 -0
- package/dist/lua.esm.js +1119 -0
- package/dist/lua.esm.js.map +1 -0
- package/dist/simulation.cjs.js +374 -0
- package/dist/simulation.cjs.js.map +1 -0
- package/dist/simulation.d.ts +190 -0
- package/dist/simulation.esm.js +368 -0
- package/dist/simulation.esm.js.map +1 -0
- package/dist/vite.cjs.js +179 -0
- package/dist/vite.cjs.js.map +1 -0
- package/dist/vite.d.ts +13 -0
- package/dist/vite.esm.js +176 -0
- package/dist/vite.esm.js.map +1 -0
- package/package.json +100 -0
- package/scripts/install-simulate.mjs +101 -0
- package/src/EventEmitter.ts +55 -0
- package/src/PlatformSession.ts +156 -0
- package/src/dev-bridge/DevBridge.ts +305 -0
- package/src/dev-bridge/index.ts +2 -0
- package/src/index.ts +98 -0
- package/src/loading/CSSPreloader.ts +129 -0
- package/src/loading/index.ts +3 -0
- package/src/loading/logo.ts +95 -0
- package/src/lua/ActionRouter.ts +132 -0
- package/src/lua/LuaEngine.ts +412 -0
- package/src/lua/LuaEngineAPI.ts +314 -0
- package/src/lua/PersistentState.ts +80 -0
- package/src/lua/SessionManager.ts +227 -0
- package/src/lua/SimulationRunner.ts +192 -0
- package/src/lua/fengari.d.ts +10 -0
- package/src/lua/index.ts +28 -0
- package/src/lua/types.ts +149 -0
- package/src/simulation/NativeSimulationRunner.ts +367 -0
- package/src/simulation/ParallelSimulationRunner.ts +156 -0
- package/src/simulation/SimulationWorker.ts +44 -0
- package/src/simulation/index.ts +21 -0
- package/src/types.ts +85 -0
- package/src/vite/index.ts +196 -0
package/dist/lua.esm.js
ADDED
|
@@ -0,0 +1,1119 @@
|
|
|
1
|
+
import fengari from 'fengari';
|
|
2
|
+
|
|
3
|
+
const { lua: lua$1, lauxlib: lauxlib$1 } = fengari;
|
|
4
|
+
const { to_luastring: to_luastring$1, to_jsstring: to_jsstring$1 } = fengari;
|
|
5
|
+
/** Cache for to_luastring() results — avoids re-encoding the same keys every iteration */
|
|
6
|
+
const luaStringCache = new Map();
|
|
7
|
+
function cachedToLuastring(s) {
|
|
8
|
+
let cached = luaStringCache.get(s);
|
|
9
|
+
if (!cached) {
|
|
10
|
+
cached = to_luastring$1(s);
|
|
11
|
+
luaStringCache.set(s, cached);
|
|
12
|
+
}
|
|
13
|
+
return cached;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Seeded xoshiro128** PRNG for deterministic simulation/replay.
|
|
17
|
+
* Period: 2^128 - 1
|
|
18
|
+
*/
|
|
19
|
+
function createSeededRng(seed) {
|
|
20
|
+
let s0 = (seed >>> 0) | 1;
|
|
21
|
+
let s1 = (seed * 1103515245 + 12345) >>> 0;
|
|
22
|
+
let s2 = (seed * 6364136223846793005 + 1442695040888963407) >>> 0;
|
|
23
|
+
let s3 = (seed * 1442695040888963407 + 6364136223846793005) >>> 0;
|
|
24
|
+
return () => {
|
|
25
|
+
const result = (((s1 * 5) << 7) * 9) >>> 0;
|
|
26
|
+
const t = s1 << 9;
|
|
27
|
+
s2 ^= s0;
|
|
28
|
+
s3 ^= s1;
|
|
29
|
+
s1 ^= s2;
|
|
30
|
+
s0 ^= s3;
|
|
31
|
+
s2 ^= t;
|
|
32
|
+
s3 = ((s3 << 11) | (s3 >>> 21)) >>> 0;
|
|
33
|
+
return result / 4294967296;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Implements and registers all platform `engine.*` functions into a Lua state.
|
|
38
|
+
*/
|
|
39
|
+
class LuaEngineAPI {
|
|
40
|
+
rng;
|
|
41
|
+
logger;
|
|
42
|
+
gameDefinition;
|
|
43
|
+
constructor(gameDefinition, rng, logger) {
|
|
44
|
+
this.gameDefinition = gameDefinition;
|
|
45
|
+
this.rng = rng ?? Math.random;
|
|
46
|
+
this.logger = logger ?? ((level, msg) => {
|
|
47
|
+
const fn = level === 'error' ? console.error
|
|
48
|
+
: level === 'warn' ? console.warn
|
|
49
|
+
: level === 'debug' ? console.debug
|
|
50
|
+
: console.log;
|
|
51
|
+
fn(`[Lua:${level}] ${msg}`);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/** Register `engine` global table on the Lua state */
|
|
55
|
+
register(L) {
|
|
56
|
+
// Create the `engine` table
|
|
57
|
+
lua$1.lua_newtable(L);
|
|
58
|
+
this.registerFunction(L, 'random', (LS) => {
|
|
59
|
+
const min = lauxlib$1.luaL_checkinteger(LS, 1);
|
|
60
|
+
const max = lauxlib$1.luaL_checkinteger(LS, 2);
|
|
61
|
+
const result = this.random(Number(min), Number(max));
|
|
62
|
+
lua$1.lua_pushinteger(LS, result);
|
|
63
|
+
return 1;
|
|
64
|
+
});
|
|
65
|
+
this.registerFunction(L, 'random_float', (LS) => {
|
|
66
|
+
lua$1.lua_pushnumber(LS, this.randomFloat());
|
|
67
|
+
return 1;
|
|
68
|
+
});
|
|
69
|
+
this.registerFunction(L, 'random_weighted', (LS) => {
|
|
70
|
+
lauxlib$1.luaL_checktype(LS, 1, lua$1.LUA_TTABLE);
|
|
71
|
+
const weights = [];
|
|
72
|
+
const len = lua$1.lua_rawlen(LS, 1);
|
|
73
|
+
for (let i = 1; i <= len; i++) {
|
|
74
|
+
lua$1.lua_rawgeti(LS, 1, i);
|
|
75
|
+
weights.push(lua$1.lua_tonumber(LS, -1));
|
|
76
|
+
lua$1.lua_pop(LS, 1);
|
|
77
|
+
}
|
|
78
|
+
const result = this.randomWeighted(weights);
|
|
79
|
+
lua$1.lua_pushinteger(LS, result);
|
|
80
|
+
return 1;
|
|
81
|
+
});
|
|
82
|
+
this.registerFunction(L, 'shuffle', (LS) => {
|
|
83
|
+
lauxlib$1.luaL_checktype(LS, 1, lua$1.LUA_TTABLE);
|
|
84
|
+
const arr = [];
|
|
85
|
+
const len = lua$1.lua_rawlen(LS, 1);
|
|
86
|
+
for (let i = 1; i <= len; i++) {
|
|
87
|
+
lua$1.lua_rawgeti(LS, 1, i);
|
|
88
|
+
arr.push(luaToJS(LS, -1));
|
|
89
|
+
lua$1.lua_pop(LS, 1);
|
|
90
|
+
}
|
|
91
|
+
const shuffled = this.shuffle(arr);
|
|
92
|
+
pushJSArray(LS, shuffled);
|
|
93
|
+
return 1;
|
|
94
|
+
});
|
|
95
|
+
this.registerFunction(L, 'log', (LS) => {
|
|
96
|
+
const level = to_jsstring$1(lauxlib$1.luaL_checkstring(LS, 1));
|
|
97
|
+
const msg = to_jsstring$1(lauxlib$1.luaL_checkstring(LS, 2));
|
|
98
|
+
this.logger(level, msg);
|
|
99
|
+
return 0;
|
|
100
|
+
});
|
|
101
|
+
this.registerFunction(L, 'get_config', (LS) => {
|
|
102
|
+
const config = this.getConfig();
|
|
103
|
+
pushJSObject(LS, config);
|
|
104
|
+
return 1;
|
|
105
|
+
});
|
|
106
|
+
// Set the table as global `engine`
|
|
107
|
+
lua$1.lua_setglobal(L, to_luastring$1('engine'));
|
|
108
|
+
}
|
|
109
|
+
// ─── engine.* implementations ─────────────────────────
|
|
110
|
+
random(min, max) {
|
|
111
|
+
return Math.floor(this.rng() * (max - min + 1)) + min;
|
|
112
|
+
}
|
|
113
|
+
randomFloat() {
|
|
114
|
+
return this.rng();
|
|
115
|
+
}
|
|
116
|
+
randomWeighted(weights) {
|
|
117
|
+
const totalWeight = weights.reduce((a, b) => a + b, 0);
|
|
118
|
+
let roll = this.rng() * totalWeight;
|
|
119
|
+
for (let i = 0; i < weights.length; i++) {
|
|
120
|
+
roll -= weights[i];
|
|
121
|
+
if (roll < 0)
|
|
122
|
+
return i + 1; // 1-based index
|
|
123
|
+
}
|
|
124
|
+
return weights.length; // fallback to last
|
|
125
|
+
}
|
|
126
|
+
shuffle(arr) {
|
|
127
|
+
const copy = [...arr];
|
|
128
|
+
for (let i = copy.length - 1; i > 0; i--) {
|
|
129
|
+
const j = Math.floor(this.rng() * (i + 1));
|
|
130
|
+
[copy[i], copy[j]] = [copy[j], copy[i]];
|
|
131
|
+
}
|
|
132
|
+
return copy;
|
|
133
|
+
}
|
|
134
|
+
getConfig() {
|
|
135
|
+
const def = this.gameDefinition;
|
|
136
|
+
let betLevels = [];
|
|
137
|
+
if (Array.isArray(def.bet_levels)) {
|
|
138
|
+
betLevels = def.bet_levels;
|
|
139
|
+
}
|
|
140
|
+
else if (def.bet_levels && 'levels' in def.bet_levels && def.bet_levels.levels) {
|
|
141
|
+
betLevels = def.bet_levels.levels;
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
id: def.id,
|
|
145
|
+
type: def.type,
|
|
146
|
+
bet_levels: betLevels,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
// ─── Helpers ──────────────────────────────────────────
|
|
150
|
+
registerFunction(L, name, fn) {
|
|
151
|
+
lua$1.lua_pushcfunction(L, fn);
|
|
152
|
+
lua$1.lua_setfield(L, -2, to_luastring$1(name));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// ─── Lua ↔ JS marshalling ───────────────────────────────
|
|
156
|
+
/** Read a Lua value at the given stack index and return its JS equivalent */
|
|
157
|
+
function luaToJS(L, idx) {
|
|
158
|
+
const type = lua$1.lua_type(L, idx);
|
|
159
|
+
switch (type) {
|
|
160
|
+
case lua$1.LUA_TNIL:
|
|
161
|
+
return null;
|
|
162
|
+
case lua$1.LUA_TBOOLEAN:
|
|
163
|
+
return lua$1.lua_toboolean(L, idx);
|
|
164
|
+
case lua$1.LUA_TNUMBER:
|
|
165
|
+
if (lua$1.lua_isinteger(L, idx)) {
|
|
166
|
+
return Number(lua$1.lua_tointeger(L, idx));
|
|
167
|
+
}
|
|
168
|
+
return lua$1.lua_tonumber(L, idx);
|
|
169
|
+
case lua$1.LUA_TSTRING:
|
|
170
|
+
return to_jsstring$1(lua$1.lua_tostring(L, idx));
|
|
171
|
+
case lua$1.LUA_TTABLE:
|
|
172
|
+
return luaTableToJS(L, idx);
|
|
173
|
+
default:
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** Convert a Lua table to a JS object or array */
|
|
178
|
+
function luaTableToJS(L, idx) {
|
|
179
|
+
// Normalize index to absolute
|
|
180
|
+
if (idx < 0)
|
|
181
|
+
idx = lua$1.lua_gettop(L) + idx + 1;
|
|
182
|
+
// Check if it's an array (sequential integer keys starting at 1)
|
|
183
|
+
const len = lua$1.lua_rawlen(L, idx);
|
|
184
|
+
if (len > 0) {
|
|
185
|
+
// Verify it's a pure array by checking key 1 exists
|
|
186
|
+
lua$1.lua_rawgeti(L, idx, 1);
|
|
187
|
+
const hasFirst = lua$1.lua_type(L, -1) !== lua$1.LUA_TNIL;
|
|
188
|
+
lua$1.lua_pop(L, 1);
|
|
189
|
+
if (hasFirst) {
|
|
190
|
+
// Check if there are also string keys (mixed table)
|
|
191
|
+
let hasStringKeys = false;
|
|
192
|
+
lua$1.lua_pushnil(L);
|
|
193
|
+
while (lua$1.lua_next(L, idx) !== 0) {
|
|
194
|
+
lua$1.lua_pop(L, 1); // pop value
|
|
195
|
+
if (lua$1.lua_type(L, -1) === lua$1.LUA_TSTRING) {
|
|
196
|
+
hasStringKeys = true;
|
|
197
|
+
lua$1.lua_pop(L, 1); // pop key
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (!hasStringKeys) {
|
|
202
|
+
// Pure array
|
|
203
|
+
const arr = [];
|
|
204
|
+
for (let i = 1; i <= len; i++) {
|
|
205
|
+
lua$1.lua_rawgeti(L, idx, i);
|
|
206
|
+
arr.push(luaToJS(L, -1));
|
|
207
|
+
lua$1.lua_pop(L, 1);
|
|
208
|
+
}
|
|
209
|
+
return arr;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
// Object (or mixed table)
|
|
214
|
+
const obj = {};
|
|
215
|
+
lua$1.lua_pushnil(L);
|
|
216
|
+
while (lua$1.lua_next(L, idx) !== 0) {
|
|
217
|
+
const keyType = lua$1.lua_type(L, -2);
|
|
218
|
+
let key;
|
|
219
|
+
if (keyType === lua$1.LUA_TSTRING) {
|
|
220
|
+
key = to_jsstring$1(lua$1.lua_tostring(L, -2));
|
|
221
|
+
}
|
|
222
|
+
else if (keyType === lua$1.LUA_TNUMBER) {
|
|
223
|
+
key = String(lua$1.lua_tonumber(L, -2));
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
lua$1.lua_pop(L, 1);
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
obj[key] = luaToJS(L, -1);
|
|
230
|
+
lua$1.lua_pop(L, 1);
|
|
231
|
+
}
|
|
232
|
+
return obj;
|
|
233
|
+
}
|
|
234
|
+
/** Push a JS value onto the Lua stack */
|
|
235
|
+
function pushJSValue(L, value) {
|
|
236
|
+
if (value === null || value === undefined) {
|
|
237
|
+
lua$1.lua_pushnil(L);
|
|
238
|
+
}
|
|
239
|
+
else if (typeof value === 'boolean') {
|
|
240
|
+
lua$1.lua_pushboolean(L, value ? 1 : 0);
|
|
241
|
+
}
|
|
242
|
+
else if (typeof value === 'number') {
|
|
243
|
+
if (Number.isInteger(value)) {
|
|
244
|
+
lua$1.lua_pushinteger(L, value);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
lua$1.lua_pushnumber(L, value);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
else if (typeof value === 'string') {
|
|
251
|
+
lua$1.lua_pushstring(L, cachedToLuastring(value));
|
|
252
|
+
}
|
|
253
|
+
else if (Array.isArray(value)) {
|
|
254
|
+
pushJSArray(L, value);
|
|
255
|
+
}
|
|
256
|
+
else if (typeof value === 'object') {
|
|
257
|
+
pushJSObject(L, value);
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
lua$1.lua_pushnil(L);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** Push a JS array as a Lua table (1-based) */
|
|
264
|
+
function pushJSArray(L, arr) {
|
|
265
|
+
lua$1.lua_createtable(L, arr.length, 0);
|
|
266
|
+
for (let i = 0; i < arr.length; i++) {
|
|
267
|
+
pushJSValue(L, arr[i]);
|
|
268
|
+
lua$1.lua_rawseti(L, -2, i + 1);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/** Push a JS object as a Lua table */
|
|
272
|
+
function pushJSObject(L, obj) {
|
|
273
|
+
const keys = Object.keys(obj);
|
|
274
|
+
lua$1.lua_createtable(L, 0, keys.length);
|
|
275
|
+
for (const key of keys) {
|
|
276
|
+
pushJSValue(L, obj[key]);
|
|
277
|
+
lua$1.lua_setfield(L, -2, cachedToLuastring(key));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Replicates the platform's action dispatch and transition evaluation.
|
|
283
|
+
* Routes play requests to the correct action, evaluates transition conditions
|
|
284
|
+
* against current variables to determine next actions and session operations.
|
|
285
|
+
*/
|
|
286
|
+
class ActionRouter {
|
|
287
|
+
actions;
|
|
288
|
+
constructor(gameDefinition) {
|
|
289
|
+
this.actions = gameDefinition.actions;
|
|
290
|
+
}
|
|
291
|
+
/** Look up action by name and validate prerequisites */
|
|
292
|
+
resolveAction(actionName, hasSession) {
|
|
293
|
+
const action = this.actions[actionName];
|
|
294
|
+
if (!action) {
|
|
295
|
+
throw new Error(`Unknown action: "${actionName}". Available: ${Object.keys(this.actions).join(', ')}`);
|
|
296
|
+
}
|
|
297
|
+
if (action.requires_session && !hasSession) {
|
|
298
|
+
throw new Error(`Action "${actionName}" requires an active session`);
|
|
299
|
+
}
|
|
300
|
+
return action;
|
|
301
|
+
}
|
|
302
|
+
/** Evaluate transitions in order, return the first matching rule */
|
|
303
|
+
evaluateTransitions(action, variables) {
|
|
304
|
+
for (const rule of action.transitions) {
|
|
305
|
+
if (evaluateCondition(rule.condition, variables)) {
|
|
306
|
+
return { rule, nextActions: rule.next_actions };
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
throw new Error(`No matching transition for action with stage "${action.stage}". ` +
|
|
310
|
+
`Variables: ${JSON.stringify(variables)}`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
// ─── Condition Evaluator ────────────────────────────────
|
|
314
|
+
/**
|
|
315
|
+
* Evaluates a transition condition expression against variables.
|
|
316
|
+
*
|
|
317
|
+
* Supports:
|
|
318
|
+
* - "always" → true
|
|
319
|
+
* - Simple comparisons: "var > 0", "var == 1", "var >= 10", "var != 0", "var < 5", "var <= 3"
|
|
320
|
+
* - Logical connectives: "expr && expr", "expr || expr"
|
|
321
|
+
*
|
|
322
|
+
* This covers all patterns used by the platform's govaluate conditions.
|
|
323
|
+
*/
|
|
324
|
+
function evaluateCondition(condition, variables) {
|
|
325
|
+
const trimmed = condition.trim();
|
|
326
|
+
if (trimmed === 'always')
|
|
327
|
+
return true;
|
|
328
|
+
// Handle || (OR) — lowest precedence
|
|
329
|
+
if (trimmed.includes('||')) {
|
|
330
|
+
const parts = splitOnOperator(trimmed, '||');
|
|
331
|
+
return parts.some(part => evaluateCondition(part, variables));
|
|
332
|
+
}
|
|
333
|
+
// Handle && (AND)
|
|
334
|
+
if (trimmed.includes('&&')) {
|
|
335
|
+
const parts = splitOnOperator(trimmed, '&&');
|
|
336
|
+
return parts.every(part => evaluateCondition(part, variables));
|
|
337
|
+
}
|
|
338
|
+
// Single comparison: "variable op value"
|
|
339
|
+
return evaluateComparison(trimmed, variables);
|
|
340
|
+
}
|
|
341
|
+
function splitOnOperator(expr, operator) {
|
|
342
|
+
const parts = [];
|
|
343
|
+
let depth = 0;
|
|
344
|
+
let current = '';
|
|
345
|
+
for (let i = 0; i < expr.length; i++) {
|
|
346
|
+
if (expr[i] === '(')
|
|
347
|
+
depth++;
|
|
348
|
+
else if (expr[i] === ')')
|
|
349
|
+
depth--;
|
|
350
|
+
if (depth === 0 && expr.substring(i, i + operator.length) === operator) {
|
|
351
|
+
parts.push(current);
|
|
352
|
+
current = '';
|
|
353
|
+
i += operator.length - 1;
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
current += expr[i];
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
parts.push(current);
|
|
360
|
+
return parts;
|
|
361
|
+
}
|
|
362
|
+
function evaluateComparison(expr, variables) {
|
|
363
|
+
// Match: variable_name operator value
|
|
364
|
+
const match = expr.trim().match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*(>=|<=|!=|==|>|<)\s*(-?\d+(?:\.\d+)?)\s*$/);
|
|
365
|
+
if (!match) {
|
|
366
|
+
throw new Error(`Cannot parse condition: "${expr}"`);
|
|
367
|
+
}
|
|
368
|
+
const [, varName, op, valueStr] = match;
|
|
369
|
+
const left = variables[varName] ?? 0;
|
|
370
|
+
const right = parseFloat(valueStr);
|
|
371
|
+
switch (op) {
|
|
372
|
+
case '>': return left > right;
|
|
373
|
+
case '>=': return left >= right;
|
|
374
|
+
case '<': return left < right;
|
|
375
|
+
case '<=': return left <= right;
|
|
376
|
+
case '==': return left === right;
|
|
377
|
+
case '!=': return left !== right;
|
|
378
|
+
default: return false;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const MAX_SESSION_SPINS = 200;
|
|
383
|
+
/**
|
|
384
|
+
* Manages session lifecycle matching the platform server behavior:
|
|
385
|
+
* - createSession: initial spin counted (spinsPlayed=1, totalWin=spinWin)
|
|
386
|
+
* - updateSession: accumulates win, decrements spins, checks max win cap on session level
|
|
387
|
+
* - completeSession: returns cumulative totalWin, cleans up session vars
|
|
388
|
+
* - Safety cap: 200 spins max per session
|
|
389
|
+
*/
|
|
390
|
+
class SessionManager {
|
|
391
|
+
session = null;
|
|
392
|
+
get isActive() {
|
|
393
|
+
return this.session !== null && !this.session.completed;
|
|
394
|
+
}
|
|
395
|
+
get current() {
|
|
396
|
+
if (!this.session)
|
|
397
|
+
return null;
|
|
398
|
+
return this.toSessionData();
|
|
399
|
+
}
|
|
400
|
+
get sessionTotalWin() {
|
|
401
|
+
return this.session?.totalWin ?? 0;
|
|
402
|
+
}
|
|
403
|
+
/** Get the fixed bet amount from the session (server uses session bet, not request bet) */
|
|
404
|
+
get sessionBet() {
|
|
405
|
+
return this.session?.bet;
|
|
406
|
+
}
|
|
407
|
+
/** Get spinsVarName to restore free_spins_remaining into variables */
|
|
408
|
+
get spinsVarName() {
|
|
409
|
+
return this.session?.spinsVarName;
|
|
410
|
+
}
|
|
411
|
+
get spinsRemaining() {
|
|
412
|
+
return this.session?.spinsRemaining ?? 0;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Create a new session from a transition rule.
|
|
416
|
+
* Server behavior: initial spin is already counted (spinsPlayed=1, totalWin includes spinWin).
|
|
417
|
+
*/
|
|
418
|
+
createSession(rule, variables, bet, spinWin, maxWinCap) {
|
|
419
|
+
let spinsRemaining = -1;
|
|
420
|
+
let spinsVarName;
|
|
421
|
+
if (rule.session_config?.total_spins_var) {
|
|
422
|
+
spinsVarName = rule.session_config.total_spins_var;
|
|
423
|
+
spinsRemaining = variables[spinsVarName] ?? -1;
|
|
424
|
+
}
|
|
425
|
+
const persistentVarNames = rule.session_config?.persistent_vars ?? [];
|
|
426
|
+
const persistentVars = {};
|
|
427
|
+
for (const varName of persistentVarNames) {
|
|
428
|
+
persistentVars[varName] = variables[varName] ?? 0;
|
|
429
|
+
}
|
|
430
|
+
this.session = {
|
|
431
|
+
spinsRemaining,
|
|
432
|
+
spinsPlayed: 1, // initial spin counts
|
|
433
|
+
totalWin: spinWin, // initial spin win included
|
|
434
|
+
completed: false,
|
|
435
|
+
maxWinReached: false,
|
|
436
|
+
bet,
|
|
437
|
+
maxWinCap,
|
|
438
|
+
spinsVarName,
|
|
439
|
+
persistentVarNames,
|
|
440
|
+
persistentVars,
|
|
441
|
+
persistentData: {},
|
|
442
|
+
};
|
|
443
|
+
return this.toSessionData();
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Update session after a bonus spin.
|
|
447
|
+
* Server behavior: accumulate win, decrement spins, check retrigger, check max win cap,
|
|
448
|
+
* safety cap at 200 spins.
|
|
449
|
+
*/
|
|
450
|
+
updateSession(rule, variables, spinWin) {
|
|
451
|
+
if (!this.session)
|
|
452
|
+
throw new Error('No active session');
|
|
453
|
+
// Accumulate win and count spin
|
|
454
|
+
this.session.totalWin += spinWin;
|
|
455
|
+
this.session.spinsPlayed++;
|
|
456
|
+
// Decrement spins (only for non-unlimited sessions)
|
|
457
|
+
if (this.session.spinsRemaining > 0) {
|
|
458
|
+
this.session.spinsRemaining--;
|
|
459
|
+
}
|
|
460
|
+
// Handle retrigger (add_spins_var)
|
|
461
|
+
if (rule.add_spins_var) {
|
|
462
|
+
const extraSpins = variables[rule.add_spins_var] ?? 0;
|
|
463
|
+
if (extraSpins > 0 && this.session.spinsRemaining >= 0) {
|
|
464
|
+
this.session.spinsRemaining += extraSpins;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
// Safety cap: server limits sessions to 200 spins
|
|
468
|
+
if (this.session.spinsPlayed >= MAX_SESSION_SPINS) {
|
|
469
|
+
this.session.spinsRemaining = 0;
|
|
470
|
+
}
|
|
471
|
+
// Update session persistent vars from current variables
|
|
472
|
+
for (const varName of this.session.persistentVarNames) {
|
|
473
|
+
if (varName in variables) {
|
|
474
|
+
this.session.persistentVars[varName] = variables[varName];
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// Check max win cap (on session level, not per spin)
|
|
478
|
+
if (this.session.maxWinCap !== undefined && this.session.totalWin >= this.session.maxWinCap) {
|
|
479
|
+
this.session.totalWin = this.session.maxWinCap;
|
|
480
|
+
this.session.spinsRemaining = 0;
|
|
481
|
+
this.session.maxWinReached = true;
|
|
482
|
+
}
|
|
483
|
+
// Auto-complete if spins exhausted or explicit complete
|
|
484
|
+
if (this.session.spinsRemaining === 0 || rule.complete_session) {
|
|
485
|
+
this.session.completed = true;
|
|
486
|
+
}
|
|
487
|
+
return this.toSessionData();
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Complete the session explicitly.
|
|
491
|
+
* Returns cumulative totalWin and list of session-scoped var names to clean up.
|
|
492
|
+
*/
|
|
493
|
+
completeSession() {
|
|
494
|
+
if (!this.session)
|
|
495
|
+
throw new Error('No active session to complete');
|
|
496
|
+
this.session.completed = true;
|
|
497
|
+
const totalWin = this.session.totalWin;
|
|
498
|
+
const session = this.toSessionData();
|
|
499
|
+
const sessionVarNames = [...this.session.persistentVarNames];
|
|
500
|
+
this.session = null;
|
|
501
|
+
return { totalWin, session, sessionVarNames };
|
|
502
|
+
}
|
|
503
|
+
/** Mark max win reached — stops the session */
|
|
504
|
+
markMaxWinReached() {
|
|
505
|
+
if (this.session) {
|
|
506
|
+
this.session.maxWinReached = true;
|
|
507
|
+
this.session.completed = true;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/** Store _persist_* data extracted from Lua result */
|
|
511
|
+
storePersistData(data) {
|
|
512
|
+
if (!this.session)
|
|
513
|
+
return;
|
|
514
|
+
for (const key of Object.keys(data)) {
|
|
515
|
+
if (key.startsWith('_persist_')) {
|
|
516
|
+
const cleanKey = key.slice('_persist_'.length);
|
|
517
|
+
this.session.persistentData[cleanKey] = data[key];
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
/** Get persistent params to inject into next execute() call */
|
|
522
|
+
getPersistentParams() {
|
|
523
|
+
if (!this.session)
|
|
524
|
+
return {};
|
|
525
|
+
const params = {};
|
|
526
|
+
// Session persistent vars (float64) → state.variables
|
|
527
|
+
for (const [key, value] of Object.entries(this.session.persistentVars)) {
|
|
528
|
+
params[key] = value;
|
|
529
|
+
}
|
|
530
|
+
// _persist_ complex data → _ps_* in state.params
|
|
531
|
+
for (const [key, value] of Object.entries(this.session.persistentData)) {
|
|
532
|
+
params[`_ps_${key}`] = value;
|
|
533
|
+
}
|
|
534
|
+
return params;
|
|
535
|
+
}
|
|
536
|
+
/** Reset all session state */
|
|
537
|
+
reset() {
|
|
538
|
+
this.session = null;
|
|
539
|
+
}
|
|
540
|
+
toSessionData() {
|
|
541
|
+
if (!this.session)
|
|
542
|
+
throw new Error('No session');
|
|
543
|
+
return {
|
|
544
|
+
spinsRemaining: this.session.spinsRemaining,
|
|
545
|
+
spinsPlayed: this.session.spinsPlayed,
|
|
546
|
+
totalWin: Math.round(this.session.totalWin * 100) / 100,
|
|
547
|
+
completed: this.session.completed,
|
|
548
|
+
maxWinReached: this.session.maxWinReached,
|
|
549
|
+
betAmount: this.session.bet,
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Manages cross-spin persistent state — variables that survive between base game spins.
|
|
556
|
+
* Separate from session-scoped persistence (handled by SessionManager).
|
|
557
|
+
*
|
|
558
|
+
* Handles two mechanisms:
|
|
559
|
+
* 1. Numeric vars declared in `persistent_state.vars` — stored in state.variables
|
|
560
|
+
* 2. Complex data with `_persist_game_*` prefix — stored separately, injected as `_ps_*`
|
|
561
|
+
*/
|
|
562
|
+
class PersistentState {
|
|
563
|
+
config;
|
|
564
|
+
vars = {};
|
|
565
|
+
gameData = {};
|
|
566
|
+
constructor(config) {
|
|
567
|
+
this.config = config;
|
|
568
|
+
}
|
|
569
|
+
/** Load persistent vars into variables map before execute() */
|
|
570
|
+
loadIntoVariables(variables) {
|
|
571
|
+
if (!this.config)
|
|
572
|
+
return;
|
|
573
|
+
for (const varName of this.config.vars) {
|
|
574
|
+
if (varName in this.vars) {
|
|
575
|
+
variables[varName] = this.vars[varName];
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
/** Save persistent vars from variables map after execute() */
|
|
580
|
+
saveFromVariables(variables) {
|
|
581
|
+
if (!this.config)
|
|
582
|
+
return;
|
|
583
|
+
for (const varName of this.config.vars) {
|
|
584
|
+
if (varName in variables) {
|
|
585
|
+
this.vars[varName] = variables[varName];
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
/** Extract _persist_game_* keys from Lua return data, store them */
|
|
590
|
+
storeGameData(data) {
|
|
591
|
+
for (const key of Object.keys(data)) {
|
|
592
|
+
if (key.startsWith('_persist_game_')) {
|
|
593
|
+
const cleanKey = key.slice('_persist_game_'.length);
|
|
594
|
+
this.gameData[cleanKey] = data[key];
|
|
595
|
+
delete data[key]; // remove from client data
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
/** Get _ps_* params for next execute() call */
|
|
600
|
+
getGameDataParams() {
|
|
601
|
+
const params = {};
|
|
602
|
+
for (const [key, value] of Object.entries(this.gameData)) {
|
|
603
|
+
params[`_ps_${key}`] = value;
|
|
604
|
+
}
|
|
605
|
+
return params;
|
|
606
|
+
}
|
|
607
|
+
/** Get exposed vars for client data.persistent_state */
|
|
608
|
+
getExposedVars() {
|
|
609
|
+
if (!this.config?.exposed_vars?.length)
|
|
610
|
+
return undefined;
|
|
611
|
+
const exposed = {};
|
|
612
|
+
for (const varName of this.config.exposed_vars) {
|
|
613
|
+
if (varName in this.vars) {
|
|
614
|
+
exposed[varName] = this.vars[varName];
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return exposed;
|
|
618
|
+
}
|
|
619
|
+
/** Reset all state */
|
|
620
|
+
reset() {
|
|
621
|
+
this.vars = {};
|
|
622
|
+
this.gameData = {};
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const { lua, lauxlib, lualib } = fengari;
|
|
627
|
+
const { to_luastring, to_jsstring } = fengari;
|
|
628
|
+
/** Default engine variables matching the server's NewGameState() */
|
|
629
|
+
const DEFAULT_VARIABLES = {
|
|
630
|
+
multiplier: 1,
|
|
631
|
+
total_multiplier: 1,
|
|
632
|
+
global_multiplier: 1,
|
|
633
|
+
last_win_amount: 0,
|
|
634
|
+
free_spins_awarded: 0,
|
|
635
|
+
};
|
|
636
|
+
/**
|
|
637
|
+
* Runs Lua game scripts locally, replicating the platform's server-side execution.
|
|
638
|
+
*
|
|
639
|
+
* Implements the full lifecycle matching `casino_platform/internal/usecase/game_usecase.go`:
|
|
640
|
+
* action routing → state assembly → Lua execute() → result extraction →
|
|
641
|
+
* transition evaluation → session management.
|
|
642
|
+
*/
|
|
643
|
+
class LuaEngine {
|
|
644
|
+
L;
|
|
645
|
+
api;
|
|
646
|
+
actionRouter;
|
|
647
|
+
sessionManager;
|
|
648
|
+
persistentState;
|
|
649
|
+
gameDefinition;
|
|
650
|
+
variables = {};
|
|
651
|
+
simulationMode;
|
|
652
|
+
/** Reusable state objects to avoid per-iteration allocation */
|
|
653
|
+
_stateVars = {};
|
|
654
|
+
_stateParams = {};
|
|
655
|
+
constructor(config) {
|
|
656
|
+
this.gameDefinition = config.gameDefinition;
|
|
657
|
+
this.simulationMode = config.simulationMode ?? false;
|
|
658
|
+
const rng = config.seed !== undefined
|
|
659
|
+
? createSeededRng(config.seed)
|
|
660
|
+
: undefined;
|
|
661
|
+
this.api = new LuaEngineAPI(config.gameDefinition, rng, config.logger);
|
|
662
|
+
this.actionRouter = new ActionRouter(config.gameDefinition);
|
|
663
|
+
this.sessionManager = new SessionManager();
|
|
664
|
+
this.persistentState = new PersistentState(config.gameDefinition.persistent_state);
|
|
665
|
+
this.L = lauxlib.luaL_newstate();
|
|
666
|
+
lualib.luaL_openlibs(this.L);
|
|
667
|
+
// Polyfill Lua 5.1/5.2 functions removed in 5.3
|
|
668
|
+
lauxlib.luaL_dostring(this.L, to_luastring(`
|
|
669
|
+
math.pow = function(a, b) return a ^ b end
|
|
670
|
+
math.atan2 = math.atan2 or function(y, x) return math.atan(y, x) end
|
|
671
|
+
math.log10 = math.log10 or function(x) return math.log(x, 10) end
|
|
672
|
+
math.cosh = math.cosh or function(x) return (math.exp(x) + math.exp(-x)) / 2 end
|
|
673
|
+
math.sinh = math.sinh or function(x) return (math.exp(x) - math.exp(-x)) / 2 end
|
|
674
|
+
math.tanh = math.tanh or function(x) return math.sinh(x) / math.cosh(x) end
|
|
675
|
+
math.frexp = math.frexp or function(x)
|
|
676
|
+
if x == 0 then return 0, 0 end
|
|
677
|
+
local e = math.floor(math.log(math.abs(x), 2)) + 1
|
|
678
|
+
return x / (2 ^ e), e
|
|
679
|
+
end
|
|
680
|
+
math.ldexp = math.ldexp or function(m, e) return m * (2 ^ e) end
|
|
681
|
+
unpack = unpack or table.unpack
|
|
682
|
+
loadstring = loadstring or load
|
|
683
|
+
table.getn = table.getn or function(t) return #t end
|
|
684
|
+
`));
|
|
685
|
+
this.api.register(this.L);
|
|
686
|
+
this.loadScript(config.script);
|
|
687
|
+
}
|
|
688
|
+
get session() {
|
|
689
|
+
return this.sessionManager.current;
|
|
690
|
+
}
|
|
691
|
+
get persistentVars() {
|
|
692
|
+
return { ...this.variables };
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Execute a play action — replicates server's Play() function.
|
|
696
|
+
*/
|
|
697
|
+
execute(params) {
|
|
698
|
+
const { action: actionName, params: clientParams } = params;
|
|
699
|
+
// 1. Resolve action
|
|
700
|
+
const action = this.actionRouter.resolveAction(actionName, this.sessionManager.isActive);
|
|
701
|
+
// 2. Determine bet — server uses session bet for session actions
|
|
702
|
+
let bet = params.bet;
|
|
703
|
+
if (this.sessionManager.isActive && this.sessionManager.sessionBet !== undefined) {
|
|
704
|
+
bet = this.sessionManager.sessionBet;
|
|
705
|
+
}
|
|
706
|
+
// 3. Build state.variables (matching server's NewGameState + restore)
|
|
707
|
+
// Reuse pooled object to avoid per-iteration allocation
|
|
708
|
+
const stateVars = this._stateVars;
|
|
709
|
+
// Clear previous keys
|
|
710
|
+
for (const key in stateVars)
|
|
711
|
+
delete stateVars[key];
|
|
712
|
+
// Apply defaults, then engine vars, then bet
|
|
713
|
+
Object.assign(stateVars, DEFAULT_VARIABLES, this.variables);
|
|
714
|
+
stateVars.bet = bet;
|
|
715
|
+
// Load cross-spin persistent state
|
|
716
|
+
this.persistentState.loadIntoVariables(stateVars);
|
|
717
|
+
// Load session persistent vars + restore spinsRemaining
|
|
718
|
+
if (this.sessionManager.isActive) {
|
|
719
|
+
const sessionParams = this.sessionManager.getPersistentParams();
|
|
720
|
+
for (const [k, v] of Object.entries(sessionParams)) {
|
|
721
|
+
if (typeof v === 'number') {
|
|
722
|
+
stateVars[k] = v;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
// Restore spinsRemaining into the variable the script reads
|
|
726
|
+
if (this.sessionManager.spinsVarName) {
|
|
727
|
+
stateVars[this.sessionManager.spinsVarName] = this.sessionManager.spinsRemaining;
|
|
728
|
+
}
|
|
729
|
+
// Also set free_spins_remaining for convenience
|
|
730
|
+
stateVars.free_spins_remaining = this.sessionManager.spinsRemaining;
|
|
731
|
+
}
|
|
732
|
+
// 4. Build state.params (reuse pooled object)
|
|
733
|
+
const stateParams = this._stateParams;
|
|
734
|
+
for (const key in stateParams)
|
|
735
|
+
delete stateParams[key];
|
|
736
|
+
if (clientParams)
|
|
737
|
+
Object.assign(stateParams, clientParams);
|
|
738
|
+
stateParams._action = actionName;
|
|
739
|
+
// Inject session _ps_* persistent data
|
|
740
|
+
if (this.sessionManager.isActive) {
|
|
741
|
+
const sessionParams = this.sessionManager.getPersistentParams();
|
|
742
|
+
for (const [k, v] of Object.entries(sessionParams)) {
|
|
743
|
+
if (typeof v !== 'number') {
|
|
744
|
+
stateParams[k] = v;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
// Inject cross-spin _ps_* game data
|
|
749
|
+
const gameDataParams = this.persistentState.getGameDataParams();
|
|
750
|
+
Object.assign(stateParams, gameDataParams);
|
|
751
|
+
// Handle buy bonus
|
|
752
|
+
if (action.buy_bonus_mode && this.gameDefinition.buy_bonus) {
|
|
753
|
+
const mode = this.gameDefinition.buy_bonus.modes[action.buy_bonus_mode];
|
|
754
|
+
if (mode) {
|
|
755
|
+
stateParams.buy_bonus = true;
|
|
756
|
+
stateParams.buy_bonus_mode = action.buy_bonus_mode;
|
|
757
|
+
if (mode.scatter_distribution) {
|
|
758
|
+
stateParams.forced_scatter_count = this.pickFromDistribution(mode.scatter_distribution);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
// Handle ante bet
|
|
763
|
+
if (clientParams?.ante_bet && this.gameDefinition.ante_bet) {
|
|
764
|
+
stateParams.ante_bet = true;
|
|
765
|
+
}
|
|
766
|
+
// 5. Execute Lua (server: executor.Execute(stage, state))
|
|
767
|
+
const luaResult = this.callLuaExecute(action.stage, actionName, stateParams, stateVars);
|
|
768
|
+
// 6. Process result (server: ApplyLuaResult)
|
|
769
|
+
const totalWinMultiplier = typeof luaResult.total_win === 'number' ? luaResult.total_win : 0;
|
|
770
|
+
const resultVariables = (luaResult.variables ?? {});
|
|
771
|
+
const spinWin = Math.round(totalWinMultiplier * bet * 100) / 100;
|
|
772
|
+
// Merge ONLY Lua return variables into engine state (not the whole stateVars).
|
|
773
|
+
// On the server, state.Variables is a temporary object rebuilt each call.
|
|
774
|
+
// Only the Lua result's `variables` table persists between calls.
|
|
775
|
+
Object.assign(this.variables, resultVariables);
|
|
776
|
+
// Also update stateVars for transition evaluation below
|
|
777
|
+
Object.assign(stateVars, resultVariables);
|
|
778
|
+
// Build client data (everything except special keys)
|
|
779
|
+
const data = {};
|
|
780
|
+
for (const [key, value] of Object.entries(luaResult)) {
|
|
781
|
+
if (key !== 'total_win' && key !== 'variables') {
|
|
782
|
+
data[key] = value;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
// 7. Handle _persist_* and _persist_game_* keys
|
|
786
|
+
this.sessionManager.storePersistData(data);
|
|
787
|
+
this.persistentState.storeGameData(data);
|
|
788
|
+
// Save cross-spin persistent state (from stateVars which has Lua result merged)
|
|
789
|
+
this.persistentState.saveFromVariables(stateVars);
|
|
790
|
+
// Add exposed persistent vars to client data
|
|
791
|
+
const exposedVars = this.persistentState.getExposedVars();
|
|
792
|
+
if (exposedVars) {
|
|
793
|
+
data.persistent_state = exposedVars;
|
|
794
|
+
}
|
|
795
|
+
// Remove _persist_* keys from client data
|
|
796
|
+
for (const key of Object.keys(data)) {
|
|
797
|
+
if (key.startsWith('_persist_')) {
|
|
798
|
+
delete data[key];
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
// 8. Evaluate transitions (server uses state.Variables which is stateVars)
|
|
802
|
+
const { rule, nextActions } = this.actionRouter.evaluateTransitions(action, stateVars);
|
|
803
|
+
// 9. Determine credit behavior (server: creditNow logic)
|
|
804
|
+
let creditDeferred = action.credit === 'defer' || rule.credit_override === 'defer';
|
|
805
|
+
// 10. Session lifecycle (server: create/update/complete session)
|
|
806
|
+
let session = this.sessionManager.current;
|
|
807
|
+
let resultTotalWin = spinWin;
|
|
808
|
+
let sessionCompleted = false;
|
|
809
|
+
// Calculate max win cap for session
|
|
810
|
+
const maxWinCap = this.calculateMaxWinCap(bet);
|
|
811
|
+
if (rule.creates_session && !this.sessionManager.isActive) {
|
|
812
|
+
// CREATE SESSION — initial spin counted (server: createSession includes spinWin)
|
|
813
|
+
session = this.sessionManager.createSession(rule, stateVars, bet, spinWin, maxWinCap);
|
|
814
|
+
creditDeferred = true;
|
|
815
|
+
resultTotalWin = spinWin;
|
|
816
|
+
// Clear the trigger variable — it was consumed to set spinsRemaining
|
|
817
|
+
if (rule.session_config?.total_spins_var) {
|
|
818
|
+
delete this.variables[rule.session_config.total_spins_var];
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
else if (this.sessionManager.isActive) {
|
|
822
|
+
// UPDATE SESSION — accumulate win, check completion
|
|
823
|
+
session = this.sessionManager.updateSession(rule, stateVars, spinWin);
|
|
824
|
+
if (session?.completed) {
|
|
825
|
+
// SESSION COMPLETED — server returns session.TotalWin as result.TotalWin
|
|
826
|
+
const completed = this.sessionManager.completeSession();
|
|
827
|
+
session = completed.session;
|
|
828
|
+
resultTotalWin = completed.totalWin;
|
|
829
|
+
sessionCompleted = true;
|
|
830
|
+
creditDeferred = false;
|
|
831
|
+
// Clean up session-scoped variables
|
|
832
|
+
for (const varName of completed.sessionVarNames) {
|
|
833
|
+
delete this.variables[varName];
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
else {
|
|
837
|
+
// Mid-session: totalWin = spinWin, credit deferred
|
|
838
|
+
resultTotalWin = spinWin;
|
|
839
|
+
creditDeferred = true;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
// No session: resultTotalWin = spinWin (already set)
|
|
843
|
+
// Apply max win cap for non-session spins
|
|
844
|
+
if (!this.sessionManager.isActive && !sessionCompleted && maxWinCap !== undefined && resultTotalWin > maxWinCap) {
|
|
845
|
+
resultTotalWin = maxWinCap;
|
|
846
|
+
this.variables.max_win_reached = 1;
|
|
847
|
+
data.max_win_reached = true;
|
|
848
|
+
}
|
|
849
|
+
return {
|
|
850
|
+
totalWin: Math.round(resultTotalWin * 100) / 100,
|
|
851
|
+
data,
|
|
852
|
+
nextActions,
|
|
853
|
+
session,
|
|
854
|
+
// In simulation mode, return reference directly (caller only reads, never mutates)
|
|
855
|
+
variables: this.simulationMode ? this.variables : { ...this.variables },
|
|
856
|
+
creditDeferred,
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
reset() {
|
|
860
|
+
this.variables = {};
|
|
861
|
+
this.sessionManager.reset();
|
|
862
|
+
this.persistentState.reset();
|
|
863
|
+
}
|
|
864
|
+
destroy() {
|
|
865
|
+
if (this.L) {
|
|
866
|
+
lua.lua_close(this.L);
|
|
867
|
+
this.L = null;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
// ─── Private ──────────────────────────────────────────
|
|
871
|
+
loadScript(source) {
|
|
872
|
+
const status = lauxlib.luaL_dostring(this.L, to_luastring(source));
|
|
873
|
+
if (status !== lua.LUA_OK) {
|
|
874
|
+
const err = to_jsstring(lua.lua_tostring(this.L, -1));
|
|
875
|
+
lua.lua_pop(this.L, 1);
|
|
876
|
+
throw new Error(`Failed to load Lua script: ${err}`);
|
|
877
|
+
}
|
|
878
|
+
lua.lua_getglobal(this.L, cachedToLuastring('execute'));
|
|
879
|
+
if (lua.lua_type(this.L, -1) !== lua.LUA_TFUNCTION) {
|
|
880
|
+
lua.lua_pop(this.L, 1);
|
|
881
|
+
throw new Error('Lua script must define a global `execute(state)` function');
|
|
882
|
+
}
|
|
883
|
+
lua.lua_pop(this.L, 1);
|
|
884
|
+
}
|
|
885
|
+
callLuaExecute(stage, action, params, variables) {
|
|
886
|
+
lua.lua_getglobal(this.L, cachedToLuastring('execute'));
|
|
887
|
+
// Build state table: {stage, action, params, variables}
|
|
888
|
+
lua.lua_createtable(this.L, 0, 4);
|
|
889
|
+
// state.stage
|
|
890
|
+
lua.lua_pushstring(this.L, cachedToLuastring(stage));
|
|
891
|
+
lua.lua_setfield(this.L, -2, cachedToLuastring('stage'));
|
|
892
|
+
// state.action (server sets this at top level)
|
|
893
|
+
lua.lua_pushstring(this.L, cachedToLuastring(action));
|
|
894
|
+
lua.lua_setfield(this.L, -2, cachedToLuastring('action'));
|
|
895
|
+
// state.params
|
|
896
|
+
pushJSValue(this.L, params);
|
|
897
|
+
lua.lua_setfield(this.L, -2, cachedToLuastring('params'));
|
|
898
|
+
// state.variables
|
|
899
|
+
pushJSValue(this.L, variables);
|
|
900
|
+
lua.lua_setfield(this.L, -2, cachedToLuastring('variables'));
|
|
901
|
+
const status = lua.lua_pcall(this.L, 1, 1, 0);
|
|
902
|
+
if (status !== lua.LUA_OK) {
|
|
903
|
+
const err = to_jsstring(lua.lua_tostring(this.L, -1));
|
|
904
|
+
lua.lua_pop(this.L, 1);
|
|
905
|
+
throw new Error(`Lua execute() failed: ${err}`);
|
|
906
|
+
}
|
|
907
|
+
if (this.simulationMode) {
|
|
908
|
+
// Fast path: extract only total_win, variables, _persist_* keys
|
|
909
|
+
const result = {};
|
|
910
|
+
lua.lua_getfield(this.L, -1, cachedToLuastring('total_win'));
|
|
911
|
+
result.total_win = lua.lua_type(this.L, -1) === lua.LUA_TNUMBER
|
|
912
|
+
? lua.lua_tonumber(this.L, -1) : 0;
|
|
913
|
+
lua.lua_pop(this.L, 1);
|
|
914
|
+
lua.lua_getfield(this.L, -1, cachedToLuastring('variables'));
|
|
915
|
+
if (lua.lua_type(this.L, -1) === lua.LUA_TTABLE) {
|
|
916
|
+
result.variables = luaToJS(this.L, -1);
|
|
917
|
+
}
|
|
918
|
+
lua.lua_pop(this.L, 1);
|
|
919
|
+
// Scan for _persist_* keys (different stages may or may not have them)
|
|
920
|
+
lua.lua_pushnil(this.L);
|
|
921
|
+
while (lua.lua_next(this.L, -2) !== 0) {
|
|
922
|
+
if (lua.lua_type(this.L, -2) === lua.LUA_TSTRING) {
|
|
923
|
+
const key = to_jsstring(lua.lua_tostring(this.L, -2));
|
|
924
|
+
if (key.startsWith('_persist_')) {
|
|
925
|
+
result[key] = luaToJS(this.L, -1);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
lua.lua_pop(this.L, 1);
|
|
929
|
+
}
|
|
930
|
+
lua.lua_pop(this.L, 1);
|
|
931
|
+
return result;
|
|
932
|
+
}
|
|
933
|
+
// Full path
|
|
934
|
+
const result = luaToJS(this.L, -1);
|
|
935
|
+
lua.lua_pop(this.L, 1);
|
|
936
|
+
if (!result || typeof result !== 'object' || Array.isArray(result)) {
|
|
937
|
+
throw new Error('Lua execute() must return a table');
|
|
938
|
+
}
|
|
939
|
+
return result;
|
|
940
|
+
}
|
|
941
|
+
calculateMaxWinCap(bet) {
|
|
942
|
+
const mw = this.gameDefinition.max_win;
|
|
943
|
+
if (!mw)
|
|
944
|
+
return undefined;
|
|
945
|
+
const caps = [];
|
|
946
|
+
if (mw.multiplier !== undefined)
|
|
947
|
+
caps.push(bet * mw.multiplier);
|
|
948
|
+
if (mw.fixed !== undefined)
|
|
949
|
+
caps.push(mw.fixed);
|
|
950
|
+
return caps.length > 0 ? Math.min(...caps) : undefined;
|
|
951
|
+
}
|
|
952
|
+
pickFromDistribution(distribution) {
|
|
953
|
+
const entries = Object.entries(distribution);
|
|
954
|
+
const totalWeight = entries.reduce((sum, [, w]) => sum + w, 0);
|
|
955
|
+
let roll = this.api.randomFloat() * totalWeight;
|
|
956
|
+
for (const [value, weight] of entries) {
|
|
957
|
+
roll -= weight;
|
|
958
|
+
if (roll < 0)
|
|
959
|
+
return parseInt(value, 10);
|
|
960
|
+
}
|
|
961
|
+
return parseInt(entries[entries.length - 1][0], 10);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/**
|
|
966
|
+
* Runs N iterations of a Lua game script and collects RTP statistics.
|
|
967
|
+
* Supports regular spins, buy bonus, and ante bet simulation.
|
|
968
|
+
*
|
|
969
|
+
* @example
|
|
970
|
+
* ```ts
|
|
971
|
+
* const runner = new SimulationRunner({
|
|
972
|
+
* script: luaSource,
|
|
973
|
+
* gameDefinition,
|
|
974
|
+
* iterations: 1_000_000,
|
|
975
|
+
* bet: 1.0,
|
|
976
|
+
* seed: 42,
|
|
977
|
+
* onProgress: (done, total) => console.log(`${done}/${total}`),
|
|
978
|
+
* });
|
|
979
|
+
*
|
|
980
|
+
* const result = runner.run();
|
|
981
|
+
* console.log(`RTP: ${result.totalRtp.toFixed(2)}%`);
|
|
982
|
+
* ```
|
|
983
|
+
*/
|
|
984
|
+
class SimulationRunner {
|
|
985
|
+
config;
|
|
986
|
+
constructor(config) {
|
|
987
|
+
this.config = config;
|
|
988
|
+
}
|
|
989
|
+
run() {
|
|
990
|
+
const { script, gameDefinition, iterations, bet, seed, action: startAction = 'spin', params, progressInterval = 100_000, onProgress, } = this.config;
|
|
991
|
+
const engine = new LuaEngine({
|
|
992
|
+
script,
|
|
993
|
+
gameDefinition,
|
|
994
|
+
seed,
|
|
995
|
+
logger: () => { },
|
|
996
|
+
simulationMode: true,
|
|
997
|
+
});
|
|
998
|
+
const spinCost = this.calculateSpinCost(startAction, bet, gameDefinition, params);
|
|
999
|
+
let totalWagered = 0;
|
|
1000
|
+
let totalWon = 0;
|
|
1001
|
+
let baseGameWin = 0;
|
|
1002
|
+
let bonusWin = 0;
|
|
1003
|
+
let hits = 0;
|
|
1004
|
+
let maxWinMultiplier = 0;
|
|
1005
|
+
let maxWinHits = 0;
|
|
1006
|
+
let bonusTriggered = 0;
|
|
1007
|
+
let bonusSpinsPlayed = 0;
|
|
1008
|
+
const startTime = Date.now();
|
|
1009
|
+
try {
|
|
1010
|
+
for (let i = 0; i < iterations; i++) {
|
|
1011
|
+
totalWagered += spinCost;
|
|
1012
|
+
let roundWin = 0;
|
|
1013
|
+
let roundBonusWin = 0;
|
|
1014
|
+
// Execute the starting action
|
|
1015
|
+
let result = engine.execute({
|
|
1016
|
+
action: startAction,
|
|
1017
|
+
bet,
|
|
1018
|
+
params,
|
|
1019
|
+
});
|
|
1020
|
+
const baseWin = result.totalWin;
|
|
1021
|
+
// If a session was created, play through it using nextActions from the engine
|
|
1022
|
+
if (result.session && !result.session.completed) {
|
|
1023
|
+
bonusTriggered++;
|
|
1024
|
+
let safetyLimit = 10_000;
|
|
1025
|
+
while (result.session && !result.session.completed && safetyLimit-- > 0) {
|
|
1026
|
+
const nextAction = result.nextActions[0];
|
|
1027
|
+
result = engine.execute({ action: nextAction, bet });
|
|
1028
|
+
bonusSpinsPlayed++;
|
|
1029
|
+
}
|
|
1030
|
+
// Session completion returns cumulative totalWin (includes trigger spin).
|
|
1031
|
+
// Use it as the full round win — don't add baseWin separately.
|
|
1032
|
+
roundWin = result.totalWin;
|
|
1033
|
+
roundBonusWin = roundWin - baseWin;
|
|
1034
|
+
}
|
|
1035
|
+
else {
|
|
1036
|
+
// No session — just base game win
|
|
1037
|
+
roundWin = baseWin;
|
|
1038
|
+
}
|
|
1039
|
+
baseGameWin += baseWin;
|
|
1040
|
+
bonusWin += roundBonusWin;
|
|
1041
|
+
totalWon += roundWin;
|
|
1042
|
+
if (roundWin > 0)
|
|
1043
|
+
hits++;
|
|
1044
|
+
const roundMultiplier = roundWin / bet;
|
|
1045
|
+
if (roundMultiplier > maxWinMultiplier) {
|
|
1046
|
+
maxWinMultiplier = roundMultiplier;
|
|
1047
|
+
}
|
|
1048
|
+
if (result.variables?.max_win_reached === 1) {
|
|
1049
|
+
maxWinHits++;
|
|
1050
|
+
}
|
|
1051
|
+
// Progress reporting
|
|
1052
|
+
if (onProgress && (i + 1) % progressInterval === 0) {
|
|
1053
|
+
onProgress(i + 1, iterations);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
finally {
|
|
1058
|
+
engine.destroy();
|
|
1059
|
+
}
|
|
1060
|
+
const durationMs = Date.now() - startTime;
|
|
1061
|
+
return {
|
|
1062
|
+
gameId: gameDefinition.id,
|
|
1063
|
+
action: startAction,
|
|
1064
|
+
iterations,
|
|
1065
|
+
durationMs,
|
|
1066
|
+
totalRtp: totalWagered > 0 ? (totalWon / totalWagered) * 100 : 0,
|
|
1067
|
+
baseGameRtp: totalWagered > 0 ? (baseGameWin / totalWagered) * 100 : 0,
|
|
1068
|
+
bonusRtp: totalWagered > 0 ? (bonusWin / totalWagered) * 100 : 0,
|
|
1069
|
+
hitFrequency: iterations > 0 ? (hits / iterations) * 100 : 0,
|
|
1070
|
+
maxWin: Math.round(maxWinMultiplier * 100) / 100,
|
|
1071
|
+
maxWinHits,
|
|
1072
|
+
bonusTriggered,
|
|
1073
|
+
bonusSpinsPlayed,
|
|
1074
|
+
_raw: { totalWagered, totalWon, baseGameWin, bonusWin, hits },
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
/** Calculate the real cost of one spin (accounting for buy bonus / ante bet) */
|
|
1078
|
+
calculateSpinCost(action, bet, gameDefinition, params) {
|
|
1079
|
+
// Check if this is a buy bonus action
|
|
1080
|
+
const actionDef = gameDefinition.actions[action];
|
|
1081
|
+
if (actionDef?.buy_bonus_mode && gameDefinition.buy_bonus) {
|
|
1082
|
+
const mode = gameDefinition.buy_bonus.modes[actionDef.buy_bonus_mode];
|
|
1083
|
+
if (mode) {
|
|
1084
|
+
return bet * mode.cost_multiplier;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
// Check ante bet
|
|
1088
|
+
if (params?.ante_bet && gameDefinition.ante_bet) {
|
|
1089
|
+
return bet * gameDefinition.ante_bet.cost_multiplier;
|
|
1090
|
+
}
|
|
1091
|
+
return bet;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
/** Format a SimulationResult for console output */
|
|
1095
|
+
function formatSimulationResult(result) {
|
|
1096
|
+
const lines = [
|
|
1097
|
+
'',
|
|
1098
|
+
'--- Simulation Results ---',
|
|
1099
|
+
`Game: ${result.gameId}`,
|
|
1100
|
+
`Action: ${result.action}`,
|
|
1101
|
+
`Iterations: ${result.iterations.toLocaleString()}`,
|
|
1102
|
+
`Duration: ${(result.durationMs / 1000).toFixed(1)}s`,
|
|
1103
|
+
`Total RTP: ${result.totalRtp.toFixed(2)}%`,
|
|
1104
|
+
`Base Game RTP: ${result.baseGameRtp.toFixed(2)}%`,
|
|
1105
|
+
`Bonus RTP: ${result.bonusRtp.toFixed(2)}%`,
|
|
1106
|
+
`Hit Frequency: ${result.hitFrequency.toFixed(2)}%`,
|
|
1107
|
+
`Max Win: ${result.maxWin.toFixed(2)}x`,
|
|
1108
|
+
`Max Win Hits: ${result.maxWinHits} (rounds capped by max_win)`,
|
|
1109
|
+
];
|
|
1110
|
+
if (result.bonusTriggered > 0) {
|
|
1111
|
+
const frequency = Math.round(result.iterations / result.bonusTriggered);
|
|
1112
|
+
lines.push(`Bonus Triggered: ${result.bonusTriggered.toLocaleString()} (1 in ${frequency} spins)`);
|
|
1113
|
+
lines.push(`Bonus Spins Played: ${result.bonusSpinsPlayed.toLocaleString()}`);
|
|
1114
|
+
}
|
|
1115
|
+
return lines.join('\n');
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
export { ActionRouter, LuaEngine, LuaEngineAPI, PersistentState, SessionManager, SimulationRunner, createSeededRng, evaluateCondition, formatSimulationResult };
|
|
1119
|
+
//# sourceMappingURL=lua.esm.js.map
|