1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2025-12-16 03:31:52 +00:00
This commit is contained in:
Daan Breur 2021-11-27 14:37:32 +00:00 committed by GitHub
commit 35aba7606a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 1363 additions and 1071 deletions

View File

@ -214,6 +214,35 @@
}
}
}
.inline {
display: flex;
flex-direction: row;
align-items: center;
> * {
@include S(margin-right, 7.5px);
}
}
.detailsFormElem {
> .object {
pointer-events: all;
> summary {
transition: opacity 0.1s ease-in-out;
cursor: pointer;
pointer-events: all;
&:hover {
opacity: 0.8;
}
}
> div {
@include S(margin-left, 4px);
cursor: pointer;
}
}
}
}
> .buttons {

View File

@ -47,13 +47,67 @@ export class FormElement {
}
}
export class FormElementDetails extends FormElement {
/**
*
* @param {object} param0
* @param {string} param0.id
* @param {string} param0.label
* @param {Array<FormElement>} param0.formElements
*/
constructor({ id, label, formElements }) {
super(id, label);
this.formElements = formElements;
this.element = null;
}
getHtml() {
return `<div class="formElement detailsFormElem"><details class='object'>
${this.label ? `<summary>${this.label}</summary>` : ""}
<div class="content">
${this.formElements.map(e => e.getHtml()).join("")}
</div></details></div>`;
}
bindEvents(parent, clickTrackers) {
this.element = this.getFormElement(parent);
for (let i = 0; i < this.formElements.length; ++i) {
const elem = this.formElements[i];
elem.bindEvents(parent, clickTrackers);
elem.valueChosen.add(this.valueChosen.dispatch, this.valueChosen);
}
}
getValue() {
let formElementValues = {};
for (let i = 0; i < this.formElements.length; ++i) {
const elem = this.formElements[i];
formElementValues[elem.id] = elem.getValue();
}
return formElementValues;
}
focus() {}
}
export class FormElementInput extends FormElement {
constructor({ id, label = null, placeholder, defaultValue = "", inputType = "text", validator = null }) {
constructor({
id,
label = null,
placeholder,
defaultValue = "",
inputType = "text",
validator = null,
inline = false,
}) {
super(id, label);
this.placeholder = placeholder;
this.defaultValue = defaultValue;
this.inputType = inputType;
this.validator = validator;
this.inline = inline;
this.element = null;
}
@ -83,7 +137,7 @@ export class FormElementInput extends FormElement {
}
return `
<div class="formElement input">
<div class="formElement input ${this.inline ? "inline" : ""}">
${this.label ? `<label>${this.label}</label>` : ""}
<input
type="${inputType}"
@ -143,21 +197,22 @@ export class FormElementInput extends FormElement {
}
export class FormElementCheckbox extends FormElement {
constructor({ id, label, defaultValue = true }) {
constructor({ id, label, defaultValue = true, inline = false }) {
super(id, label);
this.defaultValue = defaultValue;
this.value = this.defaultValue;
this.inline = inline;
this.element = null;
}
getHtml() {
return `
<div class="formElement checkBoxFormElem">
<div class="formElement checkBoxFormElem ${this.inline ? "inline" : ""}">
${this.label ? `<label>${this.label}</label>` : ""}
<div class="checkbox ${this.defaultValue ? "checked" : ""}" data-formId='${this.id}'>
<span class="knob"></span >
</div >
<span class="knob"></span>
</div>
</div>
`;
}
@ -181,7 +236,7 @@ export class FormElementCheckbox extends FormElement {
this.element.classList.toggle("checked", this.value);
}
focus(parent) {}
focus() {}
}
export class FormElementItemChooser extends FormElement {

File diff suppressed because it is too large Load Diff

View File

@ -15,6 +15,9 @@ export class BaseMap extends BasicSerializableObject {
static getSchema() {
return {
seed: types.uint,
allowNonPrimaryColors: types.bool,
fullShapePercentage: types.uint,
wierdShapePercentage: types.uint,
};
}
@ -27,6 +30,9 @@ export class BaseMap extends BasicSerializableObject {
this.root = root;
this.seed = 0;
this.allowNonPrimaryColors = false;
this.fullShapePercentage = 0;
this.wierdShapePercentage = 0;
/**
* Mapping of 'X|Y' to chunk

View File

@ -168,6 +168,11 @@ export class MapChunk {
let availableColors = [enumColors.red, enumColors.green];
if (distanceToOriginInChunks > 2) {
availableColors.push(enumColors.blue);
if (this.root.map.allowNonPrimaryColors) {
availableColors.push(enumColors.yellow);
availableColors.push(enumColors.purple);
availableColors.push(enumColors.cyan);
}
}
this.internalGeneratePatch(rng, colorPatchSize, COLOR_ITEM_SINGLETONS[rng.choice(availableColors)]);
}
@ -198,7 +203,19 @@ export class MapChunk {
weights[enumSubShape.windmill] = 0;
}
if (distanceToOriginInChunks < 10) {
if (rng.nextRange(0, 100) <= this.root.map.fullShapePercentage) {
// Spawn full shape based on percentage.
const subShape = this.internalGenerateRandomSubShape(rng, weights);
subShapes = [subShape, subShape, subShape, subShape];
} else if (rng.nextRange(0, 100) <= this.root.map.wierdShapePercentage) {
// Spawn wierd shape based on percentage.
subShapes = [
this.internalGenerateRandomSubShape(rng, weights),
this.internalGenerateRandomSubShape(rng, weights),
this.internalGenerateRandomSubShape(rng, weights),
this.internalGenerateRandomSubShape(rng, weights),
];
} else if (distanceToOriginInChunks < 10) {
// Initial chunk patches always have the same shape
const subShape = this.internalGenerateRandomSubShape(rng, weights);
subShapes = [subShape, subShape, subShape, subShape];

View File

@ -28,7 +28,10 @@
"shape": "#5d5f6a",
"red": "#854f56",
"green": "#667964",
"blue": "#5e7ca4"
"blue": "#5e7ca4",
"purple": "#8776bc",
"yellow": "#cab57d",
"cyan": "#00b5b8"
},
"chunkOverview": {
"empty": "#444856",

View File

@ -28,7 +28,10 @@
"shape": "#eaebec",
"red": "#ffbfc1",
"green": "#cbffc4",
"blue": "#bfdaff"
"blue": "#bfdaff",
"purple": "#ecb3fc",
"yellow": "#fcf99c",
"cyan": "#85fdff"
},
"chunkOverview": {

View File

@ -14,6 +14,7 @@ import { SavegameInterface_V1006 } from "./schemas/1006";
import { SavegameInterface_V1007 } from "./schemas/1007";
import { SavegameInterface_V1008 } from "./schemas/1008";
import { SavegameInterface_V1009 } from "./schemas/1009";
import { SavegameInterface_V1010 } from "./schemas/1010";
const logger = createLogger("savegame");
@ -54,7 +55,7 @@ export class Savegame extends ReadWriteProxy {
* @returns {number}
*/
static getCurrentVersion() {
return 1009;
return 1010;
}
/**
@ -160,6 +161,11 @@ export class Savegame extends ReadWriteProxy {
data.version = 1009;
}
if (data.version === 1009) {
SavegameInterface_V1010.migrate1009to1010(data);
data.version = 1010;
}
return ExplainedResult.good();
}

View File

@ -10,6 +10,7 @@ import { SavegameInterface_V1006 } from "./schemas/1006";
import { SavegameInterface_V1007 } from "./schemas/1007";
import { SavegameInterface_V1008 } from "./schemas/1008";
import { SavegameInterface_V1009 } from "./schemas/1009";
import { SavegameInterface_V1010 } from "./schemas/1010";
/** @type {Object.<number, typeof BaseSavegameInterface>} */
export const savegameInterfaces = {
@ -23,6 +24,7 @@ export const savegameInterfaces = {
1007: SavegameInterface_V1007,
1008: SavegameInterface_V1008,
1009: SavegameInterface_V1009,
1010: SavegameInterface_V1010,
};
const logger = createLogger("savegame_interface_registry");

View File

@ -0,0 +1,38 @@
import { createLogger } from "../../core/logging.js";
import { SavegameInterface_V1009 } from "./1009.js";
const schema = require("./1010.json");
const logger = createLogger("savegame_interface/1010");
export class SavegameInterface_V1010 extends SavegameInterface_V1009 {
getVersion() {
return 1010;
}
getSchemaUncached() {
return schema;
}
/**
* @param {import("../savegame_typedefs.js").SavegameData} data
*/
static migrate1009to1010(data) {
logger.log("Migrating 1009 to 1010");
const dump = data.dump;
if (!dump) {
return true;
}
if (!dump.map.hasOwnProperty("allowNonPrimaryColors")) {
dump.map.allowNonPrimaryColors = false;
}
if (!dump.map.hasOwnProperty("fullShapePercentage")) {
dump.map.fullShapePercentage = 0;
}
if (!dump.map.hasOwnProperty("wierdShapePercentage")) {
dump.map.wierdShapePercentage = 0;
}
}
}

View File

@ -0,0 +1,5 @@
{
"type": "object",
"required": [],
"additionalProperties": true
}

View File

@ -1,480 +1,513 @@
import { APPLICATION_ERROR_OCCURED } from "../core/error_handler";
import { GameState } from "../core/game_state";
import { logSection, createLogger } from "../core/logging";
import { waitNextFrame } from "../core/utils";
import { globalConfig } from "../core/config";
import { GameLoadingOverlay } from "../game/game_loading_overlay";
import { KeyActionMapper } from "../game/key_action_mapper";
import { Savegame } from "../savegame/savegame";
import { GameCore } from "../game/core";
import { MUSIC } from "../platform/sound";
import { enumGameModeIds } from "../game/game_mode";
const logger = createLogger("state/ingame");
// Different sub-states
const stages = {
s3_createCore: "🌈 3: Create core",
s4_A_initEmptyGame: "🌈 4/A: Init empty game",
s4_B_resumeGame: "🌈 4/B: Resume game",
s5_firstUpdate: "🌈 5: First game update",
s6_postLoadHook: "🌈 6: Post load hook",
s7_warmup: "🌈 7: Warmup",
s10_gameRunning: "🌈 10: Game finally running",
leaving: "🌈 Saving, then leaving the game",
destroyed: "🌈 DESTROYED: Core is empty and waits for state leave",
initFailed: "🌈 ERROR: Initialization failed!",
};
export const gameCreationAction = {
new: "new-game",
resume: "resume-game",
};
// Typehints
export class GameCreationPayload {
constructor() {
/** @type {boolean|undefined} */
this.fastEnter;
/** @type {string} */
this.gameModeId;
/** @type {Savegame} */
this.savegame;
/** @type {object|undefined} */
this.gameModeParameters;
}
}
export class InGameState extends GameState {
constructor() {
super("InGameState");
/** @type {GameCreationPayload} */
this.creationPayload = null;
// Stores current stage
this.stage = "";
/** @type {GameCore} */
this.core = null;
/** @type {KeyActionMapper} */
this.keyActionMapper = null;
/** @type {GameLoadingOverlay} */
this.loadingOverlay = null;
/** @type {Savegame} */
this.savegame = null;
this.boundInputFilter = this.filterInput.bind(this);
/**
* Whether we are currently saving the game
* @TODO: This doesn't realy fit here
*/
this.currentSavePromise = null;
}
/**
* Switches the game into another sub-state
* @param {string} stage
*/
switchStage(stage) {
assert(stage, "Got empty stage");
if (stage !== this.stage) {
this.stage = stage;
logger.log(this.stage);
return true;
} else {
// log(this, "Re entering", stage);
return false;
}
}
// GameState implementation
getInnerHTML() {
return "";
}
getThemeMusic() {
if (this.creationPayload.gameModeId && this.creationPayload.gameModeId.includes("puzzle")) {
return MUSIC.puzzle;
}
return MUSIC.theme;
}
onBeforeExit() {
// logger.log("Saving before quitting");
// return this.doSave().then(() => {
// logger.log(this, "Successfully saved");
// // this.stageDestroyed();
// });
}
onAppPause() {
// if (this.stage === stages.s10_gameRunning) {
// logger.log("Saving because app got paused");
// this.doSave();
// }
}
getHasFadeIn() {
return false;
}
getPauseOnFocusLost() {
return false;
}
getHasUnloadConfirmation() {
return true;
}
onLeave() {
if (this.core) {
this.stageDestroyed();
}
this.app.inputMgr.dismountFilter(this.boundInputFilter);
}
onResized(w, h) {
super.onResized(w, h);
if (this.stage === stages.s10_gameRunning) {
this.core.resize(w, h);
}
}
// ---- End of GameState implementation
/**
* Goes back to the menu state
*/
goBackToMenu() {
if ([enumGameModeIds.puzzleEdit, enumGameModeIds.puzzlePlay].includes(this.gameModeId)) {
this.saveThenGoToState("PuzzleMenuState");
} else {
this.saveThenGoToState("MainMenuState");
}
}
/**
* Goes back to the settings state
*/
goToSettings() {
this.saveThenGoToState("SettingsState", {
backToStateId: this.key,
backToStatePayload: this.creationPayload,
});
}
/**
* Goes back to the settings state
*/
goToKeybindings() {
this.saveThenGoToState("KeybindingsState", {
backToStateId: this.key,
backToStatePayload: this.creationPayload,
});
}
/**
* Moves to a state outside of the game
* @param {string} stateId
* @param {any=} payload
*/
saveThenGoToState(stateId, payload) {
if (this.stage === stages.leaving || this.stage === stages.destroyed) {
logger.warn(
"Tried to leave game twice or during destroy:",
this.stage,
"(attempted to move to",
stateId,
")"
);
return;
}
this.stageLeavingGame();
this.doSave().then(() => {
this.stageDestroyed();
this.moveToState(stateId, payload);
});
}
onBackButton() {
// do nothing
}
/**
* Called when the game somehow failed to initialize. Resets everything to basic state and
* then goes to the main menu, showing the error
* @param {string} err
*/
onInitializationFailure(err) {
if (this.switchStage(stages.initFailed)) {
logger.error("Init failure:", err);
this.stageDestroyed();
this.moveToState("MainMenuState", { loadError: err });
}
}
// STAGES
/**
* Creates the game core instance, and thus the root
*/
stage3CreateCore() {
if (this.switchStage(stages.s3_createCore)) {
logger.log("Creating new game core");
this.core = new GameCore(this.app);
this.core.initializeRoot(this, this.savegame, this.gameModeId);
if (this.savegame.hasGameDump()) {
this.stage4bResumeGame();
} else {
this.app.gameAnalytics.handleGameStarted();
this.stage4aInitEmptyGame();
}
}
}
/**
* Initializes a new empty game
*/
stage4aInitEmptyGame() {
if (this.switchStage(stages.s4_A_initEmptyGame)) {
this.core.initNewGame();
this.stage5FirstUpdate();
}
}
/**
* Resumes an existing game
*/
stage4bResumeGame() {
if (this.switchStage(stages.s4_B_resumeGame)) {
if (!this.core.initExistingGame()) {
this.onInitializationFailure("Savegame is corrupt and can not be restored.");
return;
}
this.app.gameAnalytics.handleGameResumed();
this.stage5FirstUpdate();
}
}
/**
* Performs the first game update on the game which initializes most caches
*/
stage5FirstUpdate() {
if (this.switchStage(stages.s5_firstUpdate)) {
this.core.root.logicInitialized = true;
this.core.updateLogic();
this.stage6PostLoadHook();
}
}
/**
* Call the post load hook, this means that we have loaded the game, and all systems
* can operate and start to work now.
*/
stage6PostLoadHook() {
if (this.switchStage(stages.s6_postLoadHook)) {
logger.log("Post load hook");
this.core.postLoadHook();
this.stage7Warmup();
}
}
/**
* This makes the game idle and draw for a while, because we run most code this way
* the V8 engine can already start to optimize it. Also this makes sure the resources
* are in the VRAM and we have a smooth experience once we start.
*/
stage7Warmup() {
if (this.switchStage(stages.s7_warmup)) {
if (this.creationPayload.fastEnter) {
this.warmupTimeSeconds = globalConfig.warmupTimeSecondsFast;
} else {
this.warmupTimeSeconds = globalConfig.warmupTimeSecondsRegular;
}
}
}
/**
* The final stage where this game is running and updating regulary.
*/
stage10GameRunning() {
if (this.switchStage(stages.s10_gameRunning)) {
this.core.root.signals.readyToRender.dispatch();
logSection("GAME STARTED", "#26a69a");
// Initial resize, might have changed during loading (this is possible)
this.core.resize(this.app.screenWidth, this.app.screenHeight);
}
}
/**
* This stage destroys the whole game, used to cleanup
*/
stageDestroyed() {
if (this.switchStage(stages.destroyed)) {
// Cleanup all api calls
this.cancelAllAsyncOperations();
if (this.syncer) {
this.syncer.cancelSync();
this.syncer = null;
}
// Cleanup core
if (this.core) {
this.core.destruct();
this.core = null;
}
}
}
/**
* When leaving the game
*/
stageLeavingGame() {
if (this.switchStage(stages.leaving)) {
// ...
}
}
// END STAGES
/**
* Filters the input (keybindings)
*/
filterInput() {
return this.stage === stages.s10_gameRunning;
}
/**
* @param {GameCreationPayload} payload
*/
onEnter(payload) {
this.app.inputMgr.installFilter(this.boundInputFilter);
this.creationPayload = payload;
this.savegame = payload.savegame;
this.gameModeId = payload.gameModeId;
this.loadingOverlay = new GameLoadingOverlay(this.app, this.getDivElement());
this.loadingOverlay.showBasic();
// Remove unneded default element
document.body.querySelector(".modalDialogParent").remove();
this.asyncChannel
.watch(waitNextFrame())
.then(() => this.stage3CreateCore())
.catch(ex => {
logger.error(ex);
throw ex;
});
}
/**
* Render callback
* @param {number} dt
*/
onRender(dt) {
if (APPLICATION_ERROR_OCCURED) {
// Application somehow crashed, do not do anything
return;
}
if (this.stage === stages.s7_warmup) {
this.core.draw();
this.warmupTimeSeconds -= dt / 1000.0;
if (this.warmupTimeSeconds < 0) {
logger.log("Warmup completed");
this.stage10GameRunning();
}
}
if (this.stage === stages.s10_gameRunning) {
this.core.tick(dt);
}
// If the stage is still active (This might not be the case if tick() moved us to game over)
if (this.stage === stages.s10_gameRunning) {
// Only draw if page visible
if (this.app.pageVisible) {
this.core.draw();
}
this.loadingOverlay.removeIfAttached();
} else {
if (!this.loadingOverlay.isAttached()) {
this.loadingOverlay.showBasic();
}
}
}
onBackgroundTick(dt) {
this.onRender(dt);
}
/**
* Saves the game
*/
doSave() {
if (!this.savegame || !this.savegame.isSaveable()) {
return Promise.resolve();
}
if (APPLICATION_ERROR_OCCURED) {
logger.warn("skipping save because application crashed");
return Promise.resolve();
}
if (
this.stage !== stages.s10_gameRunning &&
this.stage !== stages.s7_warmup &&
this.stage !== stages.leaving
) {
logger.warn("Skipping save because game is not ready");
return Promise.resolve();
}
if (this.currentSavePromise) {
logger.warn("Skipping double save and returning same promise");
return this.currentSavePromise;
}
if (!this.core.root.gameMode.getIsSaveable()) {
return Promise.resolve();
}
logger.log("Starting to save game ...");
this.savegame.updateData(this.core.root);
this.currentSavePromise = this.savegame
.writeSavegameAndMetadata()
.catch(err => {
// Catch errors
logger.warn("Failed to save:", err);
})
.then(() => {
// Clear promise
logger.log("Saved!");
this.core.root.signals.gameSaved.dispatch();
this.currentSavePromise = null;
});
return this.currentSavePromise;
}
}
import { APPLICATION_ERROR_OCCURED } from "../core/error_handler";
import { GameState } from "../core/game_state";
import { logSection, createLogger } from "../core/logging";
import { waitNextFrame } from "../core/utils";
import { globalConfig } from "../core/config";
import { GameLoadingOverlay } from "../game/game_loading_overlay";
import { KeyActionMapper } from "../game/key_action_mapper";
import { Savegame } from "../savegame/savegame";
import { GameCore } from "../game/core";
import { MUSIC } from "../platform/sound";
import { enumGameModeIds } from "../game/game_mode";
const logger = createLogger("state/ingame");
// Different sub-states
const stages = {
s3_createCore: "🌈 3: Create core",
s4_A_initEmptyGame: "🌈 4/A: Init empty game",
s4_B_resumeGame: "🌈 4/B: Resume game",
s5_firstUpdate: "🌈 5: First game update",
s6_postLoadHook: "🌈 6: Post load hook",
s7_warmup: "🌈 7: Warmup",
s10_gameRunning: "🌈 10: Game finally running",
leaving: "🌈 Saving, then leaving the game",
destroyed: "🌈 DESTROYED: Core is empty and waits for state leave",
initFailed: "🌈 ERROR: Initialization failed!",
};
export const gameCreationAction = {
new: "new-game",
resume: "resume-game",
};
// Typehints
export class GameCreationPayload {
constructor() {
/** @type {boolean|undefined} */
this.fastEnter;
/** @type {string} */
this.gameModeId;
/** @type {Savegame} */
this.savegame;
/** @type {object|undefined} */
this.gameModeParameters;
/** @type {number} */
this.seed;
/** @type {boolean} */
this.allowNonPrimaryColors;
/** @type {number} */
this.fullShapePercentage;
/** @type {number} */
this.wierdShapePercentage;
}
}
export class InGameState extends GameState {
constructor() {
super("InGameState");
/** @type {GameCreationPayload} */
this.creationPayload = null;
// Stores current stage
this.stage = "";
/** @type {GameCore} */
this.core = null;
/** @type {KeyActionMapper} */
this.keyActionMapper = null;
/** @type {GameLoadingOverlay} */
this.loadingOverlay = null;
/** @type {Savegame} */
this.savegame = null;
/** @type {number} */
this.seed = null;
/** @type {boolean} */
this.allowNonPrimaryColors = null;
/** @type {number} */
this.fullShapePercentage = null;
/** @type {number} */
this.wierdShapePercentage = null;
this.boundInputFilter = this.filterInput.bind(this);
/**
* Whether we are currently saving the game
* @TODO: This doesn't realy fit here
*/
this.currentSavePromise = null;
}
/**
* Switches the game into another sub-state
* @param {string} stage
*/
switchStage(stage) {
assert(stage, "Got empty stage");
if (stage !== this.stage) {
this.stage = stage;
logger.log(this.stage);
return true;
} else {
// log(this, "Re entering", stage);
return false;
}
}
// GameState implementation
getInnerHTML() {
return "";
}
getThemeMusic() {
if (this.creationPayload.gameModeId && this.creationPayload.gameModeId.includes("puzzle")) {
return MUSIC.puzzle;
}
return MUSIC.theme;
}
onBeforeExit() {
// logger.log("Saving before quitting");
// return this.doSave().then(() => {
// logger.log(this, "Successfully saved");
// // this.stageDestroyed();
// });
}
onAppPause() {
// if (this.stage === stages.s10_gameRunning) {
// logger.log("Saving because app got paused");
// this.doSave();
// }
}
getHasFadeIn() {
return false;
}
getPauseOnFocusLost() {
return false;
}
getHasUnloadConfirmation() {
return true;
}
onLeave() {
if (this.core) {
this.stageDestroyed();
}
this.app.inputMgr.dismountFilter(this.boundInputFilter);
}
onResized(w, h) {
super.onResized(w, h);
if (this.stage === stages.s10_gameRunning) {
this.core.resize(w, h);
}
}
// ---- End of GameState implementation
/**
* Goes back to the menu state
*/
goBackToMenu() {
if ([enumGameModeIds.puzzleEdit, enumGameModeIds.puzzlePlay].includes(this.gameModeId)) {
this.saveThenGoToState("PuzzleMenuState");
} else {
this.saveThenGoToState("MainMenuState");
}
}
/**
* Goes back to the settings state
*/
goToSettings() {
this.saveThenGoToState("SettingsState", {
backToStateId: this.key,
backToStatePayload: this.creationPayload,
});
}
/**
* Goes back to the settings state
*/
goToKeybindings() {
this.saveThenGoToState("KeybindingsState", {
backToStateId: this.key,
backToStatePayload: this.creationPayload,
});
}
/**
* Moves to a state outside of the game
* @param {string} stateId
* @param {any=} payload
*/
saveThenGoToState(stateId, payload) {
if (this.stage === stages.leaving || this.stage === stages.destroyed) {
logger.warn(
"Tried to leave game twice or during destroy:",
this.stage,
"(attempted to move to",
stateId,
")"
);
return;
}
this.stageLeavingGame();
this.doSave().then(() => {
this.stageDestroyed();
this.moveToState(stateId, payload);
});
}
onBackButton() {
// do nothing
}
/**
* Called when the game somehow failed to initialize. Resets everything to basic state and
* then goes to the main menu, showing the error
* @param {string} err
*/
onInitializationFailure(err) {
if (this.switchStage(stages.initFailed)) {
logger.error("Init failure:", err);
this.stageDestroyed();
this.moveToState("MainMenuState", { loadError: err });
}
}
// STAGES
/**
* Creates the game core instance, and thus the root
*/
stage3CreateCore() {
if (this.switchStage(stages.s3_createCore)) {
logger.log("Creating new game core");
this.core = new GameCore(this.app);
this.core.initializeRoot(this, this.savegame, this.gameModeId);
if (this.savegame.hasGameDump()) {
this.stage4bResumeGame();
} else {
this.app.gameAnalytics.handleGameStarted();
this.stage4aInitEmptyGame();
}
}
}
/**
* Initializes a new empty game
*/
stage4aInitEmptyGame() {
if (this.switchStage(stages.s4_A_initEmptyGame)) {
this.core.initNewGame({
seed: this.seed,
allowNonPrimaryColors: this.allowNonPrimaryColors,
fullShapePercentage: this.fullShapePercentage,
wierdShapePercentage: this.wierdShapePercentage,
});
this.stage5FirstUpdate();
}
}
/**
* Resumes an existing game
*/
stage4bResumeGame() {
if (this.switchStage(stages.s4_B_resumeGame)) {
if (!this.core.initExistingGame()) {
this.onInitializationFailure("Savegame is corrupt and can not be restored.");
return;
}
this.app.gameAnalytics.handleGameResumed();
this.stage5FirstUpdate();
}
}
/**
* Performs the first game update on the game which initializes most caches
*/
stage5FirstUpdate() {
if (this.switchStage(stages.s5_firstUpdate)) {
this.core.root.logicInitialized = true;
this.core.updateLogic();
this.stage6PostLoadHook();
}
}
/**
* Call the post load hook, this means that we have loaded the game, and all systems
* can operate and start to work now.
*/
stage6PostLoadHook() {
if (this.switchStage(stages.s6_postLoadHook)) {
logger.log("Post load hook");
this.core.postLoadHook();
this.stage7Warmup();
}
}
/**
* This makes the game idle and draw for a while, because we run most code this way
* the V8 engine can already start to optimize it. Also this makes sure the resources
* are in the VRAM and we have a smooth experience once we start.
*/
stage7Warmup() {
if (this.switchStage(stages.s7_warmup)) {
if (this.creationPayload.fastEnter) {
this.warmupTimeSeconds = globalConfig.warmupTimeSecondsFast;
} else {
this.warmupTimeSeconds = globalConfig.warmupTimeSecondsRegular;
}
}
}
/**
* The final stage where this game is running and updating regulary.
*/
stage10GameRunning() {
if (this.switchStage(stages.s10_gameRunning)) {
this.core.root.signals.readyToRender.dispatch();
logSection("GAME STARTED", "#26a69a");
// Initial resize, might have changed during loading (this is possible)
this.core.resize(this.app.screenWidth, this.app.screenHeight);
}
}
/**
* This stage destroys the whole game, used to cleanup
*/
stageDestroyed() {
if (this.switchStage(stages.destroyed)) {
// Cleanup all api calls
this.cancelAllAsyncOperations();
if (this.syncer) {
this.syncer.cancelSync();
this.syncer = null;
}
// Cleanup core
if (this.core) {
this.core.destruct();
this.core = null;
}
}
}
/**
* When leaving the game
*/
stageLeavingGame() {
if (this.switchStage(stages.leaving)) {
// ...
}
}
// END STAGES
/**
* Filters the input (keybindings)
*/
filterInput() {
return this.stage === stages.s10_gameRunning;
}
/**
* @param {GameCreationPayload} payload
*/
onEnter(payload) {
this.app.inputMgr.installFilter(this.boundInputFilter);
this.creationPayload = payload;
this.savegame = payload.savegame;
this.gameModeId = payload.gameModeId;
this.seed = payload.seed;
this.allowNonPrimaryColors = payload.allowNonPrimaryColors;
this.fullShapePercentage = payload.fullShapePercentage;
this.wierdShapePercentage = payload.wierdShapePercentage;
this.loadingOverlay = new GameLoadingOverlay(this.app, this.getDivElement());
this.loadingOverlay.showBasic();
// Remove unneded default element
document.body.querySelector(".modalDialogParent").remove();
this.asyncChannel
.watch(waitNextFrame())
.then(() => this.stage3CreateCore())
.catch(ex => {
logger.error(ex);
throw ex;
});
}
/**
* Render callback
* @param {number} dt
*/
onRender(dt) {
if (APPLICATION_ERROR_OCCURED) {
// Application somehow crashed, do not do anything
return;
}
if (this.stage === stages.s7_warmup) {
this.core.draw();
this.warmupTimeSeconds -= dt / 1000.0;
if (this.warmupTimeSeconds < 0) {
logger.log("Warmup completed");
this.stage10GameRunning();
}
}
if (this.stage === stages.s10_gameRunning) {
this.core.tick(dt);
}
// If the stage is still active (This might not be the case if tick() moved us to game over)
if (this.stage === stages.s10_gameRunning) {
// Only draw if page visible
if (this.app.pageVisible) {
this.core.draw();
}
this.loadingOverlay.removeIfAttached();
} else {
if (!this.loadingOverlay.isAttached()) {
this.loadingOverlay.showBasic();
}
}
}
onBackgroundTick(dt) {
this.onRender(dt);
}
/**
* Saves the game
*/
doSave() {
if (!this.savegame || !this.savegame.isSaveable()) {
return Promise.resolve();
}
if (APPLICATION_ERROR_OCCURED) {
logger.warn("skipping save because application crashed");
return Promise.resolve();
}
if (
this.stage !== stages.s10_gameRunning &&
this.stage !== stages.s7_warmup &&
this.stage !== stages.leaving
) {
logger.warn("Skipping save because game is not ready");
return Promise.resolve();
}
if (this.currentSavePromise) {
logger.warn("Skipping double save and returning same promise");
return this.currentSavePromise;
}
if (!this.core.root.gameMode.getIsSaveable()) {
return Promise.resolve();
}
logger.log("Starting to save game ...");
this.savegame.updateData(this.core.root);
this.currentSavePromise = this.savegame
.writeSavegameAndMetadata()
.catch(err => {
// Catch errors
logger.warn("Failed to save:", err);
})
.then(() => {
// Clear promise
logger.log("Saved!");
this.core.root.signals.gameSaved.dispatch();
this.currentSavePromise = null;
});
return this.currentSavePromise;
}
}

View File

@ -3,7 +3,7 @@ import { cachebust } from "../core/cachebust";
import { A_B_TESTING_LINK_TYPE, globalConfig, THIRDPARTY_URLS } from "../core/config";
import { GameState } from "../core/game_state";
import { DialogWithForm } from "../core/modal_dialog_elements";
import { FormElementInput } from "../core/modal_dialog_forms";
import { FormElementCheckbox, FormElementDetails, FormElementInput } from "../core/modal_dialog_forms";
import { ReadWriteProxy } from "../core/read_write_proxy";
import {
formatSecondsToTimeAgo,
@ -12,6 +12,7 @@ import {
makeButton,
makeButtonElement,
makeDiv,
randomInt,
removeAllChildren,
startFileChoose,
waitNextFrame,
@ -672,14 +673,96 @@ export class MainMenuState extends GameState {
return;
}
this.app.analytics.trackUiClick("startgame");
this.app.adProvider.showVideoAd().then(() => {
const savegame = this.app.savegameMgr.createNewSavegame();
const regex = /^[a-zA-Z0-9_\- ]{1,20}$/;
this.moveToState("InGameState", {
savegame,
const nameInput = new FormElementInput({
id: "nameInput",
// @TODO: Add translation (T.dialogs.newSavegame.nameInputLabel)
label: "Name:",
placeholder: "",
defaultValue: "Unnamed",
validator: val => val.match(regex) && trim(val).length > 0,
inline: true,
});
const seedInput = new FormElementInput({
id: "seedInput",
// @TODO: Add translation (T.dialogs.newSavegame.seedInputLabel)
label: "Seed:",
placeholder: "",
defaultValue: randomInt(0, 100000).toString(),
validator: val => Number.isInteger(Number(val)) && Number(val) >= 0 && Number(val) <= 100000,
inline: true,
});
const allowColorsCheckbox = new FormElementCheckbox({
id: "allowColorsCheckbox",
// @TODO: Add translation (T.dialogs.newSavegame.allowColorsCheckboxLabel)
label: "Allow non-primarycolors: ",
defaultValue: false,
inline: true,
});
const fullShapePercentageInput = new FormElementInput({
id: "fullShapePercentageInput",
label: "fullShape %:",
placeholder: "",
defaultValue: Number(0).toString(),
validator: val => Number.isInteger(Number(val)) && Number(val) >= 0 && Number(val) <= 100,
inline: true,
});
const wierdShapePercentageInput = new FormElementInput({
id: "wierdShapePercentageInput",
label: "wierdShape %:",
placeholder: "",
defaultValue: Number(0).toString(),
validator: val => Number.isInteger(Number(val)) && Number(val) >= 0 && Number(val) <= 100,
inline: true,
});
const advancedContainer = new FormElementDetails({
id: "advancedContainer",
// @TODO Add translation (T.dialogs.newSavegame.advanced)
label: "Advanced Options",
formElements: [
seedInput,
allowColorsCheckbox,
fullShapePercentageInput,
wierdShapePercentageInput,
],
});
const dialog = new DialogWithForm({
app: this.app,
// @TODO: Add translation (T.dialogs.newSavegame.title)
title: "New Game Options",
// @TODO: Add translation (T.dialogs.newSavegame.desc)
desc: "Configure your new savegame",
formElements: [nameInput, advancedContainer],
buttons: ["ok:good:enter"],
});
this.dialogs.internalShowDialog(dialog);
dialog.buttonSignals.ok.add(() => {
this.app.analytics.trackUiClick("startgame");
this.app.adProvider.showVideoAd().then(async () => {
const savegame = this.app.savegameMgr.createNewSavegame();
const savegameMetadata = this.app.savegameMgr.getGameMetaDataByInternalId(
savegame.internalId
);
savegameMetadata.name = trim(nameInput.getValue());
await this.app.savegameMgr.writeAsync();
this.moveToState("InGameState", {
savegame,
seed: Number(seedInput.getValue()),
allowNonPrimaryColors: allowColorsCheckbox.getValue(),
fullShapePercentage: Number(fullShapePercentageInput.getValue()),
wierdShapePercentage: Number(wierdShapePercentageInput.getValue()),
});
this.app.analytics.trackUiClick("startgame_adcomplete");
});
this.app.analytics.trackUiClick("startgame_adcomplete");
});
}