edadae9d-5011-42f5-bdbb-1a6f170f85e0.js 13.1 KB
"use strict";
cc._RF.push(module, 'edada6dUBFC9b27Gm8XD4Xg', 'GameRecord');
// script/avg/game-data/GameRecord.ts

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GameRecord = void 0;
const GameVariables_1 = require("./GameVariables");
const simba_eventkit_1 = require("simba-eventkit");
const simba_utils_1 = require("simba-utils");
const simba_localstorage_1 = require("simba-localstorage");
const GameConfig_1 = require("../../GameConfig");
const PlotsData_1 = require("./PlotsData");
const simba_sdk_1 = require("simba-sdk");
const PlotModel_1 = require("../model/PlotModel");
var GameRecord;
(function (GameRecord) {
    let emitter = new simba_eventkit_1.Emitter;
    const _globalVariables = Object.assign({}, GameVariables_1.defaultGlobalVariables);
    const _recordVariables = Object.assign({}, GameVariables_1.defaultRecordVariables);
    let _recordVersion = 0;
    let _initailized = false;
    let _inTransaction = false;
    function startTransaction() {
        _inTransaction = true;
    }
    GameRecord.startTransaction = startTransaction;
    function endTransaction(forceSave = false) {
        _inTransaction = false;
        forceSave ? saveRecord() : GameRecord.autoSave();
    }
    GameRecord.endTransaction = endTransaction;
    let globalVarDirty = false;
    GameRecord.globalVariables = new Proxy(_globalVariables, {
        set: (target, p, value) => {
            let constrains = GameVariables_1.globalVariableConstrains[p];
            if (constrains) {
                if (constrains.min !== undefined && value < constrains.min) {
                    value = constrains.min;
                }
                if (constrains.max !== undefined && value > constrains.max) {
                    value = constrains.max;
                }
            }
            if (target[p] !== value) {
                globalVarDirty = true;
                let prevValue = target[p];
                target[p] = value;
                emitter.emit("g." + p, "global", p, prevValue, value);
            }
            return true;
        }
    });
    GameRecord.recordVariables = new Proxy(_recordVariables, {
        set: (target, p, value) => {
            let constrains = GameVariables_1.recordVariableConstrains[p];
            if (constrains) {
                if (constrains.min !== undefined && value < constrains.min) {
                    value = constrains.min;
                }
                if (constrains.max !== undefined && value > constrains.max) {
                    value = constrains.max;
                }
            }
            if (target[p] !== value) {
                let prevValue = target[p];
                target[p] = value;
                emitter.emit("r." + p, "record", p, prevValue, value);
            }
            return true;
        }
    });
    function getVariableValue(varName) {
        if (/^g\./.test(varName)) {
            return _globalVariables[varName.substr(2)];
        }
        else if (/^r\./.test(varName)) {
            return _recordVariables[varName.substr(2)];
        }
        throw new Error("Invalid varName.");
    }
    GameRecord.getVariableValue = getVariableValue;
    function setVariableValue(varName, value) {
        if (/^g\./.test(varName)) {
            GameRecord.globalVariables[varName.substr(2)] = value;
        }
        else if (/^r\./.test(varName)) {
            GameRecord.recordVariables[varName.substr(2)] = value;
        }
        else {
            throw new Error("Invalid varName.");
        }
    }
    GameRecord.setVariableValue = setVariableValue;
    function onGlobalVariableChange(varName, callback) {
        return emitter.on("g." + varName, callback);
    }
    GameRecord.onGlobalVariableChange = onGlobalVariableChange;
    function onRecordVariableChange(varName, callback) {
        return emitter.on("r." + varName, callback);
    }
    GameRecord.onRecordVariableChange = onRecordVariableChange;
    function onVariableChange(varName, callback) {
        if (!/^g\./.test(varName) && !/^r\./.test(varName)) {
            throw new Error("Invalid varName.");
        }
        return emitter.on(varName, callback);
    }
    GameRecord.onVariableChange = onVariableChange;
    const plotsInfo = {};
    const records = [];
    let lastRecordVariables;
    let currentRecordIndex = -1;
    function getPlotsInfo() {
        return plotsInfo;
    }
    GameRecord.getPlotsInfo = getPlotsInfo;
    function getRecords() {
        return records;
    }
    GameRecord.getRecords = getRecords;
    function getCurrentRecordItems() {
        return records[currentRecordIndex].d;
    }
    GameRecord.getCurrentRecordItems = getCurrentRecordItems;
    function initRecords() {
        if (_initailized)
            return;
        _initailized = true;
        Object.assign(_globalVariables, simba_localstorage_1.LocalStorage.getObject(GameConfig_1.GameConfig.gameId + ".gameGlobalVars", GameVariables_1.defaultGlobalVariables));
        Object.assign(records, simba_localstorage_1.LocalStorage.getObject(GameConfig_1.GameConfig.gameId + ".gameRecords", []));
        Object.assign(plotsInfo, simba_localstorage_1.LocalStorage.getObject(GameConfig_1.GameConfig.gameId + ".plotsInfo", {}));
        _recordVersion = simba_localstorage_1.LocalStorage.getInt(GameConfig_1.GameConfig.gameId + ".recordVersion");
        let data = simba_sdk_1.SDK.getGameRecord();
        let version = data["v"];
        if (version > _recordVersion) {
            overwriteRecordWithData(data, false);
        }
    }
    GameRecord.initRecords = initRecords;
    function setSelectOptionForPlot(plotId, option) {
        let history = records[currentRecordIndex].d;
        let top = history[history.length - 1];
        let idx = top.p.findIndex(v => v === plotId);
        if (idx >= 0) {
            if (!top.s)
                top.s = [];
            top.s[idx] = option;
            return;
        }
        throw new Error("Invalid option");
    }
    GameRecord.setSelectOptionForPlot = setSelectOptionForPlot;
    // use PlotManager.completePlto, unless you know what you are doing.
    function setPlotCustomData(index, data) {
        let items = records[currentRecordIndex].d;
        let lastItem = items[items.length - 1];
        if (!lastItem.c)
            lastItem.c = [];
        lastItem.c[index] = data;
        saveRecord();
    }
    GameRecord.setPlotCustomData = setPlotCustomData;
    let _started = false;
    function startGameWithRecord(index) {
        if (_started) {
            for (let k in _recordVariables) {
                delete _recordVariables[k];
            }
        }
        _started = true;
        currentRecordIndex = index;
        if (!records[index]) {
            records[index] = { name: "", d: [] };
        }
        const arr = records[index].d;
        Object.assign(_recordVariables, GameVariables_1.defaultRecordVariables);
        for (let v of arr) {
            Object.assign(_recordVariables, v.v);
        }
        lastRecordVariables = Object.assign({}, _recordVariables);
        if (!arr.length) {
            arr.push({ p: [PlotsData_1.getPlotsIndex().firstPlot], v: {} });
        }
        return arr[arr.length - 1].p;
    }
    GameRecord.startGameWithRecord = startGameWithRecord;
    function startPlot(plot, index = 0) {
        if (plot >= 0) {
            if (!plotsInfo[plot])
                plotsInfo[plot] = { cnt: 1 };
            else
                plotsInfo[plot].cnt++;
        }
        let history = records[currentRecordIndex].d;
        let p = [];
        if (history.length) {
            p = [...history[history.length - 1].p];
        }
        p[index] = plot;
        if (plot === PlotModel_1.SpecialPlotId.End && p.length > 1 && (index === p.length - 1)) { // 支线结束时,判断能否缩短数组
            let i = p.length - 2;
            let deleteCount = 1;
            for (; i > 0; i--) {
                if (p[i] !== PlotModel_1.SpecialPlotId.End) {
                    break;
                }
                else {
                    deleteCount++;
                }
            }
            p.length = p.length - deleteCount;
        }
        if (lastRecordVariables) {
            let diff = {};
            for (let k in _recordVariables) {
                if (_recordVariables[k] !== lastRecordVariables[k]) {
                    diff[k] = _recordVariables[k];
                }
            }
            records[currentRecordIndex].d.push({ p, v: diff });
        }
        else {
            records[currentRecordIndex].d.push({ p, v: {} });
        }
        lastRecordVariables = Object.assign({}, _recordVariables);
        GameRecord.autoSave();
        return p;
    }
    GameRecord.startPlot = startPlot;
    GameRecord.autoSave = simba_utils_1.throttle(saveRecord, 1000, true);
    GameRecord.autoUpload = simba_utils_1.throttle(uploadRecord, 5000, true);
    async function uploadRecord() {
        if (_inTransaction)
            return;
        console.log("准备上传云存档");
        simba_sdk_1.SDK.uploadGameRecord({ g: _globalVariables, r: records, p: plotsInfo, v: _recordVersion });
    }
    GameRecord.uploadRecord = uploadRecord;
    function overwriteRecordWithData(data, upload = true) {
        if (typeof data === "string")
            data = JSON.parse(data);
        for (let k in _globalVariables) {
            delete _globalVariables[k];
        }
        while (records.length) {
            records.pop();
        }
        _recordVersion = data["v"];
        Object.assign(_globalVariables, data["g"]);
        Object.assign(records, data["r"]);
        Object.assign(plotsInfo, data["p"]);
        saveRecord(upload);
    }
    GameRecord.overwriteRecordWithData = overwriteRecordWithData;
    function getRecordAsString() {
        return JSON.stringify({ g: _globalVariables, r: records, p: plotsInfo, v: _recordVersion });
    }
    GameRecord.getRecordAsString = getRecordAsString;
    function saveRecord(upload = true) {
        if (_inTransaction)
            return;
        if (globalVarDirty) {
            simba_localstorage_1.LocalStorage.setObject(GameConfig_1.GameConfig.gameId + ".gameGlobalVars", _globalVariables);
        }
        simba_localstorage_1.LocalStorage.setObject(GameConfig_1.GameConfig.gameId + ".gameRecords", records);
        simba_localstorage_1.LocalStorage.setObject(GameConfig_1.GameConfig.gameId + ".plotsInfo", plotsInfo);
        _recordVersion = (new Date).getTime();
        simba_localstorage_1.LocalStorage.setInt(GameConfig_1.GameConfig.gameId + ".recordVersion", _recordVersion);
        upload && GameRecord.autoUpload();
    }
    GameRecord.saveRecord = saveRecord;
    function emptyRecords() {
        simba_localstorage_1.LocalStorage.remove(GameConfig_1.GameConfig.gameId + ".gameGlobalVars");
        simba_localstorage_1.LocalStorage.remove(GameConfig_1.GameConfig.gameId + ".gameRecords");
        simba_localstorage_1.LocalStorage.remove(GameConfig_1.GameConfig.gameId + ".plotsInfo");
        simba_localstorage_1.LocalStorage.remove(GameConfig_1.GameConfig.gameId + ".recordVersion");
        for (let k in _globalVariables) {
            delete _globalVariables[k];
        }
        while (records.length) {
            records.pop();
        }
        for (let k in plotsInfo) {
            delete plotsInfo[k];
        }
        _recordVersion = 0;
        _initailized = false;
        initRecords();
        return uploadRecord();
    }
    GameRecord.emptyRecords = emptyRecords;
    function rollbackToIndex(index, preserveVars) {
        if (index < 0 || index >= records[currentRecordIndex].d.length)
            return false;
        let currRecords = records[currentRecordIndex].d;
        currRecords.length = index + 1;
        currRecords[index].s = undefined;
        let preserves = {};
        if (preserveVars) {
            for (let v of preserveVars) {
                preserves[v] = _recordVariables[v];
            }
        }
        for (let k in _recordVariables) { // clear all variables
            delete _recordVariables[k];
        }
        Object.assign(_recordVariables, GameVariables_1.defaultRecordVariables);
        for (let i = 0; i <= index; i++) {
            let data = currRecords[i];
            Object.assign(_recordVariables, data.v);
        }
        Object.assign(_recordVariables, preserves);
        lastRecordVariables = Object.assign({}, _recordVariables);
        GameRecord.autoSave();
        return true;
    }
    GameRecord.rollbackToIndex = rollbackToIndex;
    function rollbackToPlot(plot, reverseFind = false, preserveVars) {
        let items = records[currentRecordIndex].d;
        let index = 0;
        if (reverseFind) {
            index = items.length - 1;
            for (; index >= 0; index--) {
                if (items[index].p.findIndex(p => p === plot) >= 0) {
                    break;
                }
            }
        }
        else {
            index = items.findIndex(v => v.p.findIndex(p => p === plot) >= 0);
        }
        if (index < 0) {
            throw new Error("Plot " + plot + " not found!");
        }
        return rollbackToIndex(index, preserveVars);
    }
    GameRecord.rollbackToPlot = rollbackToPlot;
})(GameRecord = exports.GameRecord || (exports.GameRecord = {}));
if (GameConfig_1.GameConfig.debug) {
    window.GameRecord = GameRecord;
}

cc._RF.pop();