From b107ff9f247308215f12c8e462093831c7fa18bc Mon Sep 17 00:00:00 2001 From: Scott Anderson <662325+scottanderson@users.noreply.github.com> Date: Sun, 24 Aug 2025 15:59:43 -0400 Subject: [PATCH] format --- eslint.config.js | 53 +-- src/client/ClientGameRunner.ts | 58 +-- src/client/Cosmetics.ts | 6 +- src/client/DarkModeButton.ts | 2 +- src/client/FlagInput.ts | 4 +- src/client/FlagInputModal.ts | 17 +- src/client/GameStartingModal.ts | 2 +- src/client/GoogleAdElement.ts | 2 +- src/client/HelpModal.ts | 2 +- src/client/HostLobbyModal.ts | 84 ++-- src/client/InputHandler.ts | 2 +- src/client/JoinPrivateLobbyModal.ts | 34 +- src/client/LangSelector.ts | 24 +- src/client/LanguageModal.ts | 4 +- src/client/LocalPersistantStats.ts | 4 +- src/client/LocalServer.ts | 13 +- src/client/Main.ts | 38 +- src/client/NewsModal.ts | 4 +- src/client/PublicLobby.ts | 51 +-- src/client/SinglePlayerModal.ts | 82 ++-- src/client/TerrainMapFileLoader.ts | 2 +- src/client/TerritoryPatternsModal.ts | 70 ++-- src/client/Transport.ts | 10 +- src/client/UserSettingModal.ts | 45 ++- src/client/UsernameInput.ts | 18 +- src/client/Utils.ts | 2 +- src/client/components/Difficulties.ts | 2 +- src/client/components/Maps.ts | 14 +- src/client/components/ModalOverlay.ts | 2 +- src/client/components/NewsButton.ts | 13 +- .../components/baseComponents/Button.ts | 10 +- src/client/components/baseComponents/Modal.ts | 24 +- .../baseComponents/setting/SettingKeybind.ts | 2 +- .../baseComponents/setting/SettingNumber.ts | 2 +- .../baseComponents/setting/SettingSlider.ts | 2 +- .../baseComponents/setting/SettingToggle.ts | 2 +- src/client/graphics/AnimatedSpriteLoader.ts | 21 +- src/client/graphics/GameRenderer.ts | 14 +- src/client/graphics/SpriteLoader.ts | 8 +- src/client/graphics/TransformHandler.ts | 6 +- src/client/graphics/fx/ConquestFx.ts | 8 +- src/client/graphics/fx/NukeFx.ts | 6 +- src/client/graphics/fx/SpriteFx.ts | 6 +- src/client/graphics/fx/UnitExplosionFx.ts | 4 +- src/client/graphics/layers/AlertFrame.ts | 6 +- src/client/graphics/layers/BuildMenu.ts | 72 ++-- src/client/graphics/layers/ChatDisplay.ts | 40 +- src/client/graphics/layers/ChatIntegration.ts | 6 +- src/client/graphics/layers/ChatModal.ts | 67 ++-- src/client/graphics/layers/ControlPanel.ts | 36 +- src/client/graphics/layers/EmojiTable.ts | 18 +- src/client/graphics/layers/EventsDisplay.ts | 374 ++++++++++-------- src/client/graphics/layers/FPSDisplay.ts | 6 +- src/client/graphics/layers/FxLayer.ts | 14 +- src/client/graphics/layers/GameLeftSidebar.ts | 42 +- .../graphics/layers/GameRightSidebar.ts | 18 +- src/client/graphics/layers/GutterAdModal.ts | 6 +- src/client/graphics/layers/HeadsUpMessage.ts | 4 +- src/client/graphics/layers/Leaderboard.ts | 59 +-- src/client/graphics/layers/MainRadialMenu.ts | 54 ++- src/client/graphics/layers/MultiTabModal.ts | 4 +- src/client/graphics/layers/NameLayer.ts | 26 +- src/client/graphics/layers/OptionsMenu.ts | 13 +- .../graphics/layers/PlayerActionHandler.ts | 6 +- .../graphics/layers/PlayerInfoOverlay.ts | 80 ++-- src/client/graphics/layers/PlayerPanel.ts | 156 +++++--- src/client/graphics/layers/RadialMenu.ts | 51 ++- .../graphics/layers/RadialMenuElements.ts | 26 +- src/client/graphics/layers/RailroadLayer.ts | 10 +- src/client/graphics/layers/ReplayPanel.ts | 26 +- src/client/graphics/layers/SettingsModal.ts | 150 ++++--- src/client/graphics/layers/SpawnAd.ts | 16 +- src/client/graphics/layers/SpawnTimer.ts | 2 +- .../graphics/layers/StructureIconsLayer.ts | 32 +- src/client/graphics/layers/StructureLayer.ts | 22 +- src/client/graphics/layers/TeamStats.ts | 16 +- src/client/graphics/layers/TerrainLayer.ts | 4 +- src/client/graphics/layers/TerritoryLayer.ts | 40 +- src/client/graphics/layers/UILayer.ts | 17 +- src/client/graphics/layers/UnitDisplay.ts | 26 +- src/client/graphics/layers/UnitLayer.ts | 44 ++- src/client/graphics/layers/WinModal.ts | 6 +- src/client/jwt.ts | 4 +- src/client/styles.css | 61 +-- src/client/utilities/RenderUnitTypeOptions.ts | 4 +- src/core/ApiSchemas.ts | 3 +- src/core/CosmeticSchemas.ts | 2 +- src/core/CustomFlag.ts | 8 +- src/core/EventBus.ts | 6 +- src/core/ExpressSchemas.ts | 3 +- src/core/GameRunner.ts | 36 +- src/core/Schemas.ts | 12 +- src/core/StatsSchemas.ts | 2 +- src/core/Util.ts | 17 +- src/core/WorkerSchemas.ts | 3 +- src/core/configuration/ColorAllocator.ts | 11 +- src/core/configuration/Config.ts | 8 +- src/core/configuration/ConfigLoader.ts | 8 +- src/core/configuration/DefaultConfig.ts | 17 +- src/core/configuration/DevConfig.ts | 6 +- src/core/configuration/PastelTheme.ts | 21 +- src/core/configuration/PastelThemeDark.ts | 21 +- src/core/configuration/PreprodConfig.ts | 2 +- src/core/configuration/ProdConfig.ts | 2 +- src/core/execution/AttackExecution.ts | 19 +- src/core/execution/BotExecution.ts | 2 +- src/core/execution/BotSpawner.ts | 8 +- src/core/execution/ConstructionExecution.ts | 5 +- src/core/execution/DefensePostExecution.ts | 2 +- src/core/execution/ExecutionManager.ts | 10 +- src/core/execution/FakeHumanExecution.ts | 37 +- src/core/execution/MIRVExecution.ts | 6 +- src/core/execution/NukeExecution.ts | 8 +- src/core/execution/PlayerExecution.ts | 4 +- src/core/execution/PortExecution.ts | 2 +- src/core/execution/RailroadExecution.ts | 8 +- src/core/execution/SAMLauncherExecution.ts | 4 +- src/core/execution/SAMMissileExecution.ts | 4 +- src/core/execution/ShellExecution.ts | 4 +- src/core/execution/SpawnExecution.ts | 2 +- src/core/execution/TradeShipExecution.ts | 4 +- src/core/execution/TrainExecution.ts | 4 +- src/core/execution/TrainStationExecution.ts | 2 +- src/core/execution/TransportShipExecution.ts | 6 +- src/core/execution/Util.ts | 2 +- src/core/execution/WarshipExecution.ts | 17 +- src/core/execution/WinCheckExecution.ts | 2 +- src/core/execution/utils/BotBehavior.ts | 6 +- src/core/game/AllianceRequestImpl.ts | 2 +- src/core/game/AttackImpl.ts | 2 +- src/core/game/BinaryLoaderGameMapLoader.ts | 2 +- src/core/game/FetchGameMapLoader.ts | 2 +- src/core/game/Game.ts | 2 +- src/core/game/GameImpl.ts | 19 +- src/core/game/GameView.ts | 34 +- src/core/game/PlayerImpl.ts | 33 +- src/core/game/RailNetwork.ts | 2 +- src/core/game/RailNetworkImpl.ts | 12 +- src/core/game/Railroad.ts | 2 +- src/core/game/Stats.ts | 2 +- src/core/game/StatsImpl.ts | 2 +- src/core/game/TeamAssignment.ts | 2 +- src/core/game/TerrainMapLoader.ts | 7 +- src/core/game/TrainStation.ts | 12 +- src/core/game/TransportShipUtils.ts | 6 +- src/core/game/UnitGrid.ts | 2 +- src/core/game/UnitImpl.ts | 6 +- src/core/pathfinding/AStar.ts | 20 +- src/core/pathfinding/MiniAStar.ts | 6 +- src/core/pathfinding/PathFinding.ts | 8 +- src/core/pathfinding/SerialAStar.ts | 5 +- src/core/validations/username.ts | 4 +- src/core/worker/Worker.worker.ts | 8 +- src/core/worker/WorkerClient.ts | 11 +- src/core/worker/WorkerMessages.ts | 4 +- src/server/Archive.ts | 4 +- src/server/Client.ts | 6 +- src/server/Cloudflare.ts | 10 +- src/server/GameManager.ts | 8 +- src/server/GameServer.ts | 19 +- src/server/Gatekeeper.ts | 2 +- src/server/Logger.ts | 9 +- src/server/MapPlaylist.ts | 8 +- src/server/Master.ts | 26 +- src/server/OtelResource.ts | 2 +- src/server/PrivilegeRefresher.ts | 6 +- src/server/Server.ts | 6 +- src/server/Worker.ts | 44 +-- src/server/WorkerMetrics.ts | 11 +- src/server/jwt.ts | 12 +- .../handler/message/PostJoinHandler.ts | 8 +- .../handler/message/PreJoinHandler.ts | 44 +-- tests/AllianceExtensionExecution.test.ts | 4 +- tests/Attack.test.ts | 10 +- tests/AttackStats.test.ts | 4 +- tests/BotBehavior.test.ts | 4 +- tests/Censor.test.ts | 4 +- tests/Colors.test.ts | 2 +- tests/DeleteUnitExecution.test.ts | 4 +- tests/Disconnected.test.ts | 4 +- tests/Donate.test.ts | 2 +- tests/MissileSilo.test.ts | 8 +- tests/ShellRandom.test.ts | 6 +- tests/TerritoryCapture.test.ts | 2 +- tests/Warship.test.ts | 6 +- .../graphics/RadialMenuElements.test.ts | 10 +- tests/core/executions/NukeExecution.test.ts | 4 +- .../executions/SAMLauncherExecution.test.ts | 10 +- .../executions/TradeShipExecution.test.ts | 2 +- tests/core/game/GameImpl.test.ts | 8 +- tests/core/game/RailNetwork.test.ts | 9 +- tests/core/game/TrainStation.test.ts | 4 +- tests/perf/AstarPerf.ts | 2 +- tests/util/Setup.ts | 12 +- tests/util/TestConfig.ts | 4 +- tests/util/TestServerConfig.ts | 6 +- tests/util/utils.ts | 2 +- webpack.config.js | 188 ++++----- 198 files changed, 1928 insertions(+), 1634 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 09cc9d80c..67ac514c6 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,12 +1,12 @@ -import eslintPluginLocal from "./eslint-plugin-local/plugin.js"; -import { fileURLToPath } from "node:url"; -import globals from "globals"; -import { includeIgnoreFile } from "@eslint/compat"; -import jest from "eslint-plugin-jest"; import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { includeIgnoreFile } from "@eslint/compat"; import pluginJs from "@eslint/js"; import stylistic from "@stylistic/eslint-plugin"; +import jest from "eslint-plugin-jest"; +import globals from "globals"; import tseslint from "typescript-eslint"; +import eslintPluginLocal from "./eslint-plugin-local/plugin.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -100,7 +100,10 @@ export default [ "function-call-argument-newline": ["error", "consistent"], "max-depth": ["error", { max: 5 }], "max-len": ["error", { code: 120 }], - "max-lines": ["error", { max: 676, skipBlankLines: true, skipComments: true }], + "max-lines": [ + "error", + { max: 676, skipBlankLines: true, skipComments: true }, + ], "max-lines-per-function": ["error", { max: 561 }], "no-loss-of-precision": "error", "no-multi-spaces": "error", @@ -108,21 +111,30 @@ export default [ "no-trailing-spaces": "error", "object-curly-newline": ["error", { multiline: true, consistent: true }], "object-curly-spacing": ["error", "always"], - "object-property-newline": ["error", { allowAllPropertiesOnSameLine: true }], + "object-property-newline": [ + "error", + { allowAllPropertiesOnSameLine: true }, + ], "object-shorthand": ["error", "always"], "no-undef": "error", "no-unused-vars": "off", // @typescript-eslint/no-unused-vars - "prefer-destructuring": ["error", { - array: false, - object: true, - }], + "prefer-destructuring": [ + "error", + { + array: false, + object: true, + }, + ], "quote-props": ["error", "consistent-as-needed"], "space-before-blocks": ["error", "always"], - "space-before-function-paren": ["error", { - anonymous: "always", - named: "never", - asyncArrow: "always", - }], + "space-before-function-paren": [ + "error", + { + anonymous: "always", + named: "never", + asyncArrow: "always", + }, + ], "space-infix-ops": "off", }, }, @@ -150,17 +162,12 @@ export default [ ...globals.jest, }, }, - files: [ - "**/*.test.{js,ts,jsx,tsx}", - "tests/**/*.{js,ts,jsx,tsx}", - ], + files: ["**/*.test.{js,ts,jsx,tsx}", "tests/**/*.{js,ts,jsx,tsx}"], plugins: ["jest"], ...jest.configs["flat/style"], }, { - files: [ - "src/client/**/*.{js,ts,jsx,tsx}", - ], + files: ["src/client/**/*.{js,ts,jsx,tsx}"], rules: { // Disabled rules for frontend "sort-keys": "off", diff --git a/src/client/ClientGameRunner.ts b/src/client/ClientGameRunner.ts index ab29a1b78..6ec54a2fe 100644 --- a/src/client/ClientGameRunner.ts +++ b/src/client/ClientGameRunner.ts @@ -1,11 +1,20 @@ +import { translateText } from "../client/Utils"; +import { ServerConfig } from "../core/configuration/Config"; +import { getConfig } from "../core/configuration/ConfigLoader"; +import { EventBus } from "../core/EventBus"; +import { PlayerActions, UnitType } from "../core/game/Game"; +import { TileRef } from "../core/game/GameMap"; +import { GameMapLoader } from "../core/game/GameMapLoader"; import { - AutoUpgradeEvent, - DoBoatAttackEvent, - DoGroundAttackEvent, - InputHandler, - MouseMoveEvent, - MouseUpEvent, -} from "./InputHandler"; + ErrorUpdate, + GameUpdateType, + GameUpdateViewData, + HashUpdate, + WinUpdate, +} from "../core/game/GameUpdates"; +import { GameView, PlayerView } from "../core/game/GameView"; +import { loadTerrainMap, TerrainMapData } from "../core/game/TerrainMapLoader"; +import { UserSettings } from "../core/game/UserSettings"; import { ClientID, GameID, @@ -14,16 +23,20 @@ import { PlayerRecord, ServerMessage, } from "../core/Schemas"; +import { createGameRecord } from "../core/Util"; +import { WorkerClient } from "../core/worker/WorkerClient"; +import { createRenderer, GameRenderer } from "./graphics/GameRenderer"; import { - ErrorUpdate, - GameUpdateType, - GameUpdateViewData, - HashUpdate, - WinUpdate, -} from "../core/game/GameUpdates"; -import { GameRenderer, createRenderer } from "./graphics/GameRenderer"; -import { GameView, PlayerView } from "../core/game/GameView"; -import { PlayerActions, UnitType } from "../core/game/Game"; + AutoUpgradeEvent, + DoBoatAttackEvent, + DoGroundAttackEvent, + InputHandler, + MouseMoveEvent, + MouseUpEvent, +} from "./InputHandler"; +import { endGame, startGame, startTime } from "./LocalPersistantStats"; +import { getPersistentID } from "./Main"; +import { terrainMapFileLoader } from "./TerrainMapFileLoader"; import { SendAttackIntentEvent, SendBoatAttackIntentEvent, @@ -32,20 +45,7 @@ import { SendUpgradeStructureIntentEvent, Transport, } from "./Transport"; -import { TerrainMapData, loadTerrainMap } from "../core/game/TerrainMapLoader"; -import { endGame, startGame, startTime } from "./LocalPersistantStats"; -import { EventBus } from "../core/EventBus"; -import { GameMapLoader } from "../core/game/GameMapLoader"; -import { ServerConfig } from "../core/configuration/Config"; -import { TileRef } from "../core/game/GameMap"; -import { UserSettings } from "../core/game/UserSettings"; -import { WorkerClient } from "../core/worker/WorkerClient"; import { createCanvas } from "./Utils"; -import { createGameRecord } from "../core/Util"; -import { getConfig } from "../core/configuration/ConfigLoader"; -import { getPersistentID } from "./Main"; -import { terrainMapFileLoader } from "./TerrainMapFileLoader"; -import { translateText } from "../client/Utils"; export type LobbyConfig = { serverConfig: ServerConfig; diff --git a/src/client/Cosmetics.ts b/src/client/Cosmetics.ts index be185cee4..6e65e8d9a 100644 --- a/src/client/Cosmetics.ts +++ b/src/client/Cosmetics.ts @@ -1,10 +1,10 @@ -import { Cosmetics, CosmeticsSchema, Pattern } from "../core/CosmeticSchemas"; +import { z } from "zod"; import { StripeCreateCheckoutSessionResponseSchema, UserMeResponse, } from "../core/ApiSchemas"; +import { Cosmetics, CosmeticsSchema, Pattern } from "../core/CosmeticSchemas"; import { getApiBase, getAuthHeader } from "./jwt"; -import { z } from "zod"; export async function patterns( userMe: UserMeResponse | null, @@ -41,7 +41,7 @@ export async function handlePurchase(priceId: string) { method: "POST", headers: { "Content-Type": "application/json", - "authorization": getAuthHeader(), + authorization: getAuthHeader(), }, body: JSON.stringify({ priceId, diff --git a/src/client/DarkModeButton.ts b/src/client/DarkModeButton.ts index e3544f8ff..e4a920013 100644 --- a/src/client/DarkModeButton.ts +++ b/src/client/DarkModeButton.ts @@ -1,4 +1,4 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; import { UserSettings } from "../core/game/UserSettings"; diff --git a/src/client/FlagInput.ts b/src/client/FlagInput.ts index e5aeabc21..5ca313364 100644 --- a/src/client/FlagInput.ts +++ b/src/client/FlagInput.ts @@ -1,7 +1,7 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; -import { FlagSchema } from "../core/Schemas"; import { renderPlayerFlag } from "../core/CustomFlag"; +import { FlagSchema } from "../core/Schemas"; const flagKey = "flag"; diff --git a/src/client/FlagInputModal.ts b/src/client/FlagInputModal.ts index c207383ed..7497eafbb 100644 --- a/src/client/FlagInputModal.ts +++ b/src/client/FlagInputModal.ts @@ -1,4 +1,4 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, query, state } from "lit/decorators.js"; import Countries from "./data/countries.json"; @@ -33,10 +33,13 @@ export class FlagInputModal extends LitElement {
- ${this.isModalOpen ? Countries.filter( - (country) => !country.restricted && this.includedInSearch(country), - ).map( - (country) => html` + ${ + this.isModalOpen + ? Countries.filter( + (country) => + !country.restricted && this.includedInSearch(country), + ).map( + (country) => html` `, - ) : html``} + ) + : html`` + }
`; diff --git a/src/client/GameStartingModal.ts b/src/client/GameStartingModal.ts index 9ae0ad232..0ec37e28d 100644 --- a/src/client/GameStartingModal.ts +++ b/src/client/GameStartingModal.ts @@ -1,4 +1,4 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; import { translateText } from "./Utils"; diff --git a/src/client/GoogleAdElement.ts b/src/client/GoogleAdElement.ts index 2d22d33bc..4424fa042 100644 --- a/src/client/GoogleAdElement.ts +++ b/src/client/GoogleAdElement.ts @@ -1,4 +1,4 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, property } from "lit/decorators.js"; declare global { diff --git a/src/client/HelpModal.ts b/src/client/HelpModal.ts index e7ec2d181..7b9919d8c 100644 --- a/src/client/HelpModal.ts +++ b/src/client/HelpModal.ts @@ -1,6 +1,6 @@ import "./components/Difficulties"; import "./components/Maps"; -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, query } from "lit/decorators.js"; import { getAltKey, getModifierKey, translateText } from "../client/Utils"; diff --git a/src/client/HostLobbyModal.ts b/src/client/HostLobbyModal.ts index b4d2b4179..b950ae375 100644 --- a/src/client/HostLobbyModal.ts +++ b/src/client/HostLobbyModal.ts @@ -2,6 +2,22 @@ import "./components/Difficulties"; import "./components/Maps"; import "./components/baseComponents/Modal"; +import { html, LitElement } from "lit"; +import { customElement, query, state } from "lit/decorators.js"; +import randomMap from "../../resources/images/RandomMap.webp"; +import { translateText } from "../client/Utils"; +import { getServerConfigFromClient } from "../core/configuration/ConfigLoader"; +import { + Difficulty, + Duos, + GameMapType, + GameMode, + mapCategories, + Quads, + Trios, + UnitType, +} from "../core/game/Game"; +import { UserSettings } from "../core/game/UserSettings"; import { ClientInfo, GameConfig, @@ -9,26 +25,10 @@ import { GameInfoSchema, TeamCountConfig, } from "../core/Schemas"; -import { - Difficulty, - Duos, - GameMapType, - GameMode, - Quads, - Trios, - UnitType, - mapCategories, -} from "../core/game/Game"; -import { LitElement, html } from "lit"; -import { customElement, query, state } from "lit/decorators.js"; +import { generateID } from "../core/Util"; import { DifficultyDescription } from "./components/Difficulties"; import { JoinLobbyEvent } from "./Main"; -import { UserSettings } from "../core/game/UserSettings"; -import { generateID } from "../core/Util"; -import { getServerConfigFromClient } from "../core/configuration/ConfigLoader"; -import randomMap from "../../resources/images/RandomMap.webp"; import { renderUnitTypeOptions } from "./utilities/RenderUnitTypeOptions"; -import { translateText } from "../client/Utils"; @customElement("host-lobby-modal") export class HostLobbyModal extends LitElement { @@ -206,8 +206,10 @@ export class HostLobbyModal extends LitElement { > html`
this.handleDifficultySelection(value)} > html`
this.handleTeamCountSelection(o)} >
- ${typeof o === "string" - ? translateText(`public_lobby.teams_${o}`) - : translateText("public_lobby.teams", { - num: o, - })} + ${ + typeof o === "string" + ? translateText(`public_lobby.teams_${o}`) + : translateText("public_lobby.teams", { + num: o, + }) + }
`, @@ -457,9 +461,9 @@ export class HostLobbyModal extends LitElement { style="display: flex; flex-wrap: wrap; justify-content: center; gap: 12px;" > ${renderUnitTypeOptions({ - disabledUnits: this.disabledUnits, - toggleUnit: this.toggleUnit.bind(this), - })} + disabledUnits: this.disabledUnits, + toggleUnit: this.toggleUnit.bind(this), + })}
@@ -482,11 +486,12 @@ export class HostLobbyModal extends LitElement { (client) => html` ${client.username} - ${client.clientID === this.lobbyCreatorClientID - ? html`(${translateText("host_modal.host_badge")})` - : html` + : html` - `} + ` + } `, )} @@ -695,8 +701,8 @@ export class HostLobbyModal extends LitElement { await this.putGameConfig(); console.log( `Starting private game with map: ${ - GameMapType[this.selectedMap as keyof typeof GameMapType]} ${ - this.useRandomMap ? " (Randomly selected)" : ""}`, + GameMapType[this.selectedMap as keyof typeof GameMapType] + } ${this.useRandomMap ? " (Randomly selected)" : ""}`, ); this.close(); const config = await getServerConfigFromClient(); diff --git a/src/client/InputHandler.ts b/src/client/InputHandler.ts index 8ff2db2f0..563f934d6 100644 --- a/src/client/InputHandler.ts +++ b/src/client/InputHandler.ts @@ -1,8 +1,8 @@ import { EventBus, GameEvent } from "../core/EventBus"; -import { ReplaySpeedMultiplier } from "./utilities/ReplaySpeedMultiplier"; import { UnitType } from "../core/game/Game"; import { UnitView } from "../core/game/GameView"; import { UserSettings } from "../core/game/UserSettings"; +import { ReplaySpeedMultiplier } from "./utilities/ReplaySpeedMultiplier"; export class MouseUpEvent implements GameEvent { constructor( diff --git a/src/client/JoinPrivateLobbyModal.ts b/src/client/JoinPrivateLobbyModal.ts index ccedb0bd1..f16e3806f 100644 --- a/src/client/JoinPrivateLobbyModal.ts +++ b/src/client/JoinPrivateLobbyModal.ts @@ -1,16 +1,16 @@ import "./components/baseComponents/Button"; import "./components/baseComponents/Modal"; +import { html, LitElement } from "lit"; +import { customElement, query, state } from "lit/decorators.js"; +import { translateText } from "../client/Utils"; +import { getServerConfigFromClient } from "../core/configuration/ConfigLoader"; import { GameInfo, GameInfoSchema } from "../core/Schemas"; -import { LitElement, html } from "lit"; +import { getClientID } from "../core/Util"; import { WorkerApiArchivedGameLobbySchema, WorkerApiGameIdExistsSchema, } from "../core/WorkerSchemas"; -import { customElement, query, state } from "lit/decorators.js"; import { JoinLobbyEvent } from "./Main"; -import { getClientID } from "../core/Util"; -import { getServerConfigFromClient } from "../core/configuration/ConfigLoader"; -import { translateText } from "../client/Utils"; @customElement("join-private-lobby-modal") export class JoinPrivateLobbyModal extends LitElement { @@ -82,13 +82,16 @@ export class JoinPrivateLobbyModal extends LitElement { ${this.message}
- ${this.hasJoined && this.players.length > 0 - ? html`
+ ${ + this.hasJoined && this.players.length > 0 + ? html`
${this.players.length} - ${this.players.length === 1 - ? translateText("private_lobby.player") - : translateText("private_lobby.players")} + ${ + this.players.length === 1 + ? translateText("private_lobby.player") + : translateText("private_lobby.players") + }
@@ -97,16 +100,19 @@ export class JoinPrivateLobbyModal extends LitElement { )}
` - : ""} + : "" + }
- ${!this.hasJoined - ? html` ` - : ""} + : "" + }
`; diff --git a/src/client/LangSelector.ts b/src/client/LangSelector.ts index 445479717..fe2e9a98a 100644 --- a/src/client/LangSelector.ts +++ b/src/client/LangSelector.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ import "./LanguageModal"; -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; import ar from "../../resources/lang/ar.json"; @@ -289,16 +289,16 @@ export class LangSelector extends LitElement { this.languageList.find((l) => l.code === this.currentLang) ?? (this.currentLang === "debug" ? { - code: "debug", - native: "Debug", - en: "Debug", - svg: "xx", - } + code: "debug", + native: "Debug", + en: "Debug", + svg: "xx", + } : { - native: "English", - en: "English", - svg: "uk_us_flag", - }); + native: "English", + en: "English", + svg: "uk_us_flag", + }); return html`
@@ -327,7 +327,7 @@ export class LangSelector extends LitElement { .languageList=${this.languageList} .currentLang=${this.currentLang} @language-selected=${(e: CustomEvent) => - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this.changeLanguage(e.detail.lang)} @close-modal=${() => (this.showModal = false)} > @@ -348,7 +348,7 @@ function flattenTranslations( if (typeof value === "string") { result[fullKey] = value; } else if (value && typeof value === "object" && !Array.isArray(value)) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument flattenTranslations(value, fullKey, result); } else { console.warn("Unknown type", typeof value, value); diff --git a/src/client/LanguageModal.ts b/src/client/LanguageModal.ts index 4b5c5e34d..f9c1b2503 100644 --- a/src/client/LanguageModal.ts +++ b/src/client/LanguageModal.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property } from "lit/decorators.js"; import { translateText } from "../client/Utils"; @@ -111,7 +111,7 @@ export class LanguageModal extends LitElement {
` + }
@@ -149,17 +150,19 @@ export class PublicLobby extends LitElement {
- ${lobby.gameConfig.gameMode === GameMode.Team - ? typeof teamCount === "string" - ? translateText(`public_lobby.teams_${teamCount}`) - : translateText("public_lobby.teams", { - num: teamCount ?? 0, - }) - : translateText("game_mode.ffa")} ${translateText( diff --git a/src/client/SinglePlayerModal.ts b/src/client/SinglePlayerModal.ts index 577a9257f..25a70195d 100644 --- a/src/client/SinglePlayerModal.ts +++ b/src/client/SinglePlayerModal.ts @@ -2,29 +2,29 @@ import "./components/Difficulties"; import "./components/Maps"; import "./components/baseComponents/Button"; import "./components/baseComponents/Modal"; +import { html, LitElement } from "lit"; +import { customElement, query, state } from "lit/decorators.js"; +import randomMap from "../../resources/images/RandomMap.webp"; +import { translateText } from "../client/Utils"; import { Difficulty, Duos, GameMapType, GameMode, GameType, + mapCategories, Quads, Trios, UnitType, - mapCategories, } from "../core/game/Game"; -import { LitElement, html } from "lit"; -import { customElement, query, state } from "lit/decorators.js"; +import { UserSettings } from "../core/game/UserSettings"; +import { TeamCountConfig } from "../core/Schemas"; import { generateID, getClientID } from "../core/Util"; import { DifficultyDescription } from "./components/Difficulties"; import { FlagInput } from "./FlagInput"; import { JoinLobbyEvent } from "./Main"; -import { TeamCountConfig } from "../core/Schemas"; -import { UserSettings } from "../core/game/UserSettings"; import { UsernameInput } from "./UsernameInput"; -import randomMap from "../../resources/images/RandomMap.webp"; import { renderUnitTypeOptions } from "./utilities/RenderUnitTypeOptions"; -import { translateText } from "../client/Utils"; @customElement("single-player-modal") export class SinglePlayerModal extends LitElement { @@ -96,8 +96,10 @@ export class SinglePlayerModal extends LitElement { >
@@ -140,9 +142,9 @@ export class SinglePlayerModal extends LitElement { .map( ([key, value]) => html`
this.handleDifficultySelection(value)} > ${translateText("host_modal.mode")}
this.handleGameModeSelection(GameMode.FFA)} >
@@ -174,9 +176,9 @@ export class SinglePlayerModal extends LitElement {
this.handleGameModeSelection(GameMode.Team)} >
@@ -186,9 +188,10 @@ export class SinglePlayerModal extends LitElement {
- ${this.gameMode === GameMode.FFA - ? "" - : html` + ${ + this.gameMode === GameMode.FFA + ? "" + : html`
@@ -198,22 +201,27 @@ export class SinglePlayerModal extends LitElement { ${[2, 3, 4, 5, 6, 7, Quads, Trios, Duos].map( (o) => html`
this.handleTeamCountSelection(o)} >
- ${typeof o === "string" - ? translateText(`public_lobby.teams_${o}`) - : translateText("public_lobby.teams", { num: o })} + ${ + typeof o === "string" + ? translateText(`public_lobby.teams_${o}`) + : translateText("public_lobby.teams", { + num: o, + }) + }
`, )}
- `} + ` + }
@@ -233,10 +241,11 @@ export class SinglePlayerModal extends LitElement { .value="${String(this.bots)}" />
- ${translateText("single_modal.bots")}${this - .bots === 0 - ? translateText("single_modal.bots_disabled") - : this.bots} + ${translateText("single_modal.bots")}${ + this.bots === 0 + ? translateText("single_modal.bots_disabled") + : this.bots + }
@@ -410,7 +419,8 @@ export class SinglePlayerModal extends LitElement { } console.log( - `Starting single player game with map: ${GameMapType[this.selectedMap as keyof typeof GameMapType] + `Starting single player game with map: ${ + GameMapType[this.selectedMap as keyof typeof GameMapType] }${this.useRandomMap ? " (Randomly selected)" : ""}`, ); const gameID = generateID(); diff --git a/src/client/TerrainMapFileLoader.ts b/src/client/TerrainMapFileLoader.ts index 40be9b4db..b3c335dd6 100644 --- a/src/client/TerrainMapFileLoader.ts +++ b/src/client/TerrainMapFileLoader.ts @@ -1,4 +1,4 @@ -import { FetchGameMapLoader } from "../core/game/FetchGameMapLoader"; import version from "../../resources/version.txt"; +import { FetchGameMapLoader } from "../core/game/FetchGameMapLoader"; export const terrainMapFileLoader = new FetchGameMapLoader("/maps", version); diff --git a/src/client/TerritoryPatternsModal.ts b/src/client/TerritoryPatternsModal.ts index 6793e7f78..c3a859171 100644 --- a/src/client/TerritoryPatternsModal.ts +++ b/src/client/TerritoryPatternsModal.ts @@ -1,14 +1,14 @@ import "./components/Difficulties"; import "./components/Maps"; -import { LitElement, html, render } from "lit"; -import { customElement, query, state } from "lit/decorators.js"; -import { handlePurchase, patterns } from "./Cosmetics"; -import { Pattern } from "../core/CosmeticSchemas"; -import { PatternDecoder } from "../core/PatternDecoder"; -import type { TemplateResult } from "lit"; -import { UserMeResponse } from "../core/ApiSchemas"; -import { UserSettings } from "../core/game/UserSettings"; import { base64url } from "jose"; +import type { TemplateResult } from "lit"; +import { html, LitElement, render } from "lit"; +import { customElement, query, state } from "lit/decorators.js"; +import { UserMeResponse } from "../core/ApiSchemas"; +import { Pattern } from "../core/CosmeticSchemas"; +import { UserSettings } from "../core/game/UserSettings"; +import { PatternDecoder } from "../core/PatternDecoder"; +import { handlePurchase, patterns } from "./Cosmetics"; import { translateText } from "./Utils"; @customElement("territory-patterns-modal") @@ -112,8 +112,9 @@ export class TerritoryPatternsModal extends LitElement { return html`
${translateText("territory_patterns.blocked.purchase")}
@@ -129,9 +130,11 @@ export class TerritoryPatternsModal extends LitElement {
- ${pattern.product !== null - ? html` + ${ + pattern.product !== null + ? html`
`; } @@ -198,9 +203,11 @@ export class TerritoryPatternsModal extends LitElement { >
diff --git a/src/client/Transport.ts b/src/client/Transport.ts index e98a7de28..20f506ab6 100644 --- a/src/client/Transport.ts +++ b/src/client/Transport.ts @@ -1,3 +1,5 @@ +import { z } from "zod"; +import { EventBus, GameEvent } from "../core/EventBus"; import { AllPlayers, GameType, @@ -7,6 +9,8 @@ import { Tick, UnitType, } from "../core/game/Game"; +import { TileRef } from "../core/game/GameMap"; +import { PlayerView } from "../core/game/GameView"; import { AllPlayersStats, ClientHashMessage, @@ -20,13 +24,9 @@ import { ServerMessageSchema, Winner, } from "../core/Schemas"; -import { EventBus, GameEvent } from "../core/EventBus"; +import { replacer } from "../core/Util"; import { LobbyConfig } from "./ClientGameRunner"; import { LocalServer } from "./LocalServer"; -import { PlayerView } from "../core/game/GameView"; -import { TileRef } from "../core/game/GameMap"; -import { replacer } from "../core/Util"; -import { z } from "zod"; export class PauseGameEvent implements GameEvent { constructor(public readonly paused: boolean) {} diff --git a/src/client/UserSettingModal.ts b/src/client/UserSettingModal.ts index 2e46a7300..a5707ab2f 100644 --- a/src/client/UserSettingModal.ts +++ b/src/client/UserSettingModal.ts @@ -2,12 +2,12 @@ import "./components/baseComponents/setting/SettingKeybind"; import "./components/baseComponents/setting/SettingNumber"; import "./components/baseComponents/setting/SettingSlider"; import "./components/baseComponents/setting/SettingToggle"; -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, query, state } from "lit/decorators.js"; -import { SettingKeybind } from "./components/baseComponents/setting/SettingKeybind"; -import { UserSettings } from "../core/game/UserSettings"; -import { translateText } from "../client/Utils"; import { z } from "zod"; +import { translateText } from "../client/Utils"; +import { UserSettings } from "../core/game/UserSettings"; +import { SettingKeybind } from "./components/baseComponents/setting/SettingKeybind"; const KeybindSchema = z.record(z.string(), z.string()); @@ -233,18 +233,22 @@ export class UserSettingModal extends LitElement {
- ${this.settingsMode === "basic" - ? this.renderBasicSettings() - : this.renderKeybindSettings()} + ${ + this.settingsMode === "basic" + ? this.renderBasicSettings() + : this.renderKeybindSettings() + }
@@ -361,13 +367,15 @@ export class UserSettingModal extends LitElement { description="${translateText("user_setting.attack_ratio_desc")}" min="1" max="100" - .value=${Number(localStorage.getItem("settings.attackRatio") ?? "0.2") * - 100} + .value=${ + Number(localStorage.getItem("settings.attackRatio") ?? "0.2") * 100 + } @change=${this.sliderAttackRatio} > - ${this.showEasterEggSettings - ? html` + ${ + this.showEasterEggSettings + ? html` ` - : null} + : null + } `; } diff --git a/src/client/UsernameInput.ts b/src/client/UsernameInput.ts index 6b72ac448..3cea66c23 100644 --- a/src/client/UsernameInput.ts +++ b/src/client/UsernameInput.ts @@ -1,12 +1,12 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; +import { customElement, property, state } from "lit/decorators.js"; +import { v4 as uuidv4 } from "uuid"; +import { translateText } from "../client/Utils"; +import { UserSettings } from "../core/game/UserSettings"; import { MAX_USERNAME_LENGTH, validateUsername, } from "../core/validations/username"; -import { customElement, property, state } from "lit/decorators.js"; -import { UserSettings } from "../core/game/UserSettings"; -import { translateText } from "../client/Utils"; -import { v4 as uuidv4 } from "uuid"; const usernameKey = "username"; @@ -48,8 +48,9 @@ export class UsernameInput extends LitElement { focus:ring-blue-500 focus:border-blue-500 dark:border-gray-300/60 dark:bg-gray-700 dark:text-white" /> - ${this.validationError - ? html`
- ${this.isLoading - ? html`
+ ${ + this.isLoading + ? html`
${translateText("map_component.loading")}
` - : this.mapWebpPath - ? html`${this.mapKey}` - : html`
Error
`} + : html`
Error
` + }
${this.translation || this.mapName}
`; diff --git a/src/client/components/ModalOverlay.ts b/src/client/components/ModalOverlay.ts index 772a7399b..5c12cfba1 100644 --- a/src/client/components/ModalOverlay.ts +++ b/src/client/components/ModalOverlay.ts @@ -1,4 +1,4 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, property } from "lit/decorators"; @customElement("modal-overlay") diff --git a/src/client/components/NewsButton.ts b/src/client/components/NewsButton.ts index 860340226..6185f6708 100644 --- a/src/client/components/NewsButton.ts +++ b/src/client/components/NewsButton.ts @@ -1,9 +1,9 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property, state } from "lit/decorators.js"; -import { NewsModal } from "../NewsModal"; import megaphone from "../../../resources/images/Megaphone.svg"; -import { translateText } from "../Utils"; import version from "../../../resources/version.txt"; +import { NewsModal } from "../NewsModal"; +import { translateText } from "../Utils"; @customElement("news-button") export class NewsButton extends LitElement { @@ -38,10 +38,9 @@ export class NewsButton extends LitElement { render() { return html`
`; } diff --git a/src/client/components/baseComponents/Modal.ts b/src/client/components/baseComponents/Modal.ts index ae58d9078..8680f001d 100644 --- a/src/client/components/baseComponents/Modal.ts +++ b/src/client/components/baseComponents/Modal.ts @@ -1,4 +1,4 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, property, state } from "lit/decorators.js"; import { translateText } from "../../Utils"; @@ -83,18 +83,21 @@ export class OModal extends LitElement { render() { return html` - ${this.isModalOpen - ? html` + ${ + this.isModalOpen + ? html` ` - : html``} + : html`` + } `; } } diff --git a/src/client/components/baseComponents/setting/SettingKeybind.ts b/src/client/components/baseComponents/setting/SettingKeybind.ts index 2be0d500b..2750103cf 100644 --- a/src/client/components/baseComponents/setting/SettingKeybind.ts +++ b/src/client/components/baseComponents/setting/SettingKeybind.ts @@ -1,4 +1,4 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property } from "lit/decorators.js"; import { translateText } from "../../../../client/Utils"; diff --git a/src/client/components/baseComponents/setting/SettingNumber.ts b/src/client/components/baseComponents/setting/SettingNumber.ts index 8b7f80770..e36f96c72 100644 --- a/src/client/components/baseComponents/setting/SettingNumber.ts +++ b/src/client/components/baseComponents/setting/SettingNumber.ts @@ -1,4 +1,4 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property } from "lit/decorators.js"; @customElement("setting-number") diff --git a/src/client/components/baseComponents/setting/SettingSlider.ts b/src/client/components/baseComponents/setting/SettingSlider.ts index 67bd562dd..466b44e75 100644 --- a/src/client/components/baseComponents/setting/SettingSlider.ts +++ b/src/client/components/baseComponents/setting/SettingSlider.ts @@ -1,4 +1,4 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property } from "lit/decorators.js"; @customElement("setting-slider") diff --git a/src/client/components/baseComponents/setting/SettingToggle.ts b/src/client/components/baseComponents/setting/SettingToggle.ts index 18f1dfe71..5eb278d09 100644 --- a/src/client/components/baseComponents/setting/SettingToggle.ts +++ b/src/client/components/baseComponents/setting/SettingToggle.ts @@ -1,4 +1,4 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property } from "lit/decorators.js"; @customElement("setting-toggle") diff --git a/src/client/graphics/AnimatedSpriteLoader.ts b/src/client/graphics/AnimatedSpriteLoader.ts index 2c82ee27e..b3a8c6cee 100644 --- a/src/client/graphics/AnimatedSpriteLoader.ts +++ b/src/client/graphics/AnimatedSpriteLoader.ts @@ -1,19 +1,19 @@ -import { AnimatedSprite } from "./AnimatedSprite"; -import { FxType } from "./fx/Fx"; -import { PlayerView } from "../../core/game/GameView"; -import SAMExplosion from "../../../resources/sprites/samExplosion.png"; -import { Theme } from "../../core/configuration/Config"; -import { colorizeCanvas } from "./SpriteLoader"; +import miniBigSmoke from "../../../resources/sprites/bigsmoke.png"; import conquestSword from "../../../resources/sprites/conquestSword.png"; import dust from "../../../resources/sprites/dust.png"; -import miniBigSmoke from "../../../resources/sprites/bigsmoke.png"; import miniExplosion from "../../../resources/sprites/miniExplosion.png"; import miniFire from "../../../resources/sprites/minifire.png"; +import nuke from "../../../resources/sprites/nukeExplosion.png"; +import SAMExplosion from "../../../resources/sprites/samExplosion.png"; +import sinkingShip from "../../../resources/sprites/sinkingShip.png"; import miniSmoke from "../../../resources/sprites/smoke.png"; import miniSmokeAndFire from "../../../resources/sprites/smokeAndFire.png"; -import nuke from "../../../resources/sprites/nukeExplosion.png"; -import sinkingShip from "../../../resources/sprites/sinkingShip.png"; import unitExplosion from "../../../resources/sprites/unitExplosion.png"; +import { Theme } from "../../core/configuration/Config"; +import { PlayerView } from "../../core/game/GameView"; +import { AnimatedSprite } from "./AnimatedSprite"; +import { FxType } from "./fx/Fx"; +import { colorizeCanvas } from "./SpriteLoader"; type AnimatedSpriteConfig = { url: string; @@ -128,7 +128,8 @@ const ANIMATED_SPRITE_CONFIG: Partial> = { }; export class AnimatedSpriteLoader { - private readonly animatedSpriteImageMap: Map = new Map(); + private readonly animatedSpriteImageMap: Map = + new Map(); // Do not color the same sprite twice private readonly coloredAnimatedSpriteCache: Map = new Map(); diff --git a/src/client/graphics/GameRenderer.ts b/src/client/graphics/GameRenderer.ts index 327495154..145bd7435 100644 --- a/src/client/graphics/GameRenderer.ts +++ b/src/client/graphics/GameRenderer.ts @@ -1,17 +1,19 @@ +import { EventBus } from "../../core/EventBus"; +import { GameView } from "../../core/game/GameView"; +import { UserSettings } from "../../core/game/UserSettings"; +import { GameStartingModal } from "../GameStartingModal"; +import { RedrawGraphicsEvent } from "../InputHandler"; import { AlertFrame } from "./layers/AlertFrame"; import { BuildMenu } from "./layers/BuildMenu"; import { ChatDisplay } from "./layers/ChatDisplay"; import { ChatModal } from "./layers/ChatModal"; import { ControlPanel } from "./layers/ControlPanel"; import { EmojiTable } from "./layers/EmojiTable"; -import { EventBus } from "../../core/EventBus"; import { EventsDisplay } from "./layers/EventsDisplay"; import { FPSDisplay } from "./layers/FPSDisplay"; import { FxLayer } from "./layers/FxLayer"; import { GameLeftSidebar } from "./layers/GameLeftSidebar"; import { GameRightSidebar } from "./layers/GameRightSidebar"; -import { GameStartingModal } from "../GameStartingModal"; -import { GameView } from "../../core/game/GameView"; import { GutterAdModal } from "./layers/GutterAdModal"; import { HeadsUpMessage } from "./layers/HeadsUpMessage"; import { Layer } from "./layers/Layer"; @@ -22,7 +24,6 @@ import { NameLayer } from "./layers/NameLayer"; import { PlayerInfoOverlay } from "./layers/PlayerInfoOverlay"; import { PlayerPanel } from "./layers/PlayerPanel"; import { RailroadLayer } from "./layers/RailroadLayer"; -import { RedrawGraphicsEvent } from "../InputHandler"; import { ReplayPanel } from "./layers/ReplayPanel"; import { SettingsModal } from "./layers/SettingsModal"; import { SpawnAd } from "./layers/SpawnAd"; @@ -32,13 +33,12 @@ import { StructureLayer } from "./layers/StructureLayer"; import { TeamStats } from "./layers/TeamStats"; import { TerrainLayer } from "./layers/TerrainLayer"; import { TerritoryLayer } from "./layers/TerritoryLayer"; -import { TransformHandler } from "./TransformHandler"; import { UILayer } from "./layers/UILayer"; -import { UIState } from "./UIState"; import { UnitDisplay } from "./layers/UnitDisplay"; import { UnitLayer } from "./layers/UnitLayer"; -import { UserSettings } from "../../core/game/UserSettings"; import { WinModal } from "./layers/WinModal"; +import { TransformHandler } from "./TransformHandler"; +import { UIState } from "./UIState"; export function createRenderer( canvas: HTMLCanvasElement, diff --git a/src/client/graphics/SpriteLoader.ts b/src/client/graphics/SpriteLoader.ts index 4e140ec4e..95a913b47 100644 --- a/src/client/graphics/SpriteLoader.ts +++ b/src/client/graphics/SpriteLoader.ts @@ -1,17 +1,17 @@ -import { TrainType, UnitType } from "../../core/game/Game"; import { Colord } from "colord"; -import { Theme } from "../../core/configuration/Config"; -import { UnitView } from "../../core/game/GameView"; import atomBombSprite from "../../../resources/sprites/atombomb.png"; import hydrogenBombSprite from "../../../resources/sprites/hydrogenbomb.png"; import mirvSprite from "../../../resources/sprites/mirv2.png"; import samMissileSprite from "../../../resources/sprites/samMissile.png"; import tradeShipSprite from "../../../resources/sprites/tradeship.png"; import trainCarriageSprite from "../../../resources/sprites/trainCarriage.png"; -import trainEngineSprite from "../../../resources/sprites/trainEngine.png"; import trainLoadedCarriageSprite from "../../../resources/sprites/trainCarriageLoaded.png"; +import trainEngineSprite from "../../../resources/sprites/trainEngine.png"; import transportShipSprite from "../../../resources/sprites/transportship.png"; import warshipSprite from "../../../resources/sprites/warship.png"; +import { Theme } from "../../core/configuration/Config"; +import { TrainType, UnitType } from "../../core/game/Game"; +import { UnitView } from "../../core/game/GameView"; // Can't reuse TrainType because "loaded" is not a type, just an attribute const TrainTypeSprite = { diff --git a/src/client/graphics/TransformHandler.ts b/src/client/graphics/TransformHandler.ts index b1569e463..c0a735e9c 100644 --- a/src/client/graphics/TransformHandler.ts +++ b/src/client/graphics/TransformHandler.ts @@ -1,12 +1,12 @@ +import { EventBus } from "../../core/EventBus"; +import { Cell } from "../../core/game/Game"; +import { GameView } from "../../core/game/GameView"; import { CenterCameraEvent, DragEvent, ZoomEvent } from "../InputHandler"; import { GoToPlayerEvent, GoToPositionEvent, GoToUnitEvent, } from "./layers/Leaderboard"; -import { Cell } from "../../core/game/Game"; -import { EventBus } from "../../core/EventBus"; -import { GameView } from "../../core/game/GameView"; export const GOTO_INTERVAL_MS = 16; export const CAMERA_MAX_SPEED = 15; diff --git a/src/client/graphics/fx/ConquestFx.ts b/src/client/graphics/fx/ConquestFx.ts index 272ccbd3f..a7d5ab7a5 100644 --- a/src/client/graphics/fx/ConquestFx.ts +++ b/src/client/graphics/fx/ConquestFx.ts @@ -1,10 +1,10 @@ -import { FadeFx, SpriteFx } from "./SpriteFx"; -import { Fx, FxType } from "./Fx"; -import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; import { ConquestUpdate } from "../../../core/game/GameUpdates"; import { GameView } from "../../../core/game/GameView"; -import { TextFx } from "./TextFx"; import { renderNumber } from "../../Utils"; +import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; +import { Fx, FxType } from "./Fx"; +import { FadeFx, SpriteFx } from "./SpriteFx"; +import { TextFx } from "./TextFx"; /** * Conquest FX: diff --git a/src/client/graphics/fx/NukeFx.ts b/src/client/graphics/fx/NukeFx.ts index d610d403c..bebf04621 100644 --- a/src/client/graphics/fx/NukeFx.ts +++ b/src/client/graphics/fx/NukeFx.ts @@ -1,7 +1,7 @@ -import { FadeFx, SpriteFx } from "./SpriteFx"; -import { Fx, FxType } from "./Fx"; -import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; import { GameView } from "../../../core/game/GameView"; +import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; +import { Fx, FxType } from "./Fx"; +import { FadeFx, SpriteFx } from "./SpriteFx"; /** * Shockwave effect: draw a growing 1px white circle diff --git a/src/client/graphics/fx/SpriteFx.ts b/src/client/graphics/fx/SpriteFx.ts index be5e7ddb7..653d4986a 100644 --- a/src/client/graphics/fx/SpriteFx.ts +++ b/src/client/graphics/fx/SpriteFx.ts @@ -1,8 +1,8 @@ -import { Fx, FxType } from "./Fx"; +import { Theme } from "../../../core/configuration/Config"; +import { PlayerView } from "../../../core/game/GameView"; import { AnimatedSprite } from "../AnimatedSprite"; import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; -import { PlayerView } from "../../../core/game/GameView"; -import { Theme } from "../../../core/configuration/Config"; +import { Fx, FxType } from "./Fx"; function fadeInOut(t: number, fadeIn = 0.3, fadeOut = 0.7): number { if (t < fadeIn) { diff --git a/src/client/graphics/fx/UnitExplosionFx.ts b/src/client/graphics/fx/UnitExplosionFx.ts index 8971e057d..241e07508 100644 --- a/src/client/graphics/fx/UnitExplosionFx.ts +++ b/src/client/graphics/fx/UnitExplosionFx.ts @@ -1,6 +1,6 @@ -import { Fx, FxType } from "./Fx"; -import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; import { GameView } from "../../../core/game/GameView"; +import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; +import { Fx, FxType } from "./Fx"; import { SpriteFx } from "./SpriteFx"; import { Timeline } from "./Timeline"; diff --git a/src/client/graphics/layers/AlertFrame.ts b/src/client/graphics/layers/AlertFrame.ts index a77e0603c..949b7d28b 100644 --- a/src/client/graphics/layers/AlertFrame.ts +++ b/src/client/graphics/layers/AlertFrame.ts @@ -1,12 +1,12 @@ +import { css, html, LitElement } from "lit"; +import { customElement, state } from "lit/decorators.js"; import { BrokeAllianceUpdate, GameUpdateType, } from "../../../core/game/GameUpdates"; -import { LitElement, css, html } from "lit"; -import { customElement, state } from "lit/decorators.js"; import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; import { UserSettings } from "../../../core/game/UserSettings"; +import { Layer } from "./Layer"; // Parameters for the alert animation const ALERT_SPEED = 1.6; diff --git a/src/client/graphics/layers/BuildMenu.ts b/src/client/graphics/layers/BuildMenu.ts index 53702ed82..dcaa11fd9 100644 --- a/src/client/graphics/layers/BuildMenu.ts +++ b/src/client/graphics/layers/BuildMenu.ts @@ -1,39 +1,39 @@ -import { - BuildUnitIntentEvent, - SendUpgradeStructureIntentEvent, -} from "../../Transport"; +import { css, html, LitElement } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import warshipIcon from "../../../../resources/images/BattleshipIconWhite.svg"; +import cityIcon from "../../../../resources/images/CityIconWhite.svg"; +import factoryIcon from "../../../../resources/images/FactoryIconWhite.svg"; +import goldCoinIcon from "../../../../resources/images/GoldCoinIcon.svg"; +import mirvIcon from "../../../../resources/images/MIRVIcon.svg"; +import hydrogenBombIcon from "../../../../resources/images/MushroomCloudIconWhite.svg"; +import atomBombIcon from "../../../../resources/images/NukeIconWhite.svg"; +import portIcon from "../../../../resources/images/PortIcon.svg"; +import shieldIcon from "../../../../resources/images/ShieldIconWhite.svg"; +import missileSiloIcon from "../../../../resources/non-commercial/svg/MissileSiloIconWhite.svg"; +import samlauncherIcon from "../../../../resources/non-commercial/svg/SamLauncherIconWhite.svg"; +import { translateText } from "../../../client/Utils"; +import { EventBus } from "../../../core/EventBus"; import { BuildableUnit, Gold, PlayerActions, UnitType, } from "../../../core/game/Game"; +import { TileRef } from "../../../core/game/GameMap"; +import { GameView } from "../../../core/game/GameView"; import { CloseViewEvent, MouseDownEvent, ShowBuildMenuEvent, ShowEmojiMenuEvent, } from "../../InputHandler"; -import { LitElement, css, html } from "lit"; -import { customElement, state } from "lit/decorators.js"; -import { EventBus } from "../../../core/EventBus"; -import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; -import { TileRef } from "../../../core/game/GameMap"; -import { TransformHandler } from "../TransformHandler"; -import atomBombIcon from "../../../../resources/images/NukeIconWhite.svg"; -import cityIcon from "../../../../resources/images/CityIconWhite.svg"; -import factoryIcon from "../../../../resources/images/FactoryIconWhite.svg"; -import goldCoinIcon from "../../../../resources/images/GoldCoinIcon.svg"; -import hydrogenBombIcon from "../../../../resources/images/MushroomCloudIconWhite.svg"; -import mirvIcon from "../../../../resources/images/MIRVIcon.svg"; -import missileSiloIcon from "../../../../resources/non-commercial/svg/MissileSiloIconWhite.svg"; -import portIcon from "../../../../resources/images/PortIcon.svg"; +import { + BuildUnitIntentEvent, + SendUpgradeStructureIntentEvent, +} from "../../Transport"; import { renderNumber } from "../../Utils"; -import samlauncherIcon from "../../../../resources/non-commercial/svg/SamLauncherIconWhite.svg"; -import shieldIcon from "../../../../resources/images/ShieldIconWhite.svg"; -import { translateText } from "../../../client/Utils"; -import warshipIcon from "../../../../resources/images/BattleshipIconWhite.svg"; +import { TransformHandler } from "../TransformHandler"; +import { Layer } from "./Layer"; export type BuildItemDisplay = { unitType: UnitType; @@ -389,7 +389,10 @@ export class BuildMenu extends LitElement implements Layer { return player.totalUnitLevels(item.unitType).toString(); } - public sendBuildOrUpgrade(buildableUnit: BuildableUnit, tile?: TileRef): void { + public sendBuildOrUpgrade( + buildableUnit: BuildableUnit, + tile?: TileRef, + ): void { if (tile === undefined) throw new Error("Missing tile"); if (this.eventBus === undefined) throw new Error("Not initialized"); if (buildableUnit.canUpgrade !== false) { @@ -430,9 +433,11 @@ export class BuildMenu extends LitElement implements Layer { @click=${() => this.sendBuildOrUpgrade(buildableUnit, this.clickedTile)} ?disabled=${!enabled} - title=${!enabled - ? translateText("build_menu.not_enough_money") - : ""} + title=${ + !enabled + ? translateText("build_menu.not_enough_money") + : "" + } > ${item.key && translateText(item.key)} ${item.description && - translateText(item.description)}${ + item.description && translateText(item.description) + } ${renderNumber( @@ -459,11 +465,13 @@ export class BuildMenu extends LitElement implements Layer { style="vertical-align: middle;" /> - ${item.countable - ? html`
+ ${ + item.countable + ? html`
${this.count(item)}
` - : ""} + : "" + } `; })} diff --git a/src/client/graphics/layers/ChatDisplay.ts b/src/client/graphics/layers/ChatDisplay.ts index da81e5c21..5c87d25c0 100644 --- a/src/client/graphics/layers/ChatDisplay.ts +++ b/src/client/graphics/layers/ChatDisplay.ts @@ -1,16 +1,16 @@ +import { html, LitElement } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import { DirectiveResult } from "lit/directive.js"; +import { UnsafeHTMLDirective, unsafeHTML } from "lit/directives/unsafe-html.js"; +import { EventBus } from "../../../core/EventBus"; +import { MessageType } from "../../../core/game/Game"; import { DisplayMessageUpdate, GameUpdateType, } from "../../../core/game/GameUpdates"; -import { LitElement, html } from "lit"; -import { UnsafeHTMLDirective, unsafeHTML } from "lit/directives/unsafe-html.js"; -import { customElement, state } from "lit/decorators.js"; -import { DirectiveResult } from "lit/directive.js"; -import { EventBus } from "../../../core/EventBus"; import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; -import { MessageType } from "../../../core/game/Game"; import { onlyImages } from "../../../core/Util"; +import { Layer } from "./Layer"; type ChatEvent = { description: string; @@ -136,10 +136,9 @@ export class ChatDisplay extends LitElement implements Layer {
diff --git a/src/client/graphics/layers/ChatIntegration.ts b/src/client/graphics/layers/ChatIntegration.ts index f8993604b..fd1984811 100644 --- a/src/client/graphics/layers/ChatIntegration.ts +++ b/src/client/graphics/layers/ChatIntegration.ts @@ -1,9 +1,9 @@ -import { COLORS, MenuElement, MenuElementParams } from "./RadialMenuElements"; -import { ChatModal, QuickChatPhrase, quickChatPhrases } from "./ChatModal"; -import { GameView, PlayerView } from "../../../core/game/GameView"; import { EventBus } from "../../../core/EventBus"; +import { GameView, PlayerView } from "../../../core/game/GameView"; import { SendQuickChatEvent } from "../../Transport"; import { translateText } from "../../Utils"; +import { ChatModal, QuickChatPhrase, quickChatPhrases } from "./ChatModal"; +import { COLORS, MenuElement, MenuElementParams } from "./RadialMenuElements"; export class ChatIntegration { private readonly ctModal: ChatModal; diff --git a/src/client/graphics/layers/ChatModal.ts b/src/client/graphics/layers/ChatModal.ts index 3aacd9538..c8ca5ae01 100644 --- a/src/client/graphics/layers/ChatModal.ts +++ b/src/client/graphics/layers/ChatModal.ts @@ -1,11 +1,11 @@ -import { GameView, PlayerView } from "../../../core/game/GameView"; -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, query } from "lit/decorators.js"; -import { CloseViewEvent } from "../../InputHandler"; +import quickChatData from "../../../../resources/QuickChat.json"; import { EventBus } from "../../../core/EventBus"; import { PlayerType } from "../../../core/game/Game"; +import { GameView, PlayerView } from "../../../core/game/GameView"; +import { CloseViewEvent } from "../../InputHandler"; import { SendQuickChatEvent } from "../../Transport"; -import quickChatData from "../../../../resources/QuickChat.json"; import { translateText } from "../../Utils"; export type QuickChatPhrase = { @@ -78,10 +78,9 @@ export class ChatModal extends LitElement { ${this.categories.map( (category) => html` diff --git a/src/client/graphics/layers/ControlPanel.ts b/src/client/graphics/layers/ControlPanel.ts index 3257f0f6f..f07c6e6bd 100644 --- a/src/client/graphics/layers/ControlPanel.ts +++ b/src/client/graphics/layers/ControlPanel.ts @@ -1,14 +1,14 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; -import { renderNumber, renderTroops } from "../../Utils"; -import { AttackRatioEvent } from "../../InputHandler"; -import { ClientID } from "../../../core/Schemas"; -import { EventBus } from "../../../core/EventBus"; -import { GameView } from "../../../core/game/GameView"; -import { Gold } from "../../../core/game/Game"; -import { Layer } from "./Layer"; -import { UIState } from "../UIState"; import { translateText } from "../../../client/Utils"; +import { EventBus } from "../../../core/EventBus"; +import { Gold } from "../../../core/game/Game"; +import { GameView } from "../../../core/game/GameView"; +import { ClientID } from "../../../core/Schemas"; +import { AttackRatioEvent } from "../../InputHandler"; +import { renderNumber, renderTroops } from "../../Utils"; +import { UIState } from "../UIState"; +import { Layer } from "./Layer"; @customElement("control-panel") export class ControlPanel extends LitElement implements Layer { @@ -166,10 +166,12 @@ export class ControlPanel extends LitElement implements Layer { }
e.preventDefault()} >
@@ -180,9 +182,11 @@ export class ControlPanel extends LitElement implements Layer { ${renderTroops(this._troops)} / ${renderTroops(this._maxTroops)} (+${renderTroops(this.troopRate)}) { this.isVisible = true; const cell = transformHandler.screenToWorldCoordinates(e.x, e.y); diff --git a/src/client/graphics/layers/EventsDisplay.ts b/src/client/graphics/layers/EventsDisplay.ts index 193e5f314..af089203a 100644 --- a/src/client/graphics/layers/EventsDisplay.ts +++ b/src/client/graphics/layers/EventsDisplay.ts @@ -1,12 +1,22 @@ /* eslint-disable max-lines */ + +import { html, LitElement, TemplateResult } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import { DirectiveResult } from "lit/directive.js"; +import { UnsafeHTMLDirective, unsafeHTML } from "lit/directives/unsafe-html.js"; +import allianceIcon from "../../../../resources/images/AllianceIconWhite.svg"; +import chatIcon from "../../../../resources/images/ChatIconWhite.svg"; +import donateGoldIcon from "../../../../resources/images/DonateGoldIconWhite.svg"; +import swordIcon from "../../../../resources/images/SwordIconWhite.svg"; +import { EventBus } from "../../../core/EventBus"; import { AllPlayers, + getMessageCategory, MessageCategory, MessageType, PlayerType, Tick, UnitType, - getMessageCategory, } from "../../../core/game/Game"; import { AllianceExpiredUpdate, @@ -21,31 +31,26 @@ import { TargetPlayerUpdate, UnitIncomingUpdate, } from "../../../core/game/GameUpdates"; +import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; +import { onlyImages } from "../../../core/Util"; import { CancelAttackIntentEvent, CancelBoatIntentEvent, SendAllianceExtensionIntentEvent, SendAllianceReplyIntentEvent, } from "../../Transport"; -import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; +import { + getMessageTypeClasses, + renderNumber, + renderTroops, + translateText, +} from "../../Utils"; +import { Layer } from "./Layer"; import { GoToPlayerEvent, GoToPositionEvent, GoToUnitEvent, } from "./Leaderboard"; -import { LitElement, TemplateResult, html } from "lit"; -import { UnsafeHTMLDirective, unsafeHTML } from "lit/directives/unsafe-html.js"; -import { customElement, state } from "lit/decorators.js"; -import { getMessageTypeClasses, translateText } from "../../Utils"; -import { renderNumber, renderTroops } from "../../Utils"; -import { DirectiveResult } from "lit/directive.js"; -import { EventBus } from "../../../core/EventBus"; -import { Layer } from "./Layer"; -import allianceIcon from "../../../../resources/images/AllianceIconWhite.svg"; -import chatIcon from "../../../../resources/images/ChatIconWhite.svg"; -import donateGoldIcon from "../../../../resources/images/DonateGoldIconWhite.svg"; -import { onlyImages } from "../../../core/Util"; -import swordIcon from "../../../../resources/images/SwordIconWhite.svg"; type GameEvent = { description: string; @@ -87,15 +92,19 @@ export class EventsDisplay extends LitElement implements Layer { @state() private latestGoldAmount: bigint | null = null; @state() private goldAmountAnimating = false; private goldAmountTimeoutId: ReturnType | null = null; - @state() private readonly eventsFilters: Map = new Map([ - [MessageCategory.ATTACK, false], - [MessageCategory.TRADE, false], - [MessageCategory.ALLIANCE, false], - [MessageCategory.CHAT, false], - ]); + @state() private readonly eventsFilters: Map = + new Map([ + [MessageCategory.ATTACK, false], + [MessageCategory.TRADE, false], + [MessageCategory.ALLIANCE, false], + [MessageCategory.CHAT, false], + ]); private renderButton(options: { - content: string | TemplateResult | DirectiveResult; + content: + | string + | TemplateResult + | DirectiveResult; onClick?: () => void; className?: string; disabled?: boolean; @@ -539,8 +548,8 @@ export class EventsDisplay extends LitElement implements Layer { traitorDuration === 1 ? translateText("events_display.duration_second") : translateText("events_display.duration_seconds_plural", { - seconds: traitorDuration, - }); + seconds: traitorDuration, + }); this.addEvent({ description: translateText("events_display.betrayal_description", { @@ -738,41 +747,43 @@ export class EventsDisplay extends LitElement implements Layer { private renderIncomingAttacks() { return html` - ${this.incomingAttacks.length > 0 - ? html` - ${this.incomingAttacks.map( - (attack) => { - const attacker = this.game?.playerBySmallID(attack.attackerID); - return html` + ${ + this.incomingAttacks.length > 0 + ? html` + ${this.incomingAttacks.map((attack) => { + const attacker = this.game?.playerBySmallID(attack.attackerID); + return html` ${this.renderButton({ content: html` ${renderTroops(attack.troops)} ${attacker?.isPlayer() ? attacker.name() : "unknown"} - ${attack.retreating - ? `(${translateText("events_display.retreating")}...)` - : ""} + ${ + attack.retreating + ? `(${translateText("events_display.retreating")}...)` + : "" + } `, onClick: () => this.attackWarningOnClick(attack), className: "text-left text-red-400", translate: false, })} `; - }, - )} + })} ` - : ""} + : "" + } `; } private renderOutgoingAttacks() { return html` - ${this.outgoingAttacks.length > 0 - ? html` + ${ + this.outgoingAttacks.length > 0 + ? html`
- ${this.outgoingAttacks.map( - (attack) => { - const target = this.game?.playerBySmallID(attack.targetID); - return html` + ${this.outgoingAttacks.map((attack) => { + const target = this.game?.playerBySmallID(attack.targetID); + return html`
${this.renderButton({ content: html` @@ -783,32 +794,36 @@ export class EventsDisplay extends LitElement implements Layer { className: "text-left text-blue-400", translate: false, })} - ${!attack.retreating - ? this.renderButton({ - content: "❌", - onClick: () => this.emitCancelAttackIntent(attack.id), - className: "text-left flex-shrink-0", - disabled: attack.retreating, - }) - : html` + this.emitCancelAttackIntent(attack.id), + className: "text-left flex-shrink-0", + disabled: attack.retreating, + }) + : html`(${translateText( "events_display.retreating", )}...)`} + >` + }
`; - }, - )} + })}
` - : ""} + : "" + } `; } private renderOutgoingLandAttacks() { return html` - ${this.outgoingLandAttacks.length > 0 - ? html` + ${ + this.outgoingLandAttacks.length > 0 + ? html`
${this.outgoingLandAttacks.map( (landAttack) => html` @@ -819,32 +834,36 @@ export class EventsDisplay extends LitElement implements Layer { className: "text-left text-gray-400", translate: false, })} - ${!landAttack.retreating - ? this.renderButton({ - content: "❌", - onClick: () => - this.emitCancelAttackIntent(landAttack.id), - className: "text-left flex-shrink-0", - disabled: landAttack.retreating, - }) - : html` + this.emitCancelAttackIntent(landAttack.id), + className: "text-left flex-shrink-0", + disabled: landAttack.retreating, + }) + : html`(${translateText( "events_display.retreating", )}...)`} + >` + }
`, )}
` - : ""} + : "" + } `; } private renderBoats() { return html` - ${this.outgoingBoats.length > 0 - ? html` + ${ + this.outgoingBoats.length > 0 + ? html`
${this.outgoingBoats.map( (boat) => html` @@ -856,24 +875,27 @@ export class EventsDisplay extends LitElement implements Layer { className: "text-left text-blue-400", translate: false, })} - ${!boat.retreating() - ? this.renderButton({ - content: "❌", - onClick: () => this.emitBoatCancelIntent(boat.id()), - className: "text-left flex-shrink-0", - disabled: boat.retreating(), - }) - : html` this.emitBoatCancelIntent(boat.id()), + className: "text-left flex-shrink-0", + disabled: boat.retreating(), + }) + : html`(${translateText( "events_display.retreating", )}...)`} + >` + }
`, )}
` - : ""} + : "" + } `; } @@ -921,16 +943,17 @@ export class EventsDisplay extends LitElement implements Layer { return html` ${styles} - ${this._hidden - ? html` + ${ + this._hidden + ? html`
${this.renderButton({ content: html` Events ${this.newEvents} `, @@ -941,7 +964,7 @@ export class EventsDisplay extends LitElement implements Layer { })}
` - : html` + : html`
`, onClick: () => this.toggleEventFilter(MessageCategory.ATTACK), @@ -970,11 +993,11 @@ export class EventsDisplay extends LitElement implements Layer { content: html``, onClick: () => this.toggleEventFilter(MessageCategory.TRADE), @@ -984,11 +1007,11 @@ export class EventsDisplay extends LitElement implements Layer { content: html``, onClick: () => this.toggleEventFilter(MessageCategory.ALLIANCE), @@ -998,11 +1021,11 @@ export class EventsDisplay extends LitElement implements Layer { content: html``, onClick: () => this.toggleEventFilter(MessageCategory.CHAT), @@ -1010,18 +1033,23 @@ export class EventsDisplay extends LitElement implements Layer { })}
- ${this.latestGoldAmount !== null - ? html`+${renderNumber(this.latestGoldAmount)}` - : ""} + : "" + } ${this.renderButton({ content: translateText("leaderboard.hide"), onClick: this.toggleHidden, @@ -1052,30 +1080,36 @@ export class EventsDisplay extends LitElement implements Layer { event.type, )}" > - ${event.focusID - ? this.renderButton({ - content: this.getEventDescription(event), - onClick: () => { - event.focusID && - this.emitGoToPlayerEvent(event.focusID); - }, - className: "text-left", - }) - : event.unitView + ${ + event.focusID ? this.renderButton({ - content: this.getEventDescription(event), - onClick: () => { - event.unitView && - this.emitGoToUnitEvent( - event.unitView, + content: this.getEventDescription(event), + onClick: () => { + event.focusID && + this.emitGoToPlayerEvent( + event.focusID, ); - }, - className: "text-left", - }) - : this.getEventDescription(event)} + }, + className: "text-left", + }) + : event.unitView + ? this.renderButton({ + content: + this.getEventDescription(event), + onClick: () => { + event.unitView && + this.emitGoToUnitEvent( + event.unitView, + ); + }, + className: "text-left", + }) + : this.getEventDescription(event) + } - ${event.buttons - ? html` + ${ + event.buttons + ? html`
${event.buttons.map( (btn) => html` @@ -1084,13 +1118,13 @@ export class EventsDisplay extends LitElement implements Layer { text-white rounded text-md md:text-sm cursor-pointer transition-colors duration-300 - ${btn.className.includes("btn-info") - ? "bg-blue-500 hover:bg-blue-600" - : btn.className.includes( - "btn-gray", - ) - ? "bg-gray-500 hover:bg-gray-600" - : "bg-green-600 hover:bg-green-700"}" + ${ + btn.className.includes("btn-info") + ? "bg-blue-500 hover:bg-blue-600" + : btn.className.includes("btn-gray") + ? "bg-gray-500 hover:bg-gray-600" + : "bg-green-600 hover:bg-green-700" + }" @click=${() => { btn.action(); if (!btn.preventClose) { @@ -1113,62 +1147,72 @@ export class EventsDisplay extends LitElement implements Layer { )}
` - : ""} + : "" + } `, )} - ${this.incomingAttacks.length > 0 - ? html` + ${ + this.incomingAttacks.length > 0 + ? html`
` - : ""} + : "" + } - ${this.outgoingAttacks.length > 0 - ? html` + ${ + this.outgoingAttacks.length > 0 + ? html` ` - : ""} + : "" + } - ${this.outgoingLandAttacks.length > 0 - ? html` + ${ + this.outgoingLandAttacks.length > 0 + ? html` ` - : ""} + : "" + } - ${this.outgoingBoats.length > 0 - ? html` + ${ + this.outgoingBoats.length > 0 + ? html` ` - : ""} + : "" + } - ${filteredEvents.length === 0 && - this.incomingAttacks.length === 0 && - this.outgoingAttacks.length === 0 && - this.outgoingLandAttacks.length === 0 && - this.outgoingBoats.length === 0 - ? html` + ${ + filteredEvents.length === 0 && + this.incomingAttacks.length === 0 && + this.outgoingAttacks.length === 0 && + this.outgoingLandAttacks.length === 0 && + this.outgoingBoats.length === 0 + ? html` ` - : ""} + : "" + }
${this.renderIncomingAttacks()}
${this.renderOutgoingAttacks()}
${this.renderOutgoingLandAttacks()}
${this.renderBoats()}
- `} + ` + } `; } diff --git a/src/client/graphics/layers/FPSDisplay.ts b/src/client/graphics/layers/FPSDisplay.ts index cb999ed51..7ebd27ef8 100644 --- a/src/client/graphics/layers/FPSDisplay.ts +++ b/src/client/graphics/layers/FPSDisplay.ts @@ -1,9 +1,9 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, property, state } from "lit/decorators.js"; import { EventBus } from "../../../core/EventBus"; -import { Layer } from "./Layer"; -import { TogglePerformanceOverlayEvent } from "../../InputHandler"; import { UserSettings } from "../../../core/game/UserSettings"; +import { TogglePerformanceOverlayEvent } from "../../InputHandler"; +import { Layer } from "./Layer"; @customElement("fps-display") export class FPSDisplay extends LitElement implements Layer { diff --git a/src/client/graphics/layers/FxLayer.ts b/src/client/graphics/layers/FxLayer.ts index 3fa6a2072..128790c8e 100644 --- a/src/client/graphics/layers/FxLayer.ts +++ b/src/client/graphics/layers/FxLayer.ts @@ -1,21 +1,21 @@ +import { Theme } from "../../../core/configuration/Config"; +import { UnitType } from "../../../core/game/Game"; import { BonusEventUpdate, ConquestUpdate, GameUpdateType, RailroadUpdate, } from "../../../core/game/GameUpdates"; -import { Fx, FxType } from "../fx/Fx"; import { GameView, UnitView } from "../../../core/game/GameView"; -import { ShockwaveFx, nukeFxFactory } from "../fx/NukeFx"; +import { renderNumber } from "../../Utils"; import { AnimatedSpriteLoader } from "../AnimatedSpriteLoader"; -import { Layer } from "./Layer"; +import { conquestFxFactory } from "../fx/ConquestFx"; +import { Fx, FxType } from "../fx/Fx"; +import { nukeFxFactory, ShockwaveFx } from "../fx/NukeFx"; import { SpriteFx } from "../fx/SpriteFx"; import { TextFx } from "../fx/TextFx"; -import { Theme } from "../../../core/configuration/Config"; import { UnitExplosionFx } from "../fx/UnitExplosionFx"; -import { UnitType } from "../../../core/game/Game"; -import { conquestFxFactory } from "../fx/ConquestFx"; -import { renderNumber } from "../../Utils"; +import { Layer } from "./Layer"; export class FxLayer implements Layer { private canvas: HTMLCanvasElement | undefined; diff --git a/src/client/graphics/layers/GameLeftSidebar.ts b/src/client/graphics/layers/GameLeftSidebar.ts index 11cddc2d1..44ee0ac57 100644 --- a/src/client/graphics/layers/GameLeftSidebar.ts +++ b/src/client/graphics/layers/GameLeftSidebar.ts @@ -1,14 +1,14 @@ -import { LitElement, html } from "lit"; -import { customElement, state } from "lit/decorators.js"; import { Colord } from "colord"; -import { GameMode } from "../../../core/game/Game"; -import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; +import { html, LitElement } from "lit"; +import { customElement, state } from "lit/decorators.js"; import leaderboardRegularIcon from "../../../../resources/images/LeaderboardIconRegularWhite.svg"; import leaderboardSolidIcon from "../../../../resources/images/LeaderboardIconSolidWhite.svg"; import teamRegularIcon from "../../../../resources/images/TeamIconRegularWhite.svg"; import teamSolidIcon from "../../../../resources/images/TeamIconSolidWhite.svg"; +import { GameMode } from "../../../core/game/Game"; +import { GameView } from "../../../core/game/GameView"; import { translateText } from "../../Utils"; +import { Layer } from "./Layer"; @customElement("game-left-sidebar") export class GameLeftSidebar extends LitElement implements Layer { @@ -97,8 +97,9 @@ export class GameLeftSidebar extends LitElement implements Layer { transition-transform duration-300 ease-out transform ${this.isVisible ? "translate-x-0" : "-translate-x-full"}`} > - ${this.isPlayerTeamLabelVisible - ? html` + ${ + this.isPlayerTeamLabelVisible + ? html`
e.preventDefault()} @@ -109,7 +110,8 @@ export class GameLeftSidebar extends LitElement implements Layer {
` - : null} + : null + }
treeIcon
- ${this.isTeamGame - ? html` + ${ + this.isTeamGame + ? html`
treeIcon
` - : null} + : null + }
diff --git a/src/client/graphics/layers/GameRightSidebar.ts b/src/client/graphics/layers/GameRightSidebar.ts index 7c8d1c9b6..03d2e4be7 100644 --- a/src/client/graphics/layers/GameRightSidebar.ts +++ b/src/client/graphics/layers/GameRightSidebar.ts @@ -1,20 +1,20 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; -import { EventBus } from "../../../core/EventBus"; -import { GameType } from "../../../core/game/Game"; -import { GameUpdateType } from "../../../core/game/GameUpdates"; -import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; -import { PauseGameEvent } from "../../Transport"; -import { ShowReplayPanelEvent } from "./ReplayPanel"; -import { ShowSettingsModalEvent } from "./SettingsModal"; import exitIcon from "../../../../resources/images/ExitIconWhite.svg"; import pauseIcon from "../../../../resources/images/PauseIconWhite.svg"; import playIcon from "../../../../resources/images/PlayIconWhite.svg"; import replayRegularIcon from "../../../../resources/images/ReplayRegularIconWhite.svg"; import replaySolidIcon from "../../../../resources/images/ReplaySolidIconWhite.svg"; import settingsIcon from "../../../../resources/images/SettingIconWhite.svg"; +import { EventBus } from "../../../core/EventBus"; +import { GameType } from "../../../core/game/Game"; +import { GameUpdateType } from "../../../core/game/GameUpdates"; +import { GameView } from "../../../core/game/GameView"; +import { PauseGameEvent } from "../../Transport"; import { translateText } from "../../Utils"; +import { Layer } from "./Layer"; +import { ShowReplayPanelEvent } from "./ReplayPanel"; +import { ShowSettingsModalEvent } from "./SettingsModal"; @customElement("game-right-sidebar") export class GameRightSidebar extends LitElement implements Layer { diff --git a/src/client/graphics/layers/GutterAdModal.ts b/src/client/graphics/layers/GutterAdModal.ts index 2b9ed8991..b2447db65 100644 --- a/src/client/graphics/layers/GutterAdModal.ts +++ b/src/client/graphics/layers/GutterAdModal.ts @@ -1,8 +1,8 @@ -import { EventBus, GameEvent } from "../../../core/EventBus"; -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; -import { Layer } from "./Layer"; +import { EventBus, GameEvent } from "../../../core/EventBus"; import { getGamesPlayed } from "../../Utils"; +import { Layer } from "./Layer"; export class GutterAdModalEvent implements GameEvent { constructor(public readonly isVisible: boolean) {} diff --git a/src/client/graphics/layers/HeadsUpMessage.ts b/src/client/graphics/layers/HeadsUpMessage.ts index 2bf546eb4..c5393712f 100644 --- a/src/client/graphics/layers/HeadsUpMessage.ts +++ b/src/client/graphics/layers/HeadsUpMessage.ts @@ -1,8 +1,8 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; import { translateText } from "../../Utils"; +import { Layer } from "./Layer"; @customElement("heads-up-message") export class HeadsUpMessage extends LitElement implements Layer { diff --git a/src/client/graphics/layers/Leaderboard.ts b/src/client/graphics/layers/Leaderboard.ts index b702a63ed..7d388bf48 100644 --- a/src/client/graphics/layers/Leaderboard.ts +++ b/src/client/graphics/layers/Leaderboard.ts @@ -1,11 +1,11 @@ -import { EventBus, GameEvent } from "../../../core/EventBus"; -import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property, state } from "lit/decorators.js"; -import { Layer } from "./Layer"; -import { renderNumber } from "../../Utils"; import { repeat } from "lit/directives/repeat.js"; import { translateText } from "../../../client/Utils"; +import { EventBus, GameEvent } from "../../../core/EventBus"; +import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; +import { renderNumber } from "../../Utils"; +import { Layer } from "./Layer"; type Entry = { name: string; @@ -169,10 +169,9 @@ export class Leaderboard extends LitElement implements Layer { } return html`
e.preventDefault()} >
this.setSort("tiles")} > ${translateText("leaderboard.owned")} - ${this._sortKey === "tiles" - ? this._sortOrder === "asc" - ? "⬆️" - : "⬇️" - : ""} + ${ + this._sortKey === "tiles" + ? this._sortOrder === "asc" + ? "⬆️" + : "⬇️" + : "" + }
this.setSort("gold")} > ${translateText("leaderboard.gold")} - ${this._sortKey === "gold" - ? this._sortOrder === "asc" - ? "⬆️" - : "⬇️" - : ""} + ${ + this._sortKey === "gold" + ? this._sortOrder === "asc" + ? "⬆️" + : "⬇️" + : "" + }
this.setSort("troops")} > ${translateText("leaderboard.troops")} - ${this._sortKey === "troops" - ? this._sortOrder === "asc" - ? "⬆️" - : "⬇️" - : ""} + ${ + this._sortKey === "troops" + ? this._sortOrder === "asc" + ? "⬆️" + : "⬇️" + : "" + }
@@ -226,9 +231,9 @@ export class Leaderboard extends LitElement implements Layer { (p) => p.player.id(), (player) => html`
this.handleRowClickPlayer(player.player)} >
diff --git a/src/client/graphics/layers/MainRadialMenu.ts b/src/client/graphics/layers/MainRadialMenu.ts index 97b9d577c..91356b571 100644 --- a/src/client/graphics/layers/MainRadialMenu.ts +++ b/src/client/graphics/layers/MainRadialMenu.ts @@ -1,26 +1,26 @@ -import { - COLORS, - MenuElementParams, - centerButtonElement, - rootMenuElement, -} from "./RadialMenuElements"; -import { GameView, PlayerView } from "../../../core/game/GameView"; -import { RadialMenu, RadialMenuConfig } from "./RadialMenu"; -import { BuildMenu } from "./BuildMenu"; -import { ChatIntegration } from "./ChatIntegration"; -import { ContextMenuEvent } from "../../InputHandler"; -import { EmojiTable } from "./EmojiTable"; -import { EventBus } from "../../../core/EventBus"; -import { Layer } from "./Layer"; import { LitElement } from "lit"; -import { PlayerActionHandler } from "./PlayerActionHandler"; -import { PlayerActions } from "../../../core/game/Game"; -import { PlayerPanel } from "./PlayerPanel"; -import { TileRef } from "../../../core/game/GameMap"; -import { TransformHandler } from "../TransformHandler"; -import { UIState } from "../UIState"; import { customElement } from "lit/decorators.js"; import swordIcon from "../../../../resources/images/SwordIconWhite.svg"; +import { EventBus } from "../../../core/EventBus"; +import { PlayerActions } from "../../../core/game/Game"; +import { TileRef } from "../../../core/game/GameMap"; +import { GameView, PlayerView } from "../../../core/game/GameView"; +import { ContextMenuEvent } from "../../InputHandler"; +import { TransformHandler } from "../TransformHandler"; +import { UIState } from "../UIState"; +import { BuildMenu } from "./BuildMenu"; +import { ChatIntegration } from "./ChatIntegration"; +import { EmojiTable } from "./EmojiTable"; +import { Layer } from "./Layer"; +import { PlayerActionHandler } from "./PlayerActionHandler"; +import { PlayerPanel } from "./PlayerPanel"; +import { RadialMenu, RadialMenuConfig } from "./RadialMenu"; +import { + COLORS, + centerButtonElement, + MenuElementParams, + rootMenuElement, +} from "./RadialMenuElements"; @customElement("main-radial-menu") export class MainRadialMenu extends LitElement implements Layer { @@ -90,13 +90,7 @@ export class MainRadialMenu extends LitElement implements Layer { const actions = await myPlayer.actions(tile); // Stale check: user might have clicked somewhere else already if (this.clickedTile !== tile) return; - this.updatePlayerActions( - myPlayer, - actions, - tile, - event.x, - event.y, - ); + this.updatePlayerActions(myPlayer, actions, tile, event.x, event.y); } catch (err) { console.error("Failed to fetch player actions:", err); } @@ -152,11 +146,7 @@ export class MainRadialMenu extends LitElement implements Layer { try { const actions = await myPlayer.actions(tile); if (this.clickedTile !== tile) return; // stale - this.updatePlayerActions( - myPlayer, - actions, - tile, - ); + this.updatePlayerActions(myPlayer, actions, tile); } catch (err) { console.error("Failed to refresh player actions:", err); } diff --git a/src/client/graphics/layers/MultiTabModal.ts b/src/client/graphics/layers/MultiTabModal.ts index 412d0f18e..ce36c5e3e 100644 --- a/src/client/graphics/layers/MultiTabModal.ts +++ b/src/client/graphics/layers/MultiTabModal.ts @@ -1,11 +1,11 @@ -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, property, state } from "lit/decorators.js"; import { GameEnv } from "../../../core/configuration/Config"; import { GameType } from "../../../core/game/Game"; import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; import { MultiTabDetector } from "../../MultiTabDetector"; import { translateText } from "../../Utils"; +import { Layer } from "./Layer"; @customElement("multi-tab-modal") export class MultiTabModal extends LitElement implements Layer { diff --git a/src/client/graphics/layers/NameLayer.ts b/src/client/graphics/layers/NameLayer.ts index c089e04bd..aa3603622 100644 --- a/src/client/graphics/layers/NameLayer.ts +++ b/src/client/graphics/layers/NameLayer.ts @@ -1,13 +1,3 @@ -import { AllPlayers, Cell, nukeTypes } from "../../../core/game/Game"; -import { GameView, PlayerView } from "../../../core/game/GameView"; -import { createCanvas, renderNumber, renderTroops } from "../../Utils"; -import { AlternateViewEvent } from "../../InputHandler"; -import { EventBus } from "../../../core/EventBus"; -import { Layer } from "./Layer"; -import { PseudoRandom } from "../../../core/PseudoRandom"; -import { Theme } from "../../../core/configuration/Config"; -import { TransformHandler } from "../TransformHandler"; -import { UserSettings } from "../../../core/game/UserSettings"; import allianceIcon from "../../../../resources/images/AllianceIcon.svg"; import allianceRequestBlackIcon from "../../../../resources/images/AllianceRequestBlackIcon.svg"; import allianceRequestWhiteIcon from "../../../../resources/images/AllianceRequestWhiteIcon.svg"; @@ -17,10 +7,20 @@ import embargoBlackIcon from "../../../../resources/images/EmbargoBlackIcon.svg" import embargoWhiteIcon from "../../../../resources/images/EmbargoWhiteIcon.svg"; import nukeRedIcon from "../../../../resources/images/NukeIconRed.svg"; import nukeWhiteIcon from "../../../../resources/images/NukeIconWhite.svg"; -import { renderPlayerFlag } from "../../../core/CustomFlag"; import shieldIcon from "../../../../resources/images/ShieldIconBlack.svg"; import targetIcon from "../../../../resources/images/TargetIcon.svg"; import traitorIcon from "../../../../resources/images/TraitorIcon.svg"; +import { renderPlayerFlag } from "../../../core/CustomFlag"; +import { Theme } from "../../../core/configuration/Config"; +import { EventBus } from "../../../core/EventBus"; +import { AllPlayers, Cell, nukeTypes } from "../../../core/game/Game"; +import { GameView, PlayerView } from "../../../core/game/GameView"; +import { UserSettings } from "../../../core/game/UserSettings"; +import { PseudoRandom } from "../../../core/PseudoRandom"; +import { AlternateViewEvent } from "../../InputHandler"; +import { createCanvas, renderNumber, renderTroops } from "../../Utils"; +import { TransformHandler } from "../TransformHandler"; +import { Layer } from "./Layer"; class RenderInfo { public icons: Map = new Map(); // Track icon elements @@ -611,8 +611,8 @@ export class NameLayer implements Layer { // Position element with scale if (render.location && render.location !== oldLocation) { const scale = Math.min(baseSize * 0.25, 3); - render.element.style.transform = - `translate(${render.location.x}px, ${render.location.y}px) translate(-50%, -50%) scale(${scale})`; + // eslint-disable-next-line max-len + render.element.style.transform = `translate(${render.location.x}px, ${render.location.y}px) translate(-50%, -50%) scale(${scale})`; } } diff --git a/src/client/graphics/layers/OptionsMenu.ts b/src/client/graphics/layers/OptionsMenu.ts index 130977c68..1af1edb8f 100644 --- a/src/client/graphics/layers/OptionsMenu.ts +++ b/src/client/graphics/layers/OptionsMenu.ts @@ -1,14 +1,14 @@ -import { AlternateViewEvent, RedrawGraphicsEvent } from "../../InputHandler"; -import { LitElement, html } from "lit"; +import { html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; import { EventBus } from "../../../core/EventBus"; import { GameType } from "../../../core/game/Game"; import { GameUpdateType } from "../../../core/game/GameUpdates"; import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; -import { PauseGameEvent } from "../../Transport"; import { UserSettings } from "../../../core/game/UserSettings"; +import { AlternateViewEvent, RedrawGraphicsEvent } from "../../InputHandler"; +import { PauseGameEvent } from "../../Transport"; import { translateText } from "../../Utils"; +import { Layer } from "./Layer"; const button = ({ classes = "", @@ -209,10 +209,7 @@ export class OptionsMenu extends LitElement implements Layer {
${button({ onClick: this.onTerrainButtonClick, diff --git a/src/client/graphics/layers/PlayerActionHandler.ts b/src/client/graphics/layers/PlayerActionHandler.ts index 819cf1263..87cf7213a 100644 --- a/src/client/graphics/layers/PlayerActionHandler.ts +++ b/src/client/graphics/layers/PlayerActionHandler.ts @@ -1,4 +1,7 @@ +import { EventBus } from "../../../core/EventBus"; import { PlayerActions, PlayerID } from "../../../core/game/Game"; +import { TileRef } from "../../../core/game/GameMap"; +import { PlayerView } from "../../../core/game/GameView"; import { SendAllianceRequestIntentEvent, SendAttackIntentEvent, @@ -13,9 +16,6 @@ import { SendSpawnIntentEvent, SendTargetPlayerIntentEvent, } from "../../Transport"; -import { EventBus } from "../../../core/EventBus"; -import { PlayerView } from "../../../core/game/GameView"; -import { TileRef } from "../../../core/game/GameMap"; import { UIState } from "../UIState"; export class PlayerActionHandler { diff --git a/src/client/graphics/layers/PlayerInfoOverlay.ts b/src/client/graphics/layers/PlayerInfoOverlay.ts index 8074f1081..97c17fedd 100644 --- a/src/client/graphics/layers/PlayerInfoOverlay.ts +++ b/src/client/graphics/layers/PlayerInfoOverlay.ts @@ -1,6 +1,9 @@ -import { ContextMenuEvent, MouseMoveEvent } from "../../InputHandler"; -import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; -import { LitElement, TemplateResult, html } from "lit"; +import { html, LitElement, TemplateResult } from "lit"; +import { customElement, property, state } from "lit/decorators.js"; +import { ref } from "lit-html/directives/ref.js"; +import { translateText } from "../../../client/Utils"; +import { renderPlayerFlag } from "../../../core/CustomFlag"; +import { EventBus } from "../../../core/EventBus"; import { PlayerProfile, PlayerType, @@ -8,16 +11,13 @@ import { Unit, UnitType, } from "../../../core/game/Game"; -import { customElement, property, state } from "lit/decorators.js"; -import { renderNumber, renderTroops } from "../../Utils"; -import { CloseRadialMenuEvent } from "./RadialMenu"; -import { EventBus } from "../../../core/EventBus"; -import { Layer } from "./Layer"; import { TileRef } from "../../../core/game/GameMap"; +import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; +import { ContextMenuEvent, MouseMoveEvent } from "../../InputHandler"; +import { renderNumber, renderTroops } from "../../Utils"; import { TransformHandler } from "../TransformHandler"; -import { ref } from "lit-html/directives/ref.js"; -import { renderPlayerFlag } from "../../../core/CustomFlag"; -import { translateText } from "../../../client/Utils"; +import { Layer } from "./Layer"; +import { CloseRadialMenuEvent } from "./RadialMenu"; function euclideanDistWorld( coord: { x: number; y: number }, @@ -222,17 +222,18 @@ export class PlayerInfoOverlay extends LitElement implements Layer { return html`
- ${this.showDetails - ? html` - ${player.team() !== null - ? html`
+ ${ + this.showDetails + ? html` + ${ + player.team() !== null + ? html`
${translateText("player_info_overlay.team")}: ${player.team()}
` - : ""} + : "" + }
${translateText("player_info_overlay.type")}: ${playerType}
- ${player.troops() >= 1 - ? html`
+ ${ + player.troops() >= 1 + ? html`
${translateText("player_info_overlay.d_troops")}: ${renderTroops(player.troops())}
` - : ""} - ${attackingTroops >= 1 - ? html`
+ : "" + } + ${ + attackingTroops >= 1 + ? html`
${translateText("player_info_overlay.a_troops")}: ${renderTroops(attackingTroops)}
` - : ""} + : "" + }
${translateText("player_info_overlay.gold")}: ${renderNumber(player.gold())} @@ -310,7 +319,8 @@ export class PlayerInfoOverlay extends LitElement implements Layer { )} ${relationHtml} ` - : ""} + : "" + }
`; } @@ -328,14 +338,16 @@ export class PlayerInfoOverlay extends LitElement implements Layer {
${unit.type()}
- ${unit.hasHealth() - ? html` + ${ + unit.hasHealth() + ? html`
${translateText("player_info_overlay.health")}: ${unit.health()}
` - : ""} + : "" + }
`; diff --git a/src/client/graphics/layers/PlayerPanel.ts b/src/client/graphics/layers/PlayerPanel.ts index 0c97996a8..7296bc682 100644 --- a/src/client/graphics/layers/PlayerPanel.ts +++ b/src/client/graphics/layers/PlayerPanel.ts @@ -1,7 +1,20 @@ +import { html, LitElement } from "lit"; +import { customElement, state } from "lit/decorators.js"; +import allianceIcon from "../../../../resources/images/AllianceIconWhite.svg"; +import chatIcon from "../../../../resources/images/ChatIconWhite.svg"; +import donateGoldIcon from "../../../../resources/images/DonateGoldIconWhite.svg"; +import donateTroopIcon from "../../../../resources/images/DonateTroopIconWhite.svg"; +import emojiIcon from "../../../../resources/images/EmojiIconWhite.svg"; +import targetIcon from "../../../../resources/images/TargetIconWhite.svg"; +import traitorIcon from "../../../../resources/images/TraitorIconWhite.svg"; +import { translateText } from "../../../client/Utils"; +import { EventBus } from "../../../core/EventBus"; import { AllPlayers, PlayerActions } from "../../../core/game/Game"; -import { CloseViewEvent, MouseUpEvent } from "../../InputHandler"; +import { TileRef } from "../../../core/game/GameMap"; import { GameView, PlayerView } from "../../../core/game/GameView"; -import { LitElement, html } from "lit"; +import { flattenedEmojiTable } from "../../../core/Util"; +import Countries from "../../data/countries.json"; +import { CloseViewEvent, MouseUpEvent } from "../../InputHandler"; import { SendAllianceRequestIntentEvent, SendBreakAllianceIntentEvent, @@ -11,24 +24,11 @@ import { SendEmojiIntentEvent, SendTargetPlayerIntentEvent, } from "../../Transport"; -import { customElement, state } from "lit/decorators.js"; import { renderNumber, renderTroops } from "../../Utils"; -import { ChatModal } from "./ChatModal"; -import Countries from "../../data/countries.json"; -import { EmojiTable } from "./EmojiTable"; -import { EventBus } from "../../../core/EventBus"; -import { Layer } from "./Layer"; -import { TileRef } from "../../../core/game/GameMap"; import { UIState } from "../UIState"; -import allianceIcon from "../../../../resources/images/AllianceIconWhite.svg"; -import chatIcon from "../../../../resources/images/ChatIconWhite.svg"; -import donateGoldIcon from "../../../../resources/images/DonateGoldIconWhite.svg"; -import donateTroopIcon from "../../../../resources/images/DonateTroopIconWhite.svg"; -import emojiIcon from "../../../../resources/images/EmojiIconWhite.svg"; -import { flattenedEmojiTable } from "../../../core/Util"; -import targetIcon from "../../../../resources/images/TargetIconWhite.svg"; -import traitorIcon from "../../../../resources/images/TraitorIconWhite.svg"; -import { translateText } from "../../../client/Utils"; +import { ChatModal } from "./ChatModal"; +import { EmojiTable } from "./EmojiTable"; +import { Layer } from "./Layer"; @customElement("player-panel") export class PlayerPanel extends LitElement implements Layer { @@ -195,10 +195,7 @@ export class PlayerPanel extends LitElement implements Layer { const remainingTicks = expiresAt - this.g.ticks(); if (remainingTicks > 0) { - const remainingSeconds = Math.max( - 0, - Math.floor(remainingTicks / 10), - ); // 10 ticks per second + const remainingSeconds = Math.max(0, Math.floor(remainingTicks / 10)); // 10 ticks per second this.allianceExpiryText = this.formatDuration(remainingSeconds); } } else { @@ -246,7 +243,10 @@ export class PlayerPanel extends LitElement implements Layer { //flag icon in the playerPanel const flagCode = other.cosmetics.flag; - const country = typeof flagCode === "string" ? Countries.find((c) => c.code === flagCode) : undefined; + const country = + typeof flagCode === "string" + ? Countries.find((c) => c.code === flagCode) + : undefined; const flagName = country?.name; return html` @@ -283,8 +283,9 @@ export class PlayerPanel extends LitElement implements Layer {
- ${country - ? html` + ${ + country + ? html`
${translateText("player_panel.flag")} @@ -298,7 +299,8 @@ export class PlayerPanel extends LitElement implements Layer {
` - : ""} + : "" + }
@@ -333,9 +335,11 @@ export class PlayerPanel extends LitElement implements Layer { ${translateText("player_panel.traitor")}
- ${other.isTraitor() - ? translateText("player_panel.yes") - : translateText("player_panel.no")} + ${ + other.isTraitor() + ? translateText("player_panel.yes") + : translateText("player_panel.no") + }
@@ -355,9 +359,11 @@ export class PlayerPanel extends LitElement implements Layer { ${translateText("player_panel.embargo")}
- ${other.hasEmbargoAgainst(myPlayer) - ? translateText("player_panel.yes") - : translateText("player_panel.no")} + ${ + other.hasEmbargoAgainst(myPlayer) + ? translateText("player_panel.yes") + : translateText("player_panel.no") + }
@@ -371,17 +377,20 @@ export class PlayerPanel extends LitElement implements Layer { class="bg-opacity-50 bg-gray-700 rounded p-2 text-white max-w-72 max-h-20 overflow-y-auto" translate="no" > - ${other.allies().length > 0 - ? other - .allies() - .map((p) => p.name()) - .join(", ") - : translateText("player_panel.none")} + ${ + other.allies().length > 0 + ? other + .allies() + .map((p) => p.name()) + .join(", ") + : translateText("player_panel.none") + }
- ${this.allianceExpiryText !== null - ? html` + ${ + this.allianceExpiryText !== null + ? html`
${translateText("player_panel.alliance_time_remaining")} @@ -393,7 +402,8 @@ export class PlayerPanel extends LitElement implements Layer {
` - : ""} + : "" + }
@@ -406,8 +416,9 @@ export class PlayerPanel extends LitElement implements Layer { > Target - ${canTarget - ? html`` - : ""} - ${canBreakAlliance - ? html`` - : ""} - ${canSendAllianceRequest - ? html`` - : ""} - ${canDonateTroops - ? html`` - : ""} - ${canDonateGold - ? html`` - : ""} - ${canSendEmoji - ? html`` - : ""} + : "" + }
- ${canEmbargo && other !== myPlayer - ? html`` - : ""} - ${!canEmbargo && other !== myPlayer - ? html`` - : ""} + : "" + }
diff --git a/src/client/graphics/layers/RadialMenu.ts b/src/client/graphics/layers/RadialMenu.ts index d9740d5ba..2b5b027f1 100644 --- a/src/client/graphics/layers/RadialMenu.ts +++ b/src/client/graphics/layers/RadialMenu.ts @@ -1,16 +1,16 @@ /* eslint-disable max-lines */ import * as d3 from "d3"; +import backIcon from "../../../../resources/images/BackIconWhite.svg"; +import { EventBus, GameEvent } from "../../../core/EventBus"; +import { CloseViewEvent } from "../../InputHandler"; +import { translateText } from "../../Utils"; +import { Layer } from "./Layer"; import { CenterButtonElement, MenuElement, MenuElementParams, TooltipKey, } from "./RadialMenuElements"; -import { EventBus, GameEvent } from "../../../core/EventBus"; -import { CloseViewEvent } from "../../InputHandler"; -import { Layer } from "./Layer"; -import backIcon from "../../../../resources/images/BackIconWhite.svg"; -import { translateText } from "../../Utils"; export class CloseRadialMenuEvent implements GameEvent { constructor() {} @@ -41,7 +41,9 @@ type CenterButtonState = "default" | "back"; type RequiredRadialMenuConfig = Required; export class RadialMenu implements Layer { - private menuElement: d3.Selection | undefined; + private menuElement: + | d3.Selection + | undefined; private tooltipElement: HTMLDivElement | null = null; private isVisible = false; @@ -150,9 +152,12 @@ export class RadialMenu implements Layer { .style("position", "absolute") .style("top", "50%") .style("left", "50%") - .style("transition", `top ${ - this.config.menuTransitionDuration}ms ease, left ${ - this.config.menuTransitionDuration}ms ease`) + .style( + "transition", + `top ${this.config.menuTransitionDuration}ms ease, left ${ + this.config.menuTransitionDuration + }ms ease`, + ) .style("transform", "translate(-50%, -50%)") .style("pointer-events", "all") .on("click", (event) => this.hideRadialMenu()); @@ -392,9 +397,10 @@ export class RadialMenu implements Layer { >, level: number, ) { - const onHover = (d: d3.PieArcDatum, path: d3.Selection< - d3.BaseType, unknown, HTMLElement, unknown - >) => { + const onHover = ( + d: d3.PieArcDatum, + path: d3.Selection, + ) => { const disabled = this.params === null || d.data.disabled(this.params); if (d.data.tooltipItems && d.data.tooltipItems.length > 0) { this.showTooltip(d.data.tooltipItems); @@ -413,9 +419,10 @@ export class RadialMenu implements Layer { path.attr("stroke-width", "3"); }; - const onMouseOut = (d: d3.PieArcDatum, path: d3.Selection< - d3.BaseType, unknown, HTMLElement, unknown - >) => { + const onMouseOut = ( + d: d3.PieArcDatum, + path: d3.Selection, + ) => { const disabled = this.params === null || d.data.disabled(this.params); if (this.submenuHoverTimeout !== null) { window.clearTimeout(this.submenuHoverTimeout); @@ -1072,14 +1079,18 @@ export class RadialMenu implements Layer { const vh = window.innerHeight; // If the menu cannot fully fit on an axis, pin it to the viewport center on that axis. - const clampedX = 2 * margin > vw ? vw / 2 : Math.min(Math.max(this.anchorX, margin), vw - margin); - const clampedY = 2 * margin > vh ? vh / 2 : Math.min(Math.max(this.anchorY, margin), vh - margin); + const clampedX = + 2 * margin > vw + ? vw / 2 + : Math.min(Math.max(this.anchorX, margin), vw - margin); + const clampedY = + 2 * margin > vh + ? vh / 2 + : Math.min(Math.max(this.anchorY, margin), vh - margin); if (this.menuElement === undefined) throw new Error("Not initialized"); const svgSel = this.menuElement.select("svg"); - svgSel - .style("top", `${clampedY}px`) - .style("left", `${clampedX}px`); + svgSel.style("top", `${clampedY}px`).style("left", `${clampedX}px`); } private readonly handleResize = () => { diff --git a/src/client/graphics/layers/RadialMenuElements.ts b/src/client/graphics/layers/RadialMenuElements.ts index 2db9e4f97..2e6a70fd5 100644 --- a/src/client/graphics/layers/RadialMenuElements.ts +++ b/src/client/graphics/layers/RadialMenuElements.ts @@ -1,15 +1,3 @@ -import { AllPlayers, PlayerActions, UnitType } from "../../../core/game/Game"; -import { BuildItemDisplay, BuildMenu, flattenedBuildTable } from "./BuildMenu"; -import { GameView, PlayerView } from "../../../core/game/GameView"; -import { renderNumber, translateText } from "../../Utils"; -import { ChatIntegration } from "./ChatIntegration"; -import { Config } from "../../../core/configuration/Config"; -import { EmojiTable } from "./EmojiTable"; -import { EventBus } from "../../../core/EventBus"; -import { PlayerActionHandler } from "./PlayerActionHandler"; -import { PlayerPanel } from "./PlayerPanel"; -import { TileRef } from "../../../core/game/GameMap"; -import { TooltipItem } from "./RadialMenu"; import allianceIcon from "../../../../resources/images/AllianceIconWhite.svg"; import boatIcon from "../../../../resources/images/BoatIconWhite.svg"; import buildIcon from "../../../../resources/images/BuildIconWhite.svg"; @@ -17,12 +5,24 @@ import chatIcon from "../../../../resources/images/ChatIconWhite.svg"; import donateGoldIcon from "../../../../resources/images/DonateGoldIconWhite.svg"; import donateTroopIcon from "../../../../resources/images/DonateTroopIconWhite.svg"; import emojiIcon from "../../../../resources/images/EmojiIconWhite.svg"; -import { flattenedEmojiTable } from "../../../core/Util"; import infoIcon from "../../../../resources/images/InfoIcon.svg"; import swordIcon from "../../../../resources/images/SwordIconWhite.svg"; import targetIcon from "../../../../resources/images/TargetIconWhite.svg"; import traitorIcon from "../../../../resources/images/TraitorIconWhite.svg"; import xIcon from "../../../../resources/images/XIcon.svg"; +import { Config } from "../../../core/configuration/Config"; +import { EventBus } from "../../../core/EventBus"; +import { AllPlayers, PlayerActions, UnitType } from "../../../core/game/Game"; +import { TileRef } from "../../../core/game/GameMap"; +import { GameView, PlayerView } from "../../../core/game/GameView"; +import { flattenedEmojiTable } from "../../../core/Util"; +import { renderNumber, translateText } from "../../Utils"; +import { BuildItemDisplay, BuildMenu, flattenedBuildTable } from "./BuildMenu"; +import { ChatIntegration } from "./ChatIntegration"; +import { EmojiTable } from "./EmojiTable"; +import { PlayerActionHandler } from "./PlayerActionHandler"; +import { PlayerPanel } from "./PlayerPanel"; +import { TooltipItem } from "./RadialMenu"; export type MenuElementParams = { myPlayer: PlayerView; diff --git a/src/client/graphics/layers/RailroadLayer.ts b/src/client/graphics/layers/RailroadLayer.ts index d69494a36..0d4e0afff 100644 --- a/src/client/graphics/layers/RailroadLayer.ts +++ b/src/client/graphics/layers/RailroadLayer.ts @@ -1,15 +1,15 @@ +import { Colord } from "colord"; +import { Theme } from "../../../core/configuration/Config"; +import { PlayerID } from "../../../core/game/Game"; +import { TileRef } from "../../../core/game/GameMap"; import { GameUpdateType, + RailroadUpdate, RailTile, RailType, - RailroadUpdate, } from "../../../core/game/GameUpdates"; -import { Colord } from "colord"; import { GameView } from "../../../core/game/GameView"; import { Layer } from "./Layer"; -import { PlayerID } from "../../../core/game/Game"; -import { Theme } from "../../../core/configuration/Config"; -import { TileRef } from "../../../core/game/GameMap"; import { getRailroadRects } from "./RailroadSprites"; type RailRef = { diff --git a/src/client/graphics/layers/ReplayPanel.ts b/src/client/graphics/layers/ReplayPanel.ts index fc8ca7700..b0963de89 100644 --- a/src/client/graphics/layers/ReplayPanel.ts +++ b/src/client/graphics/layers/ReplayPanel.ts @@ -1,14 +1,14 @@ -import { LitElement, html } from "lit"; -import { - ReplaySpeedMultiplier, - defaultReplaySpeedMultiplier, -} from "../../utilities/ReplaySpeedMultiplier"; +import { html, LitElement } from "lit"; import { customElement, property, state } from "lit/decorators.js"; import { EventBus } from "../../../core/EventBus"; import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; import { ReplaySpeedChangeEvent } from "../../InputHandler"; import { translateText } from "../../Utils"; +import { + defaultReplaySpeedMultiplier, + ReplaySpeedMultiplier, +} from "../../utilities/ReplaySpeedMultiplier"; +import { Layer } from "./Layer"; export class ShowReplayPanelEvent { constructor( @@ -71,9 +71,11 @@ export class ReplayPanel extends LitElement implements Layer { @contextmenu=${(e: Event) => e.preventDefault()} >
${this.renderSpeedButton(ReplaySpeedMultiplier.slow, "×0.5")} @@ -92,9 +94,9 @@ export class ReplayPanel extends LitElement implements Layer { const isActive = this._replaySpeedMultiplier === value; return html`
- ${this.alternateView - ? translateText("user_setting.terrain_enabled") - : translateText("user_setting.terrain_disabled")} + ${ + this.alternateView + ? translateText("user_setting.terrain_enabled") + : translateText("user_setting.terrain_disabled") + }
- ${this.alternateView - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.alternateView + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
@@ -222,15 +226,19 @@ export class SettingsModal extends LitElement implements Layer { ${translateText("user_setting.emojis_label")}
- ${this.userSettings?.emojis() - ? translateText("user_setting.emojis_visible") - : translateText("user_setting.emojis_hidden")} + ${ + this.userSettings?.emojis() + ? translateText("user_setting.emojis_visible") + : translateText("user_setting.emojis_hidden") + }
- ${this.userSettings?.emojis() - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.userSettings?.emojis() + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
@@ -250,15 +258,19 @@ export class SettingsModal extends LitElement implements Layer { ${translateText("user_setting.dark_mode_label")}
- ${this.userSettings?.darkMode() - ? translateText("user_setting.dark_mode_enabled") - : translateText("user_setting.light_mode_enabled")} + ${ + this.userSettings?.darkMode() + ? translateText("user_setting.dark_mode_enabled") + : translateText("user_setting.light_mode_enabled") + }
- ${this.userSettings?.darkMode() - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.userSettings?.darkMode() + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
@@ -278,15 +290,19 @@ export class SettingsModal extends LitElement implements Layer { ${translateText("user_setting.special_effects_label")}
- ${this.userSettings?.fxLayer() - ? translateText("user_setting.special_effects_enabled") - : translateText("user_setting.special_effects_disabled")} + ${ + this.userSettings?.fxLayer() + ? translateText("user_setting.special_effects_enabled") + : translateText("user_setting.special_effects_disabled") + }
- ${this.userSettings?.fxLayer() - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.userSettings?.fxLayer() + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
@@ -306,15 +322,19 @@ export class SettingsModal extends LitElement implements Layer { ${translateText("user_setting.structure_sprites_label")}
- ${this.userSettings?.structureSprites() - ? translateText("user_setting.structure_sprites_enabled") - : translateText("user_setting.structure_sprites_disabled")} + ${ + this.userSettings?.structureSprites() + ? translateText("user_setting.structure_sprites_enabled") + : translateText("user_setting.structure_sprites_disabled") + }
- ${this.userSettings?.structureSprites() - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.userSettings?.structureSprites() + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
@@ -329,15 +349,19 @@ export class SettingsModal extends LitElement implements Layer { ${translateText("user_setting.anonymous_names_label")}
- ${this.userSettings?.anonymousNames() - ? translateText("user_setting.anonymous_names_enabled") - : translateText("user_setting.real_names_shown")} + ${ + this.userSettings?.anonymousNames() + ? translateText("user_setting.anonymous_names_enabled") + : translateText("user_setting.real_names_shown") + }
- ${this.userSettings?.anonymousNames() - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.userSettings?.anonymousNames() + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
@@ -352,15 +376,19 @@ export class SettingsModal extends LitElement implements Layer { ${translateText("user_setting.left_click_menu")}
- ${this.userSettings?.leftClickOpensMenu() - ? translateText("user_setting.left_click_opens_menu") - : translateText("user_setting.right_click_opens_menu")} + ${ + this.userSettings?.leftClickOpensMenu() + ? translateText("user_setting.left_click_opens_menu") + : translateText("user_setting.right_click_opens_menu") + }
- ${this.userSettings?.leftClickOpensMenu() - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.userSettings?.leftClickOpensMenu() + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
@@ -380,17 +408,23 @@ export class SettingsModal extends LitElement implements Layer { ${translateText("user_setting.performance_overlay_label")}
- ${this.userSettings?.performanceOverlay() - ? translateText("user_setting.performance_overlay_enabled") - : translateText( - "user_setting.performance_overlay_disabled", - )} + ${ + this.userSettings?.performanceOverlay() + ? translateText( + "user_setting.performance_overlay_enabled", + ) + : translateText( + "user_setting.performance_overlay_disabled", + ) + }
- ${this.userSettings?.performanceOverlay() - ? translateText("user_setting.on") - : translateText("user_setting.off")} + ${ + this.userSettings?.performanceOverlay() + ? translateText("user_setting.on") + : translateText("user_setting.off") + }
diff --git a/src/client/graphics/layers/SpawnAd.ts b/src/client/graphics/layers/SpawnAd.ts index 960260af5..636b4c512 100644 --- a/src/client/graphics/layers/SpawnAd.ts +++ b/src/client/graphics/layers/SpawnAd.ts @@ -1,9 +1,9 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; -import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; -import { getGamesPlayed } from "../../Utils"; import { translateText } from "../../../client/Utils"; +import { GameView } from "../../../core/game/GameView"; +import { getGamesPlayed } from "../../Utils"; +import { Layer } from "./Layer"; const AD_TYPE = "bottom_rail"; const AD_CONTAINER_ID = "bottom-rail-ad-container"; @@ -125,11 +125,13 @@ export class SpawnAd extends LitElement implements Layer { id="${AD_CONTAINER_ID}" class="w-full h-full flex items-center justify-center" > - ${!this.adLoaded - ? html`${translateText("spawn_ad.loading")}` - : ""} + : "" + } `; diff --git a/src/client/graphics/layers/SpawnTimer.ts b/src/client/graphics/layers/SpawnTimer.ts index bd21e3d40..409efbec1 100644 --- a/src/client/graphics/layers/SpawnTimer.ts +++ b/src/client/graphics/layers/SpawnTimer.ts @@ -1,7 +1,7 @@ import { GameMode, Team } from "../../../core/game/Game"; import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; import { TransformHandler } from "../TransformHandler"; +import { Layer } from "./Layer"; export class SpawnTimer implements Layer { private ratios = [0]; diff --git a/src/client/graphics/layers/StructureIconsLayer.ts b/src/client/graphics/layers/StructureIconsLayer.ts index 71f6d1ebd..5f569496c 100644 --- a/src/client/graphics/layers/StructureIconsLayer.ts +++ b/src/client/graphics/layers/StructureIconsLayer.ts @@ -1,20 +1,20 @@ import * as PIXI from "pixi.js"; -import { Cell, PlayerID, UnitType } from "../../../core/game/Game"; -import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; -import { EventBus } from "../../../core/EventBus"; -import { GameUpdateType } from "../../../core/game/GameUpdates"; -import { Layer } from "./Layer"; import { OutlineFilter } from "pixi-filters"; -import SAMMissileIcon from "../../../../resources/images/SamLauncherUnit.png"; -import { Theme } from "../../../core/configuration/Config"; -import { ToggleStructureEvent } from "../../InputHandler"; -import { TransformHandler } from "../TransformHandler"; -import anchorIcon from "../../../../resources/images/AnchorIcon.png"; import bitmapFont from "../../../../resources/fonts/round_6x6_modified.xml"; +import anchorIcon from "../../../../resources/images/AnchorIcon.png"; import cityIcon from "../../../../resources/images/CityIcon.png"; import factoryIcon from "../../../../resources/images/FactoryUnit.png"; import missileSiloIcon from "../../../../resources/images/MissileSiloUnit.png"; +import SAMMissileIcon from "../../../../resources/images/SamLauncherUnit.png"; import shieldIcon from "../../../../resources/images/ShieldIcon.png"; +import { Theme } from "../../../core/configuration/Config"; +import { EventBus } from "../../../core/EventBus"; +import { Cell, PlayerID, UnitType } from "../../../core/game/Game"; +import { GameUpdateType } from "../../../core/game/GameUpdates"; +import { GameView, PlayerView, UnitView } from "../../../core/game/GameView"; +import { ToggleStructureEvent } from "../../InputHandler"; +import { TransformHandler } from "../TransformHandler"; +import { Layer } from "./Layer"; type ShapeType = "triangle" | "square" | "pentagon" | "octagon" | "circle"; @@ -357,12 +357,12 @@ export class StructureIconsLayer implements Layer { const shape = STRUCTURE_SHAPES[structureType]; const texture = shape ? this.createIcon( - unit.owner(), - structureType, - isConstruction, - shape, - renderIcon, - ) + unit.owner(), + structureType, + isConstruction, + shape, + renderIcon, + ) : PIXI.Texture.EMPTY; this.textureCache.set(cacheKey, texture); diff --git a/src/client/graphics/layers/StructureLayer.ts b/src/client/graphics/layers/StructureLayer.ts index b02d21402..f32a74b78 100644 --- a/src/client/graphics/layers/StructureLayer.ts +++ b/src/client/graphics/layers/StructureLayer.ts @@ -1,18 +1,18 @@ -import { Cell, UnitType } from "../../../core/game/Game"; import { Colord, colord } from "colord"; -import { GameView, UnitView } from "../../../core/game/GameView"; -import { euclDistFN, isometricDistFN } from "../../../core/game/GameMap"; -import { EventBus } from "../../../core/EventBus"; -import { GameUpdateType } from "../../../core/game/GameUpdates"; -import { Layer } from "./Layer"; -import SAMMissileIcon from "../../../../resources/non-commercial/images/buildings/silo4.png"; -import { Theme } from "../../../core/configuration/Config"; -import { TransformHandler } from "../TransformHandler"; -import anchorIcon from "../../../../resources/non-commercial/images/buildings/port1.png"; import cityIcon from "../../../../resources/non-commercial/images/buildings/cityAlt1.png"; import factoryIcon from "../../../../resources/non-commercial/images/buildings/factoryAlt1.png"; -import missileSiloIcon from "../../../../resources/non-commercial/images/buildings/silo1.png"; import shieldIcon from "../../../../resources/non-commercial/images/buildings/fortAlt3.png"; +import anchorIcon from "../../../../resources/non-commercial/images/buildings/port1.png"; +import missileSiloIcon from "../../../../resources/non-commercial/images/buildings/silo1.png"; +import SAMMissileIcon from "../../../../resources/non-commercial/images/buildings/silo4.png"; +import { Theme } from "../../../core/configuration/Config"; +import { EventBus } from "../../../core/EventBus"; +import { Cell, UnitType } from "../../../core/game/Game"; +import { euclDistFN, isometricDistFN } from "../../../core/game/GameMap"; +import { GameUpdateType } from "../../../core/game/GameUpdates"; +import { GameView, UnitView } from "../../../core/game/GameView"; +import { TransformHandler } from "../TransformHandler"; +import { Layer } from "./Layer"; const underConstructionColor = colord({ r: 150, g: 150, b: 150 }); diff --git a/src/client/graphics/layers/TeamStats.ts b/src/client/graphics/layers/TeamStats.ts index 8d3830633..fbbe8f7c1 100644 --- a/src/client/graphics/layers/TeamStats.ts +++ b/src/client/graphics/layers/TeamStats.ts @@ -1,9 +1,9 @@ +import { html, LitElement } from "lit"; +import { customElement, property } from "lit/decorators.js"; +import { EventBus } from "../../../core/EventBus"; import { GameMode, Team, UnitType } from "../../../core/game/Game"; import { GameView, PlayerView } from "../../../core/game/GameView"; -import { LitElement, html } from "lit"; -import { customElement, property } from "lit/decorators.js"; import { renderNumber, translateText } from "../../Utils"; -import { EventBus } from "../../../core/EventBus"; import { Layer } from "./Layer"; type TeamEntry = { @@ -130,8 +130,9 @@ export class TeamStats extends LitElement implements Layer {
${translateText("leaderboard.team")}
- ${this.showUnits - ? html` + ${ + this.showUnits + ? html`
${translateText("leaderboard.launchers")}
@@ -145,7 +146,7 @@ export class TeamStats extends LitElement implements Layer { ${translateText("leaderboard.cities")} ` - : html` + : html`
${translateText("leaderboard.owned")}
@@ -155,7 +156,8 @@ export class TeamStats extends LitElement implements Layer {
${translateText("leaderboard.troops")}
- `} + ` + } diff --git a/src/client/graphics/layers/TerrainLayer.ts b/src/client/graphics/layers/TerrainLayer.ts index e5d4d6b99..a88fe8904 100644 --- a/src/client/graphics/layers/TerrainLayer.ts +++ b/src/client/graphics/layers/TerrainLayer.ts @@ -1,7 +1,7 @@ -import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; import { Theme } from "../../../core/configuration/Config"; +import { GameView } from "../../../core/game/GameView"; import { TransformHandler } from "../TransformHandler"; +import { Layer } from "./Layer"; export class TerrainLayer implements Layer { private canvas: HTMLCanvasElement | undefined; diff --git a/src/client/graphics/layers/TerritoryLayer.ts b/src/client/graphics/layers/TerritoryLayer.ts index 58d77526b..fb25c6b0b 100644 --- a/src/client/graphics/layers/TerritoryLayer.ts +++ b/src/client/graphics/layers/TerritoryLayer.ts @@ -1,21 +1,21 @@ +import { PriorityQueue } from "@datastructures-js/priority-queue"; +import { Colord } from "colord"; +import { Theme } from "../../../core/configuration/Config"; +import { EventBus } from "../../../core/EventBus"; +import { Cell, PlayerType, UnitType } from "../../../core/game/Game"; +import { euclDistFN, TileRef } from "../../../core/game/GameMap"; +import { GameUpdateType } from "../../../core/game/GameUpdates"; +import { GameView, PlayerView } from "../../../core/game/GameView"; +import { UserSettings } from "../../../core/game/UserSettings"; +import { PseudoRandom } from "../../../core/PseudoRandom"; import { AlternateViewEvent, DragEvent, MouseOverEvent, RedrawGraphicsEvent, } from "../../InputHandler"; -import { Cell, PlayerType, UnitType } from "../../../core/game/Game"; -import { GameView, PlayerView } from "../../../core/game/GameView"; -import { TileRef, euclDistFN } from "../../../core/game/GameMap"; -import { Colord } from "colord"; -import { EventBus } from "../../../core/EventBus"; -import { GameUpdateType } from "../../../core/game/GameUpdates"; -import { Layer } from "./Layer"; -import { PriorityQueue } from "@datastructures-js/priority-queue"; -import { PseudoRandom } from "../../../core/PseudoRandom"; -import { Theme } from "../../../core/configuration/Config"; import { TransformHandler } from "../TransformHandler"; -import { UserSettings } from "../../../core/game/UserSettings"; +import { Layer } from "./Layer"; export class TerritoryLayer implements Layer { private readonly userSettings: UserSettings; @@ -323,7 +323,8 @@ export class TerritoryLayer implements Layer { initImageData() { this.game.forEachTile((tile) => { if (this.imageData === undefined) throw new Error("Not initialized"); - if (this.alternativeImageData === undefined) throw new Error("Not initialized"); + if (this.alternativeImageData === undefined) + throw new Error("Not initialized"); const cell = new Cell(this.game.x(tile), this.game.y(tile)); const index = cell.y * this.game.width() + cell.x; const offset = index * 4; @@ -337,7 +338,8 @@ export class TerritoryLayer implements Layer { if (this.highlightCanvas === undefined) throw new Error("Not initialized"); if (this.context === undefined) throw new Error("Not initialized"); if (this.imageData === undefined) throw new Error("Not initialized"); - if (this.alternativeImageData === undefined) throw new Error("Not initialized"); + if (this.alternativeImageData === undefined) + throw new Error("Not initialized"); const now = Date.now(); if ( now > this.lastDragTime + this.nodrawDragDuration && @@ -413,7 +415,8 @@ export class TerritoryLayer implements Layer { return; } if (this.imageData === undefined) throw new Error("Not initialized"); - if (this.alternativeImageData === undefined) throw new Error("Not initialized"); + if (this.alternativeImageData === undefined) + throw new Error("Not initialized"); if (!this.game.hasOwner(tile)) { if (this.game.hasFallout(tile)) { @@ -509,7 +512,8 @@ export class TerritoryLayer implements Layer { } paintAlternateViewTile(tile: TileRef, other: PlayerView) { - if (this.alternativeImageData === undefined) throw new Error("Not initialized"); + if (this.alternativeImageData === undefined) + throw new Error("Not initialized"); const color = this.alternateViewColor(other); this.paintTile(this.alternativeImageData, tile, color, 255); } @@ -525,14 +529,16 @@ export class TerritoryLayer implements Layer { clearTile(tile: TileRef) { const offset = tile * 4; if (this.imageData === undefined) throw new Error("Not initialized"); - if (this.alternativeImageData === undefined) throw new Error("Not initialized"); + if (this.alternativeImageData === undefined) + throw new Error("Not initialized"); this.imageData.data[offset + 3] = 0; // Set alpha to 0 (fully transparent) this.alternativeImageData.data[offset + 3] = 0; // Set alpha to 0 (fully transparent) } clearAlternativeTile(tile: TileRef) { const offset = tile * 4; - if (this.alternativeImageData === undefined) throw new Error("Not initialized"); + if (this.alternativeImageData === undefined) + throw new Error("Not initialized"); this.alternativeImageData.data[offset + 3] = 0; // Set alpha to 0 (fully transparent) } diff --git a/src/client/graphics/layers/UILayer.ts b/src/client/graphics/layers/UILayer.ts index bfaa63b16..d345d40b8 100644 --- a/src/client/graphics/layers/UILayer.ts +++ b/src/client/graphics/layers/UILayer.ts @@ -1,14 +1,14 @@ -import { GameView, UnitView } from "../../../core/game/GameView"; import { Colord } from "colord"; -import { EventBus } from "../../../core/EventBus"; -import { GameUpdateType } from "../../../core/game/GameUpdates"; -import { Layer } from "./Layer"; -import { ProgressBar } from "../ProgressBar"; import { Theme } from "../../../core/configuration/Config"; -import { TransformHandler } from "../TransformHandler"; -import { UnitSelectionEvent } from "../../InputHandler"; +import { EventBus } from "../../../core/EventBus"; import { UnitType } from "../../../core/game/Game"; +import { GameUpdateType } from "../../../core/game/GameUpdates"; +import { GameView, UnitView } from "../../../core/game/GameView"; import { UserSettings } from "../../../core/game/UserSettings"; +import { UnitSelectionEvent } from "../../InputHandler"; +import { ProgressBar } from "../ProgressBar"; +import { TransformHandler } from "../TransformHandler"; +import { Layer } from "./Layer"; const COLOR_PROGRESSION = [ "rgb(232, 25, 25)", @@ -69,8 +69,7 @@ export class UILayer implements Layer { this.game .updatesSinceLastTick() - ?.[GameUpdateType.Unit] - ?.map((unit) => this.game.unit(unit.id)) + ?.[GameUpdateType.Unit]?.map((unit) => this.game.unit(unit.id)) ?.forEach((unitView) => { if (unitView === undefined) return; this.onUnitEvent(unitView); diff --git a/src/client/graphics/layers/UnitDisplay.ts b/src/client/graphics/layers/UnitDisplay.ts index 2876d1e9a..a4df6fd31 100644 --- a/src/client/graphics/layers/UnitDisplay.ts +++ b/src/client/graphics/layers/UnitDisplay.ts @@ -1,17 +1,17 @@ -import { LitElement, html } from "lit"; -import { EventBus } from "../../../core/EventBus"; -import { GameView } from "../../../core/game/GameView"; -import { Layer } from "./Layer"; -import { ToggleStructureEvent } from "../../InputHandler"; -import { UnitType } from "../../../core/game/Game"; -import cityIcon from "../../../../resources/images/CityIconWhite.svg"; +import { html, LitElement } from "lit"; import { customElement } from "lit/decorators.js"; -import defensePostIcon from "../../../../resources/images/ShieldIconWhite.svg"; +import portIcon from "../../../../resources/images/AnchorIcon.png"; +import cityIcon from "../../../../resources/images/CityIconWhite.svg"; import factoryIcon from "../../../../resources/images/FactoryIconWhite.svg"; import missileSiloIcon from "../../../../resources/images/MissileSiloUnit.png"; -import portIcon from "../../../../resources/images/AnchorIcon.png"; -import { renderNumber } from "../../Utils"; +import defensePostIcon from "../../../../resources/images/ShieldIconWhite.svg"; import samLauncherIcon from "../../../../resources/non-commercial/svg/SamLauncherIconWhite.svg"; +import { EventBus } from "../../../core/EventBus"; +import { UnitType } from "../../../core/game/Game"; +import { GameView } from "../../../core/game/GameView"; +import { ToggleStructureEvent } from "../../InputHandler"; +import { renderNumber } from "../../Utils"; +import { Layer } from "./Layer"; @customElement("unit-display") export class UnitDisplay extends LitElement implements Layer { @@ -69,9 +69,9 @@ export class UnitDisplay extends LitElement implements Layer { return html`
unit.id())); this.unitToTrail.forEach((trail, unit) => { - if (this.unitTrailContext === undefined) throw new Error("Not initialized"); + if (this.unitTrailContext === undefined) + throw new Error("Not initialized"); for (const t of trail) { this.paintCell( this.game.x(t), @@ -309,7 +311,11 @@ export class UnitLayer implements Layer { const rel = this.relationship(unit); // Clear current and previous positions - this.clearCell(this.game.x(unit.lastTile()), this.game.y(unit.lastTile()), this.context); + this.clearCell( + this.game.x(unit.lastTile()), + this.game.y(unit.lastTile()), + this.context, + ); const oldTile = this.oldShellTile.get(unit); if (oldTile !== undefined) { this.clearCell(this.game.x(oldTile), this.game.y(oldTile), this.context); @@ -432,7 +438,11 @@ export class UnitLayer implements Layer { const rel = this.relationship(unit); if (this.context === undefined) throw new Error("Not initialized"); - this.clearCell(this.game.x(unit.lastTile()), this.game.y(unit.lastTile()), this.context); + this.clearCell( + this.game.x(unit.lastTile()), + this.game.y(unit.lastTile()), + this.context, + ); if (unit.isActive()) { // Paint area @@ -504,11 +514,7 @@ export class UnitLayer implements Layer { context.fillRect(x, y, 1, 1); } - clearCell( - x: number, - y: number, - context: CanvasRenderingContext2D, - ) { + clearCell(x: number, y: number, context: CanvasRenderingContext2D) { context.clearRect(x, y, 1, 1); } diff --git a/src/client/graphics/layers/WinModal.ts b/src/client/graphics/layers/WinModal.ts index 1f8605641..e8ce74b97 100644 --- a/src/client/graphics/layers/WinModal.ts +++ b/src/client/graphics/layers/WinModal.ts @@ -1,12 +1,12 @@ -import { LitElement, css, html } from "lit"; +import { css, html, LitElement } from "lit"; import { customElement, state } from "lit/decorators.js"; +import { translateText } from "../../../client/Utils"; import { EventBus } from "../../../core/EventBus"; import { GameUpdateType } from "../../../core/game/GameUpdates"; import { GameView } from "../../../core/game/GameView"; +import { SendWinnerEvent } from "../../Transport"; import { GutterAdModalEvent } from "./GutterAdModal"; import { Layer } from "./Layer"; -import { SendWinnerEvent } from "../../Transport"; -import { translateText } from "../../../client/Utils"; @customElement("win-modal") export class WinModal extends LitElement implements Layer { diff --git a/src/client/jwt.ts b/src/client/jwt.ts index 68a230bca..8b365adf6 100644 --- a/src/client/jwt.ts +++ b/src/client/jwt.ts @@ -1,3 +1,5 @@ +import { decodeJwt } from "jose"; +import { z } from "zod"; import { RefreshResponseSchema, TokenPayload, @@ -5,9 +7,7 @@ import { UserMeResponse, UserMeResponseSchema, } from "../core/ApiSchemas"; -import { decodeJwt } from "jose"; import { getServerConfigFromClient } from "../core/configuration/ConfigLoader"; -import { z } from "zod"; function getAudience() { const { hostname } = new URL(window.location.href); diff --git a/src/client/styles.css b/src/client/styles.css index 6afaafe46..fe34dc08d 100644 --- a/src/client/styles.css +++ b/src/client/styles.css @@ -134,7 +134,7 @@ .option-image { width: 100%; - aspect-ratio: 4/2; + aspect-ratio: 4 / 2; color: #aaa; transition: transform 0.2s ease-in-out; border-radius: 8px; @@ -373,17 +373,18 @@ label.option-card:hover { } #helpModal .city-icon { - mask: url("../../resources/images/CityIconWhite.svg") no-repeat center / cover; + mask: + url("../../resources/images/CityIconWhite.svg") no-repeat center / cover; } #helpModal .factory-icon { - mask: url("../../resources/images/FactoryIconWhite.svg") no-repeat center / - cover; + mask: + url("../../resources/images/FactoryIconWhite.svg") no-repeat center / cover; } #helpModal .defense-post-icon { - mask: url("../../resources/images/ShieldIconWhite.svg") no-repeat center / - cover; + mask: + url("../../resources/images/ShieldIconWhite.svg") no-repeat center / cover; } #helpModal .port-icon { @@ -391,27 +392,32 @@ label.option-card:hover { } #helpModal .warship-icon { - mask: url("../../resources/images/BattleshipIconWhite.svg") no-repeat center / + mask: + url("../../resources/images/BattleshipIconWhite.svg") no-repeat center / cover; } #helpModal .missile-silo-icon { - mask: url("../../resources/non-commercial/svg/MissileSiloIconWhite.svg") - no-repeat center / cover; + mask: + url("../../resources/non-commercial/svg/MissileSiloIconWhite.svg") no-repeat + center / cover; } #helpModal .sam-launcher-icon { - mask: url("../../resources/non-commercial/svg/SamLauncherIconWhite.svg") - no-repeat center / cover; + mask: + url("../../resources/non-commercial/svg/SamLauncherIconWhite.svg") no-repeat + center / cover; } #helpModal .atom-bomb-icon { - mask: url("../../resources/images/NukeIconWhite.svg") no-repeat center / cover; + mask: + url("../../resources/images/NukeIconWhite.svg") no-repeat center / cover; } #helpModal .hydrogen-bomb-icon { - mask: url("../../resources/images/MushroomCloudIconWhite.svg") no-repeat - center / cover; + mask: + url("../../resources/images/MushroomCloudIconWhite.svg") no-repeat center / + cover; } #helpModal .mirv-icon { @@ -419,7 +425,8 @@ label.option-card:hover { } #helpModal .chat-icon { - mask: url("../../resources/images/ChatIconWhite.svg") no-repeat center / cover; + mask: + url("../../resources/images/ChatIconWhite.svg") no-repeat center / cover; } #helpModal .target-icon { @@ -427,33 +434,35 @@ label.option-card:hover { } #helpModal .alliance-icon { - mask: url("../../resources/images/AllianceIconWhite.svg") no-repeat center / - cover; + mask: + url("../../resources/images/AllianceIconWhite.svg") no-repeat center / cover; } #helpModal .emoji-icon { - mask: url("../../resources/images/EmojiIconWhite.svg") no-repeat center / - cover; + mask: + url("../../resources/images/EmojiIconWhite.svg") no-repeat center / cover; } #helpModal .betray-icon { - mask: url("../../resources/images/TraitorIconWhite.svg") no-repeat center / - cover; + mask: + url("../../resources/images/TraitorIconWhite.svg") no-repeat center / cover; } #helpModal .donate-icon { - mask: url("../../resources/images/DonateTroopIconWhite.svg") no-repeat - center / cover; + mask: + url("../../resources/images/DonateTroopIconWhite.svg") no-repeat center / + cover; } #helpModal .donate-gold-icon { - mask: url("../../resources/images/DonateGoldIconWhite.svg") no-repeat center / + mask: + url("../../resources/images/DonateGoldIconWhite.svg") no-repeat center / cover; } #helpModal .build-icon { - mask: url("../../resources/images/BuildIconWhite.svg") no-repeat center / - cover; + mask: + url("../../resources/images/BuildIconWhite.svg") no-repeat center / cover; } #helpModal .info-icon { diff --git a/src/client/utilities/RenderUnitTypeOptions.ts b/src/client/utilities/RenderUnitTypeOptions.ts index 02569e654..71558c018 100644 --- a/src/client/utilities/RenderUnitTypeOptions.ts +++ b/src/client/utilities/RenderUnitTypeOptions.ts @@ -1,5 +1,5 @@ // renderUnitTypeOptions.ts -import { TemplateResult, html } from "lit"; +import { html, TemplateResult } from "lit"; import { UnitType } from "../../core/game/Game"; import { translateText } from "../Utils"; @@ -36,7 +36,7 @@ export function renderUnitTypeOptions({ type="checkbox" .checked=${disabledUnits.includes(type)} @change=${(e: Event) => { - const { checked } = (e.target as HTMLInputElement); + const { checked } = e.target as HTMLInputElement; toggleUnit(type, checked); }} /> diff --git a/src/core/ApiSchemas.ts b/src/core/ApiSchemas.ts index a46f2976a..208557e3d 100644 --- a/src/core/ApiSchemas.ts +++ b/src/core/ApiSchemas.ts @@ -1,6 +1,7 @@ // This file contains schemas for api.openfront.io -import { base64urlToUuid } from "./Base64"; + import { z } from "zod"; +import { base64urlToUuid } from "./Base64"; export const RefreshResponseSchema = z.object({ token: z.string(), diff --git a/src/core/CosmeticSchemas.ts b/src/core/CosmeticSchemas.ts index c8950fcc1..af3469fe1 100644 --- a/src/core/CosmeticSchemas.ts +++ b/src/core/CosmeticSchemas.ts @@ -1,5 +1,5 @@ -import { RequiredPatternSchema } from "./Schemas"; import { z } from "zod"; +import { RequiredPatternSchema } from "./Schemas"; export const ProductSchema = z.object({ productId: z.string(), diff --git a/src/core/CustomFlag.ts b/src/core/CustomFlag.ts index 16f44a6c2..368e85cdf 100644 --- a/src/core/CustomFlag.ts +++ b/src/core/CustomFlag.ts @@ -4,11 +4,11 @@ const ANIMATION_DURATIONS: Record = { "bright-rainbow": 4000, "copper-glow": 3000, "gold-glow": 3000, - "lava": 6000, - "neon": 3000, - "rainbow": 4000, + lava: 6000, + neon: 3000, + rainbow: 4000, "silver-glow": 3000, - "water": 6200, + water: 6200, }; // TODO: Pass in cosmetics as a parameter when diff --git a/src/core/EventBus.ts b/src/core/EventBus.ts index 60e351d8f..4f4248046 100644 --- a/src/core/EventBus.ts +++ b/src/core/EventBus.ts @@ -6,8 +6,10 @@ export type EventConstructor = new ( ) => T; export class EventBus { - private readonly listeners: Map void>> = - new Map(); + private readonly listeners: Map< + EventConstructor, + Array<(event: GameEvent) => void> + > = new Map(); emit(event: T): void { const eventConstructor = event.constructor as EventConstructor; diff --git a/src/core/ExpressSchemas.ts b/src/core/ExpressSchemas.ts index 23491e470..36aa87b9a 100644 --- a/src/core/ExpressSchemas.ts +++ b/src/core/ExpressSchemas.ts @@ -1,6 +1,7 @@ // This file contians schemas for the primary openfront express server -import { GameInfoSchema } from "./Schemas"; + import { z } from "zod"; +import { GameInfoSchema } from "./Schemas"; export const ApiEnvResponseSchema = z.object({ game_env: z.string(), diff --git a/src/core/GameRunner.ts b/src/core/GameRunner.ts index b9c23465f..da26c867d 100644 --- a/src/core/GameRunner.ts +++ b/src/core/GameRunner.ts @@ -1,3 +1,7 @@ +import { placeName } from "../client/graphics/NameBoxCalculator"; +import { getConfig } from "./configuration/ConfigLoader"; +import { Executor } from "./execution/ExecutionManager"; +import { WinCheckExecution } from "./execution/WinCheckExecution"; import { AllPlayers, Attack, @@ -14,23 +18,19 @@ import { PlayerProfile, PlayerType, } from "./game/Game"; -import { ClientID, GameStartInfo, Turn } from "./Schemas"; +import { createGame } from "./game/GameImpl"; +import { TileRef } from "./game/GameMap"; +import { GameMapLoader } from "./game/GameMapLoader"; import { ErrorUpdate, GameUpdateType, GameUpdateViewData, } from "./game/GameUpdates"; -import { sanitize, simpleHash } from "./Util"; -import { Executor } from "./execution/ExecutionManager"; -import { GameMapLoader } from "./game/GameMapLoader"; -import { PseudoRandom } from "./PseudoRandom"; -import { TileRef } from "./game/GameMap"; -import { WinCheckExecution } from "./execution/WinCheckExecution"; -import { createGame } from "./game/GameImpl"; -import { fixProfaneUsername } from "./validations/username"; -import { getConfig } from "./configuration/ConfigLoader"; import { loadTerrainMap } from "./game/TerrainMapLoader"; -import { placeName } from "../client/graphics/NameBoxCalculator"; +import { PseudoRandom } from "./PseudoRandom"; +import { ClientID, GameStartInfo, Turn } from "./Schemas"; +import { sanitize, simpleHash } from "./Util"; +import { fixProfaneUsername } from "./validations/username"; export async function createGameRunner( gameStart: GameStartInfo, @@ -57,13 +57,13 @@ export async function createGameRunner( const nations = gameStart.config.disableNPCs ? [] : gameMap.manifest.nations.map( - (n) => - new Nation( - new Cell(n.coordinates[0], n.coordinates[1]), - n.strength, - new PlayerInfo(n.name, PlayerType.FakeHuman, null, random.nextID()), - ), - ); + (n) => + new Nation( + new Cell(n.coordinates[0], n.coordinates[1]), + n.strength, + new PlayerInfo(n.name, PlayerType.FakeHuman, null, random.nextID()), + ), + ); const game: Game = createGame( humans, diff --git a/src/core/Schemas.ts b/src/core/Schemas.ts index e70b9c960..2c58a95b4 100644 --- a/src/core/Schemas.ts +++ b/src/core/Schemas.ts @@ -1,3 +1,10 @@ +import { base64url } from "jose"; +import { z } from "zod"; +import quickChatData from "../../resources/QuickChat.json" with { + type: "json", +}; +import countries from "../client/data/countries.json" with { type: "json" }; +import { ID } from "./BaseSchemas"; import { AllPlayers, Difficulty, @@ -10,14 +17,9 @@ import { Trios, UnitType, } from "./game/Game"; -import { ID } from "./BaseSchemas"; import { PatternDecoder } from "./PatternDecoder"; import { PlayerStatsSchema } from "./StatsSchemas"; -import { base64url } from "jose"; -import countries from "../client/data/countries.json" with { type: "json" }; import { flattenedEmojiTable } from "./Util"; -import quickChatData from "../../resources/QuickChat.json" with { type: "json" }; -import { z } from "zod"; export type GameID = string; export type ClientID = string; diff --git a/src/core/StatsSchemas.ts b/src/core/StatsSchemas.ts index 6f58d84f2..41cb3a47e 100644 --- a/src/core/StatsSchemas.ts +++ b/src/core/StatsSchemas.ts @@ -1,5 +1,5 @@ -import { UnitType } from "./game/Game"; import { z } from "zod"; +import { UnitType } from "./game/Game"; export const BombUnitSchema = z.union([ z.literal("abomb"), diff --git a/src/core/Util.ts b/src/core/Util.ts index cb919dd72..162e5835e 100644 --- a/src/core/Util.ts +++ b/src/core/Util.ts @@ -1,8 +1,13 @@ +import DOMPurify from "dompurify"; +import { customAlphabet } from "nanoid"; +import { ID } from "./BaseSchemas"; +import { ServerConfig } from "./configuration/Config"; import { BOT_NAME_PREFIXES, BOT_NAME_SUFFIXES, } from "./execution/utils/BotNames"; import { Cell, Unit } from "./game/Game"; +import { GameMap, TileRef } from "./game/GameMap"; import { ClientID, GameConfig, @@ -12,11 +17,6 @@ import { Turn, Winner, } from "./Schemas"; -import { GameMap, TileRef } from "./game/GameMap"; -import DOMPurify from "dompurify"; -import { ID } from "./BaseSchemas"; -import { ServerConfig } from "./configuration/Config"; -import { customAlphabet } from "nanoid"; export function manhattanDistWrapped( c1: Cell, @@ -233,7 +233,12 @@ export function getClientID(gameID: GameID): ClientID { const cachedGame = localStorage.getItem("game_id"); const cachedClient = localStorage.getItem("client_id"); - if (gameID === cachedGame && cachedClient && ID.safeParse(cachedClient).success) return cachedClient; + if ( + gameID === cachedGame && + cachedClient && + ID.safeParse(cachedClient).success + ) + return cachedClient; const clientId = generateID(); localStorage.setItem("game_id", gameID); diff --git a/src/core/WorkerSchemas.ts b/src/core/WorkerSchemas.ts index f8ce25778..94b8ae08a 100644 --- a/src/core/WorkerSchemas.ts +++ b/src/core/WorkerSchemas.ts @@ -1,6 +1,7 @@ // This file contians schemas for the openfront worker express server -import { GameConfigSchema, GameRecordSchema } from "./Schemas"; + import { z } from "zod"; +import { GameConfigSchema, GameRecordSchema } from "./Schemas"; export const CreateGameInputSchema = GameConfigSchema.or( z diff --git a/src/core/configuration/ColorAllocator.ts b/src/core/configuration/ColorAllocator.ts index 97d24eadf..9c80ea4d5 100644 --- a/src/core/configuration/ColorAllocator.ts +++ b/src/core/configuration/ColorAllocator.ts @@ -1,5 +1,10 @@ import { Colord, extend } from "colord"; +import labPlugin from "colord/plugins/lab"; +import lchPlugin from "colord/plugins/lch"; +import Color from "colorjs.io"; import { ColoredTeams, Team } from "../game/Game"; +import { PseudoRandom } from "../PseudoRandom"; +import { simpleHash } from "../Util"; import { blueTeamColors, botTeamColors, @@ -10,11 +15,7 @@ import { tealTeamColors, yellowTeamColors, } from "./Colors"; -import Color from "colorjs.io"; -import { PseudoRandom } from "../PseudoRandom"; -import labPlugin from "colord/plugins/lab"; -import lchPlugin from "colord/plugins/lch"; -import { simpleHash } from "../Util"; + extend([lchPlugin]); extend([labPlugin]); diff --git a/src/core/configuration/Config.ts b/src/core/configuration/Config.ts index 16bf6bf3f..24780747b 100644 --- a/src/core/configuration/Config.ts +++ b/src/core/configuration/Config.ts @@ -1,3 +1,5 @@ +import { Colord } from "colord"; +import { JWK } from "jose"; import { Difficulty, Game, @@ -12,13 +14,11 @@ import { UnitInfo, UnitType, } from "../game/Game"; -import { GameConfig, GameID, TeamCountConfig } from "../Schemas"; import { GameMap, TileRef } from "../game/GameMap"; -import { Colord } from "colord"; -import { JWK } from "jose"; -import { NukeType } from "../StatsSchemas"; import { PlayerView } from "../game/GameView"; import { UserSettings } from "../game/UserSettings"; +import { GameConfig, GameID, TeamCountConfig } from "../Schemas"; +import { NukeType } from "../StatsSchemas"; export enum GameEnv { Dev, diff --git a/src/core/configuration/ConfigLoader.ts b/src/core/configuration/ConfigLoader.ts index 19667b45e..3bb7f53fc 100644 --- a/src/core/configuration/ConfigLoader.ts +++ b/src/core/configuration/ConfigLoader.ts @@ -1,9 +1,9 @@ -import { Config, GameEnv, ServerConfig } from "./Config"; -import { DevConfig, DevServerConfig } from "./DevConfig"; import { ApiEnvResponseSchema } from "../ExpressSchemas"; -import { DefaultConfig } from "./DefaultConfig"; -import { GameConfig } from "../Schemas"; import { UserSettings } from "../game/UserSettings"; +import { GameConfig } from "../Schemas"; +import { Config, GameEnv, ServerConfig } from "./Config"; +import { DefaultConfig } from "./DefaultConfig"; +import { DevConfig, DevServerConfig } from "./DevConfig"; import { preprodConfig } from "./PreprodConfig"; import { prodConfig } from "./ProdConfig"; diff --git a/src/core/configuration/DefaultConfig.ts b/src/core/configuration/DefaultConfig.ts index ba7ba83b6..2522651a5 100644 --- a/src/core/configuration/DefaultConfig.ts +++ b/src/core/configuration/DefaultConfig.ts @@ -1,5 +1,7 @@ /* eslint-disable max-lines */ -import { Config, GameEnv, NukeMagnitude, ServerConfig, Theme } from "./Config"; + +import { JWK } from "jose"; +import { z } from "zod"; import { Difficulty, Duos, @@ -12,23 +14,22 @@ import { PlayerInfo, PlayerType, Quads, - TerraNullius, TerrainType, + TerraNullius, Tick, Trios, UnitInfo, UnitType, } from "../game/Game"; +import { TileRef } from "../game/GameMap"; +import { PlayerView } from "../game/GameView"; +import { UserSettings } from "../game/UserSettings"; import { GameConfig, GameID, TeamCountConfig } from "../Schemas"; -import { assertNever, simpleHash, within } from "../Util"; -import { JWK } from "jose"; import { NukeType } from "../StatsSchemas"; +import { assertNever, simpleHash, within } from "../Util"; +import { Config, GameEnv, NukeMagnitude, ServerConfig, Theme } from "./Config"; import { PastelTheme } from "./PastelTheme"; import { PastelThemeDark } from "./PastelThemeDark"; -import { PlayerView } from "../game/GameView"; -import { TileRef } from "../game/GameMap"; -import { UserSettings } from "../game/UserSettings"; -import { z } from "zod"; const JwksSchema = z.object({ keys: z diff --git a/src/core/configuration/DevConfig.ts b/src/core/configuration/DevConfig.ts index 6f20d5df6..3a14b39bb 100644 --- a/src/core/configuration/DevConfig.ts +++ b/src/core/configuration/DevConfig.ts @@ -1,8 +1,8 @@ -import { DefaultConfig, DefaultServerConfig } from "./DefaultConfig"; -import { GameEnv, ServerConfig } from "./Config"; import { UnitInfo, UnitType } from "../game/Game"; -import { GameConfig } from "../Schemas"; import { UserSettings } from "../game/UserSettings"; +import { GameConfig } from "../Schemas"; +import { GameEnv, ServerConfig } from "./Config"; +import { DefaultConfig, DefaultServerConfig } from "./DefaultConfig"; export class DevServerConfig extends DefaultServerConfig { adminToken(): string { diff --git a/src/core/configuration/PastelTheme.ts b/src/core/configuration/PastelTheme.ts index 0c72cfe13..72db7689e 100644 --- a/src/core/configuration/PastelTheme.ts +++ b/src/core/configuration/PastelTheme.ts @@ -1,10 +1,10 @@ import { Colord, colord } from "colord"; -import { GameMap, TileRef } from "../game/GameMap"; import { PlayerType, Team, TerrainType } from "../game/Game"; -import { botColors, fallbackColors, humanColors, nationColors } from "./Colors"; -import { ColorAllocator } from "./ColorAllocator"; +import { GameMap, TileRef } from "../game/GameMap"; import { PlayerView } from "../game/GameView"; import { PseudoRandom } from "../PseudoRandom"; +import { ColorAllocator } from "./ColorAllocator"; +import { botColors, fallbackColors, humanColors, nationColors } from "./Colors"; import { Theme } from "./Config"; type ColorCache = Map; @@ -12,10 +12,19 @@ type ColorCache = Map; export class PastelTheme implements Theme { private readonly borderColorCache: ColorCache = new Map(); private readonly rand = new PseudoRandom(123); - private readonly humanColorAllocator = new ColorAllocator(humanColors, fallbackColors); + private readonly humanColorAllocator = new ColorAllocator( + humanColors, + fallbackColors, + ); private readonly botColorAllocator = new ColorAllocator(botColors, botColors); - private readonly teamColorAllocator = new ColorAllocator(humanColors, fallbackColors); - private readonly nationColorAllocator = new ColorAllocator(nationColors, nationColors); + private readonly teamColorAllocator = new ColorAllocator( + humanColors, + fallbackColors, + ); + private readonly nationColorAllocator = new ColorAllocator( + nationColors, + nationColors, + ); /* eslint-disable sort-keys */ private readonly background = colord({ r: 60, g: 60, b: 60 }); diff --git a/src/core/configuration/PastelThemeDark.ts b/src/core/configuration/PastelThemeDark.ts index cfed90ba5..8c5ba3ca5 100644 --- a/src/core/configuration/PastelThemeDark.ts +++ b/src/core/configuration/PastelThemeDark.ts @@ -1,10 +1,10 @@ import { Colord, colord } from "colord"; -import { GameMap, TileRef } from "../game/GameMap"; import { PlayerType, Team, TerrainType } from "../game/Game"; -import { botColors, fallbackColors, humanColors, nationColors } from "./Colors"; -import { ColorAllocator } from "./ColorAllocator"; +import { GameMap, TileRef } from "../game/GameMap"; import { PlayerView } from "../game/GameView"; import { PseudoRandom } from "../PseudoRandom"; +import { ColorAllocator } from "./ColorAllocator"; +import { botColors, fallbackColors, humanColors, nationColors } from "./Colors"; import { Theme } from "./Config"; type ColorCache = Map; @@ -12,10 +12,19 @@ type ColorCache = Map; export class PastelThemeDark implements Theme { private readonly borderColorCache: ColorCache = new Map(); private readonly rand = new PseudoRandom(123); - private readonly humanColorAllocator = new ColorAllocator(humanColors, fallbackColors); + private readonly humanColorAllocator = new ColorAllocator( + humanColors, + fallbackColors, + ); private readonly botColorAllocator = new ColorAllocator(botColors, botColors); - private readonly teamColorAllocator = new ColorAllocator(humanColors, fallbackColors); - private readonly nationColorAllocator = new ColorAllocator(nationColors, nationColors); + private readonly teamColorAllocator = new ColorAllocator( + humanColors, + fallbackColors, + ); + private readonly nationColorAllocator = new ColorAllocator( + nationColors, + nationColors, + ); /* eslint-disable sort-keys */ private readonly background = colord({ r: 0, g: 0, b: 0 }); diff --git a/src/core/configuration/PreprodConfig.ts b/src/core/configuration/PreprodConfig.ts index 75467cecb..a0567aaa9 100644 --- a/src/core/configuration/PreprodConfig.ts +++ b/src/core/configuration/PreprodConfig.ts @@ -1,5 +1,5 @@ -import { DefaultServerConfig } from "./DefaultConfig"; import { GameEnv } from "./Config"; +import { DefaultServerConfig } from "./DefaultConfig"; export const preprodConfig = new (class extends DefaultServerConfig { env(): GameEnv { diff --git a/src/core/configuration/ProdConfig.ts b/src/core/configuration/ProdConfig.ts index 24a671933..7bea841a8 100644 --- a/src/core/configuration/ProdConfig.ts +++ b/src/core/configuration/ProdConfig.ts @@ -1,5 +1,5 @@ -import { DefaultServerConfig } from "./DefaultConfig"; import { GameEnv } from "./Config"; +import { DefaultServerConfig } from "./DefaultConfig"; export const prodConfig = new (class extends DefaultServerConfig { numWorkers(): number { diff --git a/src/core/execution/AttackExecution.ts b/src/core/execution/AttackExecution.ts index 44bddccda..0991a1e2b 100644 --- a/src/core/execution/AttackExecution.ts +++ b/src/core/execution/AttackExecution.ts @@ -1,3 +1,4 @@ +import { renderTroops } from "../../client/Utils"; import { Attack, Execution, @@ -6,13 +7,12 @@ import { Player, PlayerID, PlayerType, - TerraNullius, TerrainType, + TerraNullius, } from "../game/Game"; -import { FlatBinaryHeap } from "./utils/FlatBinaryHeap"; // adjust path if needed -import { PseudoRandom } from "../PseudoRandom"; import { TileRef } from "../game/GameMap"; -import { renderTroops } from "../../client/Utils"; +import { PseudoRandom } from "../PseudoRandom"; +import { FlatBinaryHeap } from "./utils/FlatBinaryHeap"; // adjust path if needed const malusForRetreat = 25; export class AttackExecution implements Execution { @@ -209,7 +209,9 @@ export class AttackExecution implements Execution { throw new Error("Attack not initialized"); } let troopCount = this.attack.troops(); // cache troop count - const targetPlayer: Player | null = this.target.isPlayer() ? this.target : null; // cache target player + const targetPlayer: Player | null = this.target.isPlayer() + ? this.target + : null; // cache target player if (this.attack.retreated()) { if (targetPlayer !== null) { @@ -230,9 +232,10 @@ export class AttackExecution implements Execution { return; } - const alliance = this.target && this.target.isPlayer() - ? this._owner.allianceWith(this.target) - : null; + const alliance = + this.target && this.target.isPlayer() + ? this._owner.allianceWith(this.target) + : null; if (this.breakAlliance && alliance !== null) { this.breakAlliance = false; this._owner.breakAlliance(alliance); diff --git a/src/core/execution/BotExecution.ts b/src/core/execution/BotExecution.ts index 75d843632..f1685ddbb 100644 --- a/src/core/execution/BotExecution.ts +++ b/src/core/execution/BotExecution.ts @@ -1,7 +1,7 @@ import { Execution, Game, Player } from "../game/Game"; -import { BotBehavior } from "./utils/BotBehavior"; import { PseudoRandom } from "../PseudoRandom"; import { simpleHash } from "../Util"; +import { BotBehavior } from "./utils/BotBehavior"; export class BotExecution implements Execution { private active = true; diff --git a/src/core/execution/BotSpawner.ts b/src/core/execution/BotSpawner.ts index a0e9eeaaf..67b13eb95 100644 --- a/src/core/execution/BotSpawner.ts +++ b/src/core/execution/BotSpawner.ts @@ -1,10 +1,10 @@ -import { BOT_NAME_PREFIXES, BOT_NAME_SUFFIXES } from "./utils/BotNames"; import { Game, PlayerInfo, PlayerType } from "../game/Game"; -import { GameID } from "../Schemas"; -import { PseudoRandom } from "../PseudoRandom"; -import { SpawnExecution } from "./SpawnExecution"; import { TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; +import { GameID } from "../Schemas"; import { simpleHash } from "../Util"; +import { SpawnExecution } from "./SpawnExecution"; +import { BOT_NAME_PREFIXES, BOT_NAME_SUFFIXES } from "./utils/BotNames"; export class BotSpawner { private readonly random: PseudoRandom; diff --git a/src/core/execution/ConstructionExecution.ts b/src/core/execution/ConstructionExecution.ts index 033505ff4..9f08a660c 100644 --- a/src/core/execution/ConstructionExecution.ts +++ b/src/core/execution/ConstructionExecution.ts @@ -7,6 +7,7 @@ import { Unit, UnitType, } from "../game/Game"; +import { TileRef } from "../game/GameMap"; import { CityExecution } from "./CityExecution"; import { DefensePostExecution } from "./DefensePostExecution"; import { FactoryExecution } from "./FactoryExecution"; @@ -15,7 +16,6 @@ import { MissileSiloExecution } from "./MissileSiloExecution"; import { NukeExecution } from "./NukeExecution"; import { PortExecution } from "./PortExecution"; import { SAMLauncherExecution } from "./SAMLauncherExecution"; -import { TileRef } from "../game/GameMap"; import { WarshipExecution } from "./WarshipExecution"; export class ConstructionExecution implements Execution { @@ -97,7 +97,8 @@ export class ConstructionExecution implements Execution { this.active = false; return; } - if (this.ticksUntilComplete === undefined) throw new Error("Not initialized"); + if (this.ticksUntilComplete === undefined) + throw new Error("Not initialized"); this.ticksUntilComplete--; } diff --git a/src/core/execution/DefensePostExecution.ts b/src/core/execution/DefensePostExecution.ts index 62243c3fc..0cb2a9969 100644 --- a/src/core/execution/DefensePostExecution.ts +++ b/src/core/execution/DefensePostExecution.ts @@ -1,6 +1,6 @@ import { Execution, Game, Player, Unit, UnitType } from "../game/Game"; -import { ShellExecution } from "./ShellExecution"; import { TileRef } from "../game/GameMap"; +import { ShellExecution } from "./ShellExecution"; export class DefensePostExecution implements Execution { private mg: Game | undefined; diff --git a/src/core/execution/ExecutionManager.ts b/src/core/execution/ExecutionManager.ts index 122448eda..11c76fafa 100644 --- a/src/core/execution/ExecutionManager.ts +++ b/src/core/execution/ExecutionManager.ts @@ -1,12 +1,14 @@ -import { ClientID, GameID, Intent, Turn } from "../Schemas"; import { Execution, Game } from "../game/Game"; +import { PseudoRandom } from "../PseudoRandom"; +import { ClientID, GameID, Intent, Turn } from "../Schemas"; +import { simpleHash } from "../Util"; +import { AttackExecution } from "./AttackExecution"; import { AllianceExtensionExecution } from "./alliance/AllianceExtensionExecution"; import { AllianceRequestExecution } from "./alliance/AllianceRequestExecution"; import { AllianceRequestReplyExecution } from "./alliance/AllianceRequestReplyExecution"; -import { AttackExecution } from "./AttackExecution"; +import { BreakAllianceExecution } from "./alliance/BreakAllianceExecution"; import { BoatRetreatExecution } from "./BoatRetreatExecution"; import { BotSpawner } from "./BotSpawner"; -import { BreakAllianceExecution } from "./alliance/BreakAllianceExecution"; import { ConstructionExecution } from "./ConstructionExecution"; import { DeleteUnitExecution } from "./DeleteUnitExecution"; import { DonateGoldExecution } from "./DonateGoldExecution"; @@ -17,14 +19,12 @@ import { FakeHumanExecution } from "./FakeHumanExecution"; import { MarkDisconnectedExecution } from "./MarkDisconnectedExecution"; import { MoveWarshipExecution } from "./MoveWarshipExecution"; import { NoOpExecution } from "./NoOpExecution"; -import { PseudoRandom } from "../PseudoRandom"; import { QuickChatExecution } from "./QuickChatExecution"; import { RetreatExecution } from "./RetreatExecution"; import { SpawnExecution } from "./SpawnExecution"; import { TargetPlayerExecution } from "./TargetPlayerExecution"; import { TransportShipExecution } from "./TransportShipExecution"; import { UpgradeStructureExecution } from "./UpgradeStructureExecution"; -import { simpleHash } from "../Util"; export class Executor { // private random = new PseudoRandom(999) diff --git a/src/core/execution/FakeHumanExecution.ts b/src/core/execution/FakeHumanExecution.ts index dac000a3d..c266cf129 100644 --- a/src/core/execution/FakeHumanExecution.ts +++ b/src/core/execution/FakeHumanExecution.ts @@ -14,17 +14,17 @@ import { Unit, UnitType, } from "../game/Game"; -import { TileRef, euclDistFN, manhattanDistFN } from "../game/GameMap"; +import { euclDistFN, manhattanDistFN, TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; +import { GameID } from "../Schemas"; import { calculateBoundingBox, flattenedEmojiTable, simpleHash } from "../Util"; -import { BotBehavior } from "./utils/BotBehavior"; import { ConstructionExecution } from "./ConstructionExecution"; import { EmojiExecution } from "./EmojiExecution"; -import { GameID } from "../Schemas"; import { NukeExecution } from "./NukeExecution"; -import { PseudoRandom } from "../PseudoRandom"; import { SpawnExecution } from "./SpawnExecution"; import { TransportShipExecution } from "./TransportShipExecution"; import { closestTwoTiles } from "./Util"; +import { BotBehavior } from "./utils/BotBehavior"; export class FakeHumanExecution implements Execution { private active = true; @@ -174,8 +174,7 @@ export class FakeHumanExecution implements Execution { const enemyborder = Array.from(this.player.borderTiles()) .flatMap((t) => game.neighbors(t)) .filter( - (t) => - game.isLand(t) && game.ownerID(t) !== this.player?.smallID(), + (t) => game.isLand(t) && game.ownerID(t) !== this.player?.smallID(), ); if (enemyborder.length === 0) { @@ -306,7 +305,9 @@ export class FakeHumanExecution implements Execution { UnitType.SAMLauncher, ); const structureTiles = structures.map((u) => u.tile()); - const randomTiles: (TileRef | null)[] = new Array(10).fill(null); + const randomTiles: (TileRef | null)[] = new Array(10).fill( + null, + ); for (let i = 0; i < randomTiles.length; i++) { randomTiles[i] = this.randTerritoryTile(other); } @@ -413,7 +414,9 @@ export class FakeHumanExecution implements Execution { if (this.player.isOnSameTeam(other)) return; const closest = closestTwoTiles( this.mg, - Array.from(this.player.borderTiles()).filter((t) => this.mg?.isOceanShore(t)), + Array.from(this.player.borderTiles()).filter((t) => + this.mg?.isOceanShore(t), + ), Array.from(other.borderTiles()).filter((t) => this.mg?.isOceanShore(t)), ); if (closest === null) { @@ -467,8 +470,8 @@ export class FakeHumanExecution implements Execution { const tiles = type === UnitType.Port ? Array.from(this.player.borderTiles()).filter((t) => - this.mg?.isOceanShore(t), - ) + this.mg?.isOceanShore(t), + ) : Array.from(this.player.tiles()); if (tiles.length === 0) return null; const valueFunction = this.structureSpawnTileValue(type); @@ -486,7 +489,7 @@ export class FakeHumanExecution implements Execution { return bestTile; } - private * arraySampler(a: T[], sampleSize = 50): Generator { + private *arraySampler(a: T[], sampleSize = 50): Generator { if (a.length <= sampleSize) { // Return all elements yield* a; @@ -508,7 +511,9 @@ export class FakeHumanExecution implements Execution { const { mg } = this; const otherUnits = this.player.units(type); // Prefer spacing structures out of atom bomb range - const borderSpacing = this.mg.config().nukeMagnitudes(UnitType.AtomBomb).outer; + const borderSpacing = this.mg + .config() + .nukeMagnitudes(UnitType.AtomBomb).outer; const structureSpacing = borderSpacing * 2; switch (type) { case UnitType.Port: @@ -516,7 +521,9 @@ export class FakeHumanExecution implements Execution { let w = 0; // Prefer to be far away from other structures of the same type - const otherTiles: Set = new Set(otherUnits.map((u) => u.tile())); + const otherTiles: Set = new Set( + otherUnits.map((u) => u.tile()), + ); otherTiles.delete(tile); const closestOther = closestTwoTiles(mg, otherTiles, [tile]); if (closestOther !== null) { @@ -543,7 +550,9 @@ export class FakeHumanExecution implements Execution { } // Prefer to be away from other structures of the same type - const otherTiles: Set = new Set(otherUnits.map((u) => u.tile())); + const otherTiles: Set = new Set( + otherUnits.map((u) => u.tile()), + ); otherTiles.delete(tile); const closestOther = closestTwoTiles(mg, otherTiles, [tile]); if (closestOther !== null) { diff --git a/src/core/execution/MIRVExecution.ts b/src/core/execution/MIRVExecution.ts index 6360ba826..5067d66d3 100644 --- a/src/core/execution/MIRVExecution.ts +++ b/src/core/execution/MIRVExecution.ts @@ -7,11 +7,11 @@ import { Unit, UnitType, } from "../game/Game"; -import { NukeExecution } from "./NukeExecution"; -import { ParabolaPathFinder } from "../pathfinding/PathFinding"; -import { PseudoRandom } from "../PseudoRandom"; import { TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; +import { ParabolaPathFinder } from "../pathfinding/PathFinding"; import { simpleHash } from "../Util"; +import { NukeExecution } from "./NukeExecution"; export class MirvExecution implements Execution { private active = true; diff --git a/src/core/execution/NukeExecution.ts b/src/core/execution/NukeExecution.ts index 575cbaf86..6020e7812 100644 --- a/src/core/execution/NukeExecution.ts +++ b/src/core/execution/NukeExecution.ts @@ -1,18 +1,18 @@ import { Execution, Game, + isStructureType, MessageType, Player, TerraNullius, TrajectoryTile, Unit, UnitType, - isStructureType, } from "../game/Game"; -import { NukeType } from "../StatsSchemas"; -import { ParabolaPathFinder } from "../pathfinding/PathFinding"; -import { PseudoRandom } from "../PseudoRandom"; import { TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; +import { ParabolaPathFinder } from "../pathfinding/PathFinding"; +import { NukeType } from "../StatsSchemas"; const SPRITE_RADIUS = 16; diff --git a/src/core/execution/PlayerExecution.ts b/src/core/execution/PlayerExecution.ts index 457a79222..f8945adea 100644 --- a/src/core/execution/PlayerExecution.ts +++ b/src/core/execution/PlayerExecution.ts @@ -1,8 +1,8 @@ +import { Config } from "../configuration/Config"; import { Execution, Game, Player, UnitType } from "../game/Game"; +import { GameImpl } from "../game/GameImpl"; import { GameMap, TileRef } from "../game/GameMap"; import { calculateBoundingBox, getMode, inscribed, simpleHash } from "../Util"; -import { Config } from "../configuration/Config"; -import { GameImpl } from "../game/GameImpl"; export class PlayerExecution implements Execution { private readonly ticksPerClusterCalc = 20; diff --git a/src/core/execution/PortExecution.ts b/src/core/execution/PortExecution.ts index fc8971b2d..9395564f4 100644 --- a/src/core/execution/PortExecution.ts +++ b/src/core/execution/PortExecution.ts @@ -1,6 +1,6 @@ import { Execution, Game, Player, Unit, UnitType } from "../game/Game"; -import { PseudoRandom } from "../PseudoRandom"; import { TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; import { TradeShipExecution } from "./TradeShipExecution"; import { TrainStationExecution } from "./TrainStationExecution"; diff --git a/src/core/execution/RailroadExecution.ts b/src/core/execution/RailroadExecution.ts index 33ddaa804..c3e2ca0b4 100644 --- a/src/core/execution/RailroadExecution.ts +++ b/src/core/execution/RailroadExecution.ts @@ -1,7 +1,7 @@ import { Execution, Game } from "../game/Game"; +import { TileRef } from "../game/GameMap"; import { GameUpdateType, RailTile, RailType } from "../game/GameUpdates"; import { Railroad } from "../game/Railroad"; -import { TileRef } from "../game/GameMap"; export class RailroadExecution implements Execution { private mg: Game | undefined; @@ -43,9 +43,9 @@ export class RailroadExecution implements Execution { railType: tiles.length > 0 ? this.computeExtremityDirection( - tiles[tiles.length - 1], - tiles[tiles.length - 2], - ) + tiles[tiles.length - 1], + tiles[tiles.length - 2], + ) : RailType.VERTICAL, }); } diff --git a/src/core/execution/SAMLauncherExecution.ts b/src/core/execution/SAMLauncherExecution.ts index 744021ce3..1b193b621 100644 --- a/src/core/execution/SAMLauncherExecution.ts +++ b/src/core/execution/SAMLauncherExecution.ts @@ -1,15 +1,15 @@ import { Execution, Game, + isUnit, MessageType, Player, Unit, UnitType, - isUnit, } from "../game/Game"; +import { TileRef } from "../game/GameMap"; import { PseudoRandom } from "../PseudoRandom"; import { SAMMissileExecution } from "./SAMMissileExecution"; -import { TileRef } from "../game/GameMap"; type Target = { unit: Unit; diff --git a/src/core/execution/SAMMissileExecution.ts b/src/core/execution/SAMMissileExecution.ts index 0b598f072..8ca029f79 100644 --- a/src/core/execution/SAMMissileExecution.ts +++ b/src/core/execution/SAMMissileExecution.ts @@ -6,10 +6,10 @@ import { Unit, UnitType, } from "../game/Game"; +import { TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; import { AirPathFinder } from "../pathfinding/PathFinding"; import { NukeType } from "../StatsSchemas"; -import { PseudoRandom } from "../PseudoRandom"; -import { TileRef } from "../game/GameMap"; export class SAMMissileExecution implements Execution { private active = true; diff --git a/src/core/execution/ShellExecution.ts b/src/core/execution/ShellExecution.ts index 3573a0690..3abc1e63e 100644 --- a/src/core/execution/ShellExecution.ts +++ b/src/core/execution/ShellExecution.ts @@ -1,7 +1,7 @@ import { Execution, Game, Player, Unit, UnitType } from "../game/Game"; -import { AirPathFinder } from "../pathfinding/PathFinding"; -import { PseudoRandom } from "../PseudoRandom"; import { TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; +import { AirPathFinder } from "../pathfinding/PathFinding"; export class ShellExecution implements Execution { private active = true; diff --git a/src/core/execution/SpawnExecution.ts b/src/core/execution/SpawnExecution.ts index 3ed33dd38..3eac33ca1 100644 --- a/src/core/execution/SpawnExecution.ts +++ b/src/core/execution/SpawnExecution.ts @@ -1,7 +1,7 @@ import { Execution, Game, Player, PlayerInfo, PlayerType } from "../game/Game"; +import { TileRef } from "../game/GameMap"; import { BotExecution } from "./BotExecution"; import { PlayerExecution } from "./PlayerExecution"; -import { TileRef } from "../game/GameMap"; import { getSpawnTiles } from "./Util"; export class SpawnExecution implements Execution { diff --git a/src/core/execution/TradeShipExecution.ts b/src/core/execution/TradeShipExecution.ts index 04e9fbbc7..3815b35c3 100644 --- a/src/core/execution/TradeShipExecution.ts +++ b/src/core/execution/TradeShipExecution.ts @@ -1,3 +1,4 @@ +import { renderNumber } from "../../client/Utils"; import { Execution, Game, @@ -6,11 +7,10 @@ import { Unit, UnitType, } from "../game/Game"; +import { TileRef } from "../game/GameMap"; import { PathFindResultType } from "../pathfinding/AStar"; import { PathFinder } from "../pathfinding/PathFinding"; -import { TileRef } from "../game/GameMap"; import { distSortUnit } from "../Util"; -import { renderNumber } from "../../client/Utils"; export class TradeShipExecution implements Execution { private active = true; diff --git a/src/core/execution/TrainExecution.ts b/src/core/execution/TrainExecution.ts index 2fafd2af3..707c6a3bb 100644 --- a/src/core/execution/TrainExecution.ts +++ b/src/core/execution/TrainExecution.ts @@ -6,9 +6,9 @@ import { Unit, UnitType, } from "../game/Game"; -import { OrientedRailroad, getOrientedRailroad } from "../game/Railroad"; -import { RailNetwork } from "../game/RailNetwork"; import { TileRef } from "../game/GameMap"; +import { RailNetwork } from "../game/RailNetwork"; +import { getOrientedRailroad, OrientedRailroad } from "../game/Railroad"; import { TrainStation } from "../game/TrainStation"; export class TrainExecution implements Execution { diff --git a/src/core/execution/TrainStationExecution.ts b/src/core/execution/TrainStationExecution.ts index 5053dffd7..25eeb91d4 100644 --- a/src/core/execution/TrainStationExecution.ts +++ b/src/core/execution/TrainStationExecution.ts @@ -1,7 +1,7 @@ import { Execution, Game, Unit } from "../game/Game"; +import { TrainStation } from "../game/TrainStation"; import { PseudoRandom } from "../PseudoRandom"; import { TrainExecution } from "./TrainExecution"; -import { TrainStation } from "../game/TrainStation"; export class TrainStationExecution implements Execution { private mg: Game | undefined; diff --git a/src/core/execution/TransportShipExecution.ts b/src/core/execution/TransportShipExecution.ts index 4862d53af..5ed3938ae 100644 --- a/src/core/execution/TransportShipExecution.ts +++ b/src/core/execution/TransportShipExecution.ts @@ -8,11 +8,11 @@ import { Unit, UnitType, } from "../game/Game"; -import { AttackExecution } from "./AttackExecution"; -import { PathFindResultType } from "../pathfinding/AStar"; -import { PathFinder } from "../pathfinding/PathFinding"; import { TileRef } from "../game/GameMap"; import { targetTransportTile } from "../game/TransportShipUtils"; +import { PathFindResultType } from "../pathfinding/AStar"; +import { PathFinder } from "../pathfinding/PathFinding"; +import { AttackExecution } from "./AttackExecution"; export class TransportShipExecution implements Execution { private lastMove: number | undefined; diff --git a/src/core/execution/Util.ts b/src/core/execution/Util.ts index 302ea0000..f1b6e87eb 100644 --- a/src/core/execution/Util.ts +++ b/src/core/execution/Util.ts @@ -1,4 +1,4 @@ -import { GameMap, TileRef, euclDistFN } from "../game/GameMap"; +import { euclDistFN, GameMap, TileRef } from "../game/GameMap"; export function getSpawnTiles(gm: GameMap, tile: TileRef): TileRef[] { return Array.from(gm.bfs(tile, euclDistFN(tile, 4, true))).filter( diff --git a/src/core/execution/WarshipExecution.ts b/src/core/execution/WarshipExecution.ts index 2ba6dacfc..6ba5ba056 100644 --- a/src/core/execution/WarshipExecution.ts +++ b/src/core/execution/WarshipExecution.ts @@ -1,17 +1,17 @@ import { Execution, Game, + isUnit, OwnerComp, Unit, UnitParams, UnitType, - isUnit, } from "../game/Game"; +import { TileRef } from "../game/GameMap"; +import { PseudoRandom } from "../PseudoRandom"; import { PathFindResultType } from "../pathfinding/AStar"; import { PathFinder } from "../pathfinding/PathFinding"; -import { PseudoRandom } from "../PseudoRandom"; import { ShellExecution } from "./ShellExecution"; -import { TileRef } from "../game/GameMap"; export class WarshipExecution implements Execution { private random: PseudoRandom | undefined; @@ -108,10 +108,8 @@ export class WarshipExecution implements Execution { const patrolTile = this.warship.patrolTile(); if ( patrolTile !== undefined && - this.mg.euclideanDistSquared( - patrolTile, - unit.tile(), - ) > patrolRangeSquared + this.mg.euclideanDistSquared(patrolTile, unit.tile()) > + patrolRangeSquared ) { // Prevent warship from chasing trade ship that is too far away from // the patrol tile to prevent warships from wandering around the map. @@ -224,10 +222,7 @@ export class WarshipExecution implements Execution { return; } } - const result = this.pathfinder.nextTile( - this.warship.tile(), - targetTile, - ); + const result = this.pathfinder.nextTile(this.warship.tile(), targetTile); switch (result.type) { case PathFindResultType.Completed: this.warship.setTargetTile(undefined); diff --git a/src/core/execution/WinCheckExecution.ts b/src/core/execution/WinCheckExecution.ts index 996cc4527..8c2159a71 100644 --- a/src/core/execution/WinCheckExecution.ts +++ b/src/core/execution/WinCheckExecution.ts @@ -1,3 +1,4 @@ +import { GameEvent } from "../EventBus"; import { ColoredTeams, Execution, @@ -6,7 +7,6 @@ import { Player, Team, } from "../game/Game"; -import { GameEvent } from "../EventBus"; export class WinEvent implements GameEvent { constructor(public readonly winner: Player) {} diff --git a/src/core/execution/utils/BotBehavior.ts b/src/core/execution/utils/BotBehavior.ts index 76497968c..2c7f6057c 100644 --- a/src/core/execution/utils/BotBehavior.ts +++ b/src/core/execution/utils/BotBehavior.ts @@ -7,11 +7,11 @@ import { TerraNullius, Tick, } from "../../game/Game"; -import { AllianceExtensionExecution } from "../alliance/AllianceExtensionExecution"; -import { AttackExecution } from "../AttackExecution"; -import { EmojiExecution } from "../EmojiExecution"; import { PseudoRandom } from "../../PseudoRandom"; import { flattenedEmojiTable } from "../../Util"; +import { AttackExecution } from "../AttackExecution"; +import { AllianceExtensionExecution } from "../alliance/AllianceExtensionExecution"; +import { EmojiExecution } from "../EmojiExecution"; export class BotBehavior { private enemy: Player | null = null; diff --git a/src/core/game/AllianceRequestImpl.ts b/src/core/game/AllianceRequestImpl.ts index 6fbb7bd0c..e26c8df9b 100644 --- a/src/core/game/AllianceRequestImpl.ts +++ b/src/core/game/AllianceRequestImpl.ts @@ -1,6 +1,6 @@ import { AllianceRequest, Player, Tick } from "./Game"; -import { AllianceRequestUpdate, GameUpdateType } from "./GameUpdates"; import { GameImpl } from "./GameImpl"; +import { AllianceRequestUpdate, GameUpdateType } from "./GameUpdates"; export class AllianceRequestImpl implements AllianceRequest { constructor( diff --git a/src/core/game/AttackImpl.ts b/src/core/game/AttackImpl.ts index 6ab6dd56d..7bb4cc1e9 100644 --- a/src/core/game/AttackImpl.ts +++ b/src/core/game/AttackImpl.ts @@ -1,7 +1,7 @@ import { Attack, Cell, Player, TerraNullius } from "./Game"; import { GameImpl } from "./GameImpl"; -import { PlayerImpl } from "./PlayerImpl"; import { TileRef } from "./GameMap"; +import { PlayerImpl } from "./PlayerImpl"; export class AttackImpl implements Attack { private _isActive = true; diff --git a/src/core/game/BinaryLoaderGameMapLoader.ts b/src/core/game/BinaryLoaderGameMapLoader.ts index 233adbd98..808986032 100644 --- a/src/core/game/BinaryLoaderGameMapLoader.ts +++ b/src/core/game/BinaryLoaderGameMapLoader.ts @@ -1,5 +1,5 @@ -import { GameMapLoader, MapData } from "./GameMapLoader"; import { GameMapType } from "./Game"; +import { GameMapLoader, MapData } from "./GameMapLoader"; import { MapManifest } from "./TerrainMapLoader"; export type BinModule = { diff --git a/src/core/game/FetchGameMapLoader.ts b/src/core/game/FetchGameMapLoader.ts index 5bdeed62d..096f97447 100644 --- a/src/core/game/FetchGameMapLoader.ts +++ b/src/core/game/FetchGameMapLoader.ts @@ -1,5 +1,5 @@ -import { GameMapLoader, MapData } from "./GameMapLoader"; import { GameMapType } from "./Game"; +import { GameMapLoader, MapData } from "./GameMapLoader"; import { MapManifestSchema } from "./TerrainMapLoader"; export class FetchGameMapLoader implements GameMapLoader { diff --git a/src/core/game/Game.ts b/src/core/game/Game.ts index 713b46b2c..3f90c909c 100644 --- a/src/core/game/Game.ts +++ b/src/core/game/Game.ts @@ -1,3 +1,4 @@ +import { Config } from "../configuration/Config"; import { AllPlayersStats, ClientID } from "../Schemas"; import { GameMap, TileRef } from "./GameMap"; import { @@ -6,7 +7,6 @@ import { PlayerUpdate, UnitUpdate, } from "./GameUpdates"; -import { Config } from "../configuration/Config"; import { RailNetwork } from "./RailNetwork"; import { Stats } from "./Stats"; import { UnitPredicate } from "./UnitGrid"; diff --git a/src/core/game/GameImpl.ts b/src/core/game/GameImpl.ts index 91e6ff98d..e0c4aa776 100644 --- a/src/core/game/GameImpl.ts +++ b/src/core/game/GameImpl.ts @@ -1,5 +1,11 @@ /* eslint-disable max-lines */ + +import { renderNumber } from "../../client/Utils"; +import { Config } from "../configuration/Config"; import { AllPlayersStats, ClientID, Winner } from "../Schemas"; +import { simpleHash } from "../Util"; +import { AllianceImpl } from "./AllianceImpl"; +import { AllianceRequestImpl } from "./AllianceRequestImpl"; import { Alliance, AllianceRequest, @@ -20,8 +26,8 @@ import { PlayerType, Quads, Team, - TerraNullius, TerrainType, + TerraNullius, Trios, Unit, UnitInfo, @@ -29,19 +35,14 @@ import { } from "./Game"; import { GameMap, TileRef, TileUpdate } from "./GameMap"; import { GameUpdate, GameUpdateType } from "./GameUpdates"; -import { UnitGrid, UnitPredicate } from "./UnitGrid"; -import { AllianceImpl } from "./AllianceImpl"; -import { AllianceRequestImpl } from "./AllianceRequestImpl"; -import { Config } from "../configuration/Config"; import { PlayerImpl } from "./PlayerImpl"; import { RailNetwork } from "./RailNetwork"; +import { createRailNetwork } from "./RailNetworkImpl"; import { Stats } from "./Stats"; import { StatsImpl } from "./StatsImpl"; -import { TerraNulliusImpl } from "./TerraNulliusImpl"; import { assignTeams } from "./TeamAssignment"; -import { createRailNetwork } from "./RailNetworkImpl"; -import { renderNumber } from "../../client/Utils"; -import { simpleHash } from "../Util"; +import { TerraNulliusImpl } from "./TerraNulliusImpl"; +import { UnitGrid, UnitPredicate } from "./UnitGrid"; export function createGame( humans: PlayerInfo[], diff --git a/src/core/game/GameView.ts b/src/core/game/GameView.ts index 01a08f59e..dedec770b 100644 --- a/src/core/game/GameView.ts +++ b/src/core/game/GameView.ts @@ -1,11 +1,9 @@ -import { - AllianceView, - AttackUpdate, - GameUpdateType, - GameUpdateViewData, - PlayerUpdate, - UnitUpdate, -} from "./GameUpdates"; +import { base64url } from "jose"; +import { Config } from "../configuration/Config"; +import { PatternDecoder } from "../PatternDecoder"; +import { ClientID, GameID, Player } from "../Schemas"; +import { createRandomName } from "../Util"; +import { WorkerClient } from "../worker/WorkerClient"; import { Cell, EmojiMessage, @@ -18,24 +16,26 @@ import { PlayerProfile, PlayerType, Team, - TerraNullius, TerrainType, + TerraNullius, Tick, TrainType, UnitInfo, UnitType, } from "./Game"; -import { ClientID, GameID, Player } from "../Schemas"; import { GameMap, TileRef, TileUpdate } from "./GameMap"; -import { UnitGrid, UnitPredicate } from "./UnitGrid"; -import { Config } from "../configuration/Config"; -import { PatternDecoder } from "../PatternDecoder"; -import { TerraNulliusImpl } from "./TerraNulliusImpl"; +import { + AllianceView, + AttackUpdate, + GameUpdateType, + GameUpdateViewData, + PlayerUpdate, + UnitUpdate, +} from "./GameUpdates"; import { TerrainMapData } from "./TerrainMapLoader"; +import { TerraNulliusImpl } from "./TerraNulliusImpl"; +import { UnitGrid, UnitPredicate } from "./UnitGrid"; import { UserSettings } from "./UserSettings"; -import { WorkerClient } from "../worker/WorkerClient"; -import { base64url } from "jose"; -import { createRandomName } from "../Util"; const userSettings: UserSettings = new UserSettings(); diff --git a/src/core/game/PlayerImpl.ts b/src/core/game/PlayerImpl.ts index 0483b2064..a4d08df29 100644 --- a/src/core/game/PlayerImpl.ts +++ b/src/core/game/PlayerImpl.ts @@ -1,8 +1,22 @@ /* eslint-disable max-lines */ + +import { renderNumber, renderTroops } from "../../client/Utils"; +import { PseudoRandom } from "../PseudoRandom"; +import { ClientID } from "../Schemas"; +import { + assertNever, + distSortUnit, + minInt, + simpleHash, + toInt, + within, +} from "../Util"; +import { sanitizeUsername } from "../validations/username"; +import { AttackImpl } from "./AttackImpl"; import { - AllPlayers, Alliance, AllianceRequest, + AllPlayers, Attack, BuildableUnit, Cell, @@ -27,32 +41,19 @@ import { UnitParams, UnitType, } from "./Game"; +import { GameImpl } from "./GameImpl"; +import { andFN, manhattanDistFN, TileRef } from "./GameMap"; import { AllianceView, AttackUpdate, GameUpdateType, PlayerUpdate, } from "./GameUpdates"; -import { TileRef, andFN, manhattanDistFN } from "./GameMap"; -import { - assertNever, - distSortUnit, - minInt, - simpleHash, - toInt, - within, -} from "../Util"; import { bestShoreDeploymentSource, canBuildTransportShip, } from "./TransportShipUtils"; -import { renderNumber, renderTroops } from "../../client/Utils"; -import { AttackImpl } from "./AttackImpl"; -import { ClientID } from "../Schemas"; -import { GameImpl } from "./GameImpl"; -import { PseudoRandom } from "../PseudoRandom"; import { UnitImpl } from "./UnitImpl"; -import { sanitizeUsername } from "../validations/username"; type Target = { tick: Tick; diff --git a/src/core/game/RailNetwork.ts b/src/core/game/RailNetwork.ts index 1606180e7..00c2e6f5e 100644 --- a/src/core/game/RailNetwork.ts +++ b/src/core/game/RailNetwork.ts @@ -1,5 +1,5 @@ -import { TrainStation } from "./TrainStation"; import { Unit } from "./Game"; +import { TrainStation } from "./TrainStation"; export type RailNetwork = { connectStation(station: TrainStation): void; diff --git a/src/core/game/RailNetworkImpl.ts b/src/core/game/RailNetworkImpl.ts index a77d218a0..cb9cd432b 100644 --- a/src/core/game/RailNetworkImpl.ts +++ b/src/core/game/RailNetworkImpl.ts @@ -1,12 +1,12 @@ -import { Cluster, TrainStation, TrainStationMapAdapter } from "./TrainStation"; -import { Game, Unit, UnitType } from "./Game"; -import { MiniAStar } from "../pathfinding/MiniAStar"; +import { RailroadExecution } from "../execution/RailroadExecution"; import { PathFindResultType } from "../pathfinding/AStar"; +import { MiniAStar } from "../pathfinding/MiniAStar"; +import { SerialAStar } from "../pathfinding/SerialAStar"; +import { Game, Unit, UnitType } from "./Game"; +import { TileRef } from "./GameMap"; import { RailNetwork } from "./RailNetwork"; import { Railroad } from "./Railroad"; -import { RailroadExecution } from "../execution/RailroadExecution"; -import { SerialAStar } from "../pathfinding/SerialAStar"; -import { TileRef } from "./GameMap"; +import { Cluster, TrainStation, TrainStationMapAdapter } from "./TrainStation"; /** * The Stations handle their own neighbors so the graph is naturally traversable, diff --git a/src/core/game/Railroad.ts b/src/core/game/Railroad.ts index f415eede3..f862c0147 100644 --- a/src/core/game/Railroad.ts +++ b/src/core/game/Railroad.ts @@ -1,6 +1,6 @@ -import { GameUpdateType, RailTile, RailType } from "./GameUpdates"; import { Game } from "./Game"; import { TileRef } from "./GameMap"; +import { GameUpdateType, RailTile, RailType } from "./GameUpdates"; import { TrainStation } from "./TrainStation"; export class Railroad { diff --git a/src/core/game/Stats.ts b/src/core/game/Stats.ts index fbde0d972..63a8aac79 100644 --- a/src/core/game/Stats.ts +++ b/src/core/game/Stats.ts @@ -1,6 +1,6 @@ +import { AllPlayersStats } from "../Schemas"; import { NukeType, OtherUnitType, PlayerStats } from "../StatsSchemas"; import { Player, TerraNullius } from "./Game"; -import { AllPlayersStats } from "../Schemas"; export type Stats = { getPlayerStats(player: Player): PlayerStats | null; diff --git a/src/core/game/StatsImpl.ts b/src/core/game/StatsImpl.ts index bae57a81a..5b33dd624 100644 --- a/src/core/game/StatsImpl.ts +++ b/src/core/game/StatsImpl.ts @@ -1,3 +1,4 @@ +import { AllPlayersStats } from "../Schemas"; import { ATTACK_INDEX_CANCEL, ATTACK_INDEX_RECV, @@ -26,7 +27,6 @@ import { unitTypeToOtherUnit, } from "../StatsSchemas"; import { Player, TerraNullius } from "./Game"; -import { AllPlayersStats } from "../Schemas"; import { Stats } from "./Stats"; type BigIntLike = bigint | number; diff --git a/src/core/game/TeamAssignment.ts b/src/core/game/TeamAssignment.ts index fcef06c55..f5a12f221 100644 --- a/src/core/game/TeamAssignment.ts +++ b/src/core/game/TeamAssignment.ts @@ -1,6 +1,6 @@ -import { PlayerInfo, PlayerType, Team } from "./Game"; import { PseudoRandom } from "../PseudoRandom"; import { simpleHash } from "../Util"; +import { PlayerInfo, PlayerType, Team } from "./Game"; export function assignTeams( players: PlayerInfo[], diff --git a/src/core/game/TerrainMapLoader.ts b/src/core/game/TerrainMapLoader.ts index dc4bc4156..0fd01b6dc 100644 --- a/src/core/game/TerrainMapLoader.ts +++ b/src/core/game/TerrainMapLoader.ts @@ -1,7 +1,7 @@ +import { z } from "zod"; +import { GameMapType } from "./Game"; import { GameMap, GameMapImpl } from "./GameMap"; import { GameMapLoader } from "./GameMapLoader"; -import { GameMapType } from "./Game"; -import { z } from "zod"; export type TerrainMapData = { manifest: MapManifest; @@ -66,7 +66,8 @@ export async function genTerrainFromBin( ): Promise { if (data.length !== mapData.width * mapData.height) { throw new Error( - `Invalid data: buffer size ${data.length} incorrect for ${mapData.width}x${mapData.height + `Invalid data: buffer size ${data.length} incorrect for ${mapData.width}x${ + mapData.height } terrain plus 4 bytes for dimensions.`, ); } diff --git a/src/core/game/TrainStation.ts b/src/core/game/TrainStation.ts index 7e844439c..f0b28eced 100644 --- a/src/core/game/TrainStation.ts +++ b/src/core/game/TrainStation.ts @@ -1,10 +1,10 @@ -import { Game, Player, Unit, UnitType } from "./Game"; -import { GameUpdateType, RailTile, RailType } from "./GameUpdates"; -import { GraphAdapter } from "../pathfinding/SerialAStar"; -import { PseudoRandom } from "../PseudoRandom"; -import { Railroad } from "./Railroad"; -import { TileRef } from "./GameMap"; import { TrainExecution } from "../execution/TrainExecution"; +import { PseudoRandom } from "../PseudoRandom"; +import { GraphAdapter } from "../pathfinding/SerialAStar"; +import { Game, Player, Unit, UnitType } from "./Game"; +import { TileRef } from "./GameMap"; +import { GameUpdateType, RailTile, RailType } from "./GameUpdates"; +import { Railroad } from "./Railroad"; /** * Handle train stops at various station types diff --git a/src/core/game/TransportShipUtils.ts b/src/core/game/TransportShipUtils.ts index 861cfadc8..df335b714 100644 --- a/src/core/game/TransportShipUtils.ts +++ b/src/core/game/TransportShipUtils.ts @@ -1,7 +1,7 @@ -import { Game, Player, UnitType } from "./Game"; -import { GameMap, TileRef, andFN, manhattanDistFN } from "./GameMap"; -import { MiniAStar } from "../pathfinding/MiniAStar"; import { PathFindResultType } from "../pathfinding/AStar"; +import { MiniAStar } from "../pathfinding/MiniAStar"; +import { Game, Player, UnitType } from "./Game"; +import { andFN, GameMap, manhattanDistFN, TileRef } from "./GameMap"; export function canBuildTransportShip( game: Game, diff --git a/src/core/game/UnitGrid.ts b/src/core/game/UnitGrid.ts index 2f17d9ee9..103a654b0 100644 --- a/src/core/game/UnitGrid.ts +++ b/src/core/game/UnitGrid.ts @@ -1,5 +1,5 @@ -import { GameMap, TileRef } from "./GameMap"; import { PlayerID, Unit, UnitType } from "./Game"; +import { GameMap, TileRef } from "./GameMap"; import { UnitView } from "./GameView"; export type UnitPredicate = (value: { diff --git a/src/core/game/UnitImpl.ts b/src/core/game/UnitImpl.ts index 037f0e23b..7ce475469 100644 --- a/src/core/game/UnitImpl.ts +++ b/src/core/game/UnitImpl.ts @@ -1,3 +1,4 @@ +import { simpleHash, toInt, withinInt } from "../Util"; import { AllUnitParams, MessageType, @@ -9,11 +10,10 @@ import { UnitInfo, UnitType, } from "./Game"; -import { GameUpdateType, UnitUpdate } from "./GameUpdates"; -import { simpleHash, toInt, withinInt } from "../Util"; import { GameImpl } from "./GameImpl"; -import { PlayerImpl } from "./PlayerImpl"; import { TileRef } from "./GameMap"; +import { GameUpdateType, UnitUpdate } from "./GameUpdates"; +import { PlayerImpl } from "./PlayerImpl"; export class UnitImpl implements Unit { private _active = true; diff --git a/src/core/pathfinding/AStar.ts b/src/core/pathfinding/AStar.ts index 63fbf907f..4056c684f 100644 --- a/src/core/pathfinding/AStar.ts +++ b/src/core/pathfinding/AStar.ts @@ -11,19 +11,19 @@ export enum PathFindResultType { } export type AStarResult = | { - type: PathFindResultType.NextTile; - node: NodeType; - } + type: PathFindResultType.NextTile; + node: NodeType; + } | { - type: PathFindResultType.Pending; - } + type: PathFindResultType.Pending; + } | { - type: PathFindResultType.Completed; - node: NodeType; - } + type: PathFindResultType.Completed; + node: NodeType; + } | { - type: PathFindResultType.PathNotFound; - }; + type: PathFindResultType.PathNotFound; + }; export type Point = { x: number; diff --git a/src/core/pathfinding/MiniAStar.ts b/src/core/pathfinding/MiniAStar.ts index c4c227b04..826edc6bc 100644 --- a/src/core/pathfinding/MiniAStar.ts +++ b/src/core/pathfinding/MiniAStar.ts @@ -1,7 +1,7 @@ -import { AStar, PathFindResultType } from "./AStar"; -import { GameMap, TileRef } from "../game/GameMap"; -import { GraphAdapter, SerialAStar } from "./SerialAStar"; import { Cell } from "../game/Game"; +import { GameMap, TileRef } from "../game/GameMap"; +import { AStar, PathFindResultType } from "./AStar"; +import { GraphAdapter, SerialAStar } from "./SerialAStar"; export class GameMapAdapter implements GraphAdapter { constructor( diff --git a/src/core/pathfinding/PathFinding.ts b/src/core/pathfinding/PathFinding.ts index 2711b8b39..51efc3570 100644 --- a/src/core/pathfinding/PathFinding.ts +++ b/src/core/pathfinding/PathFinding.ts @@ -1,9 +1,9 @@ -import { AStar, AStarResult, PathFindResultType } from "./AStar"; -import { GameMap, TileRef } from "../game/GameMap"; -import { DistanceBasedBezierCurve } from "../utilities/Line"; import { Game } from "../game/Game"; -import { MiniAStar } from "./MiniAStar"; +import { GameMap, TileRef } from "../game/GameMap"; import { PseudoRandom } from "../PseudoRandom"; +import { DistanceBasedBezierCurve } from "../utilities/Line"; +import { AStar, AStarResult, PathFindResultType } from "./AStar"; +import { MiniAStar } from "./MiniAStar"; const parabolaMinHeight = 50; diff --git a/src/core/pathfinding/SerialAStar.ts b/src/core/pathfinding/SerialAStar.ts index 13439c818..e69f111ed 100644 --- a/src/core/pathfinding/SerialAStar.ts +++ b/src/core/pathfinding/SerialAStar.ts @@ -1,5 +1,5 @@ -import { AStar, PathFindResultType } from "./AStar"; import FastPriorityQueue from "fastpriorityqueue"; +import { AStar, PathFindResultType } from "./AStar"; /** * Implement this interface with your graph to find paths with A* @@ -128,7 +128,8 @@ export class SerialAStar implements AStar { const openSet = isForward ? this.fwdOpenSet : this.bwdOpenSet; const cameFrom = isForward ? this.fwdCameFrom : this.bwdCameFrom; - const tentativeGScore = (gScore.get(current) ?? 0) + this.graph.cost(neighbor); + const tentativeGScore = + (gScore.get(current) ?? 0) + this.graph.cost(neighbor); let penalty = 0; // With a direction change penalty, the path will get as straight as possible if (this.directionChangePenalty > 0) { diff --git a/src/core/validations/username.ts b/src/core/validations/username.ts index c587267a8..6463b31cd 100644 --- a/src/core/validations/username.ts +++ b/src/core/validations/username.ts @@ -1,14 +1,14 @@ import { - RegExpMatcher, collapseDuplicatesTransformer, englishDataset, englishRecommendedTransformers, + RegExpMatcher, resolveConfusablesTransformer, resolveLeetSpeakTransformer, skipNonAlphabeticTransformer, } from "obscenity"; -import { simpleHash } from "../Util"; import { translateText } from "../../client/Utils"; +import { simpleHash } from "../Util"; const matcher = new RegExpMatcher({ ...englishDataset.build(), diff --git a/src/core/worker/Worker.worker.ts b/src/core/worker/Worker.worker.ts index 28e979c7e..ad1f7ff72 100644 --- a/src/core/worker/Worker.worker.ts +++ b/src/core/worker/Worker.worker.ts @@ -1,3 +1,7 @@ +import version from "../../../resources/version.txt"; +import { createGameRunner, GameRunner } from "../GameRunner"; +import { FetchGameMapLoader } from "../game/FetchGameMapLoader"; +import { ErrorUpdate, GameUpdateViewData } from "../game/GameUpdates"; import { AttackAveragePositionResultMessage, InitializedMessage, @@ -8,10 +12,6 @@ import { TransportShipSpawnResultMessage, WorkerMessage, } from "./WorkerMessages"; -import { ErrorUpdate, GameUpdateViewData } from "../game/GameUpdates"; -import { GameRunner, createGameRunner } from "../GameRunner"; -import { FetchGameMapLoader } from "../game/FetchGameMapLoader"; -import version from "../../../resources/version.txt"; const ctx: Worker = self as unknown as Worker; let gameRunner: Promise | null = null; diff --git a/src/core/worker/WorkerClient.ts b/src/core/worker/WorkerClient.ts index 1017cc7f1..f4cc16ab7 100644 --- a/src/core/worker/WorkerClient.ts +++ b/src/core/worker/WorkerClient.ts @@ -5,16 +5,19 @@ import { PlayerID, PlayerProfile, } from "../game/Game"; -import { ClientID, GameStartInfo, Turn } from "../Schemas"; -import { ErrorUpdate, GameUpdateViewData } from "../game/GameUpdates"; import { TileRef } from "../game/GameMap"; -import { WorkerMessage } from "./WorkerMessages"; +import { ErrorUpdate, GameUpdateViewData } from "../game/GameUpdates"; +import { ClientID, GameStartInfo, Turn } from "../Schemas"; import { generateID } from "../Util"; +import { WorkerMessage } from "./WorkerMessages"; export class WorkerClient { private readonly worker: Worker; private isInitialized = false; - private readonly messageHandlers: Map void>; + private readonly messageHandlers: Map< + string, + (message: WorkerMessage) => void + >; private gameUpdateCallback?: ( update: GameUpdateViewData | ErrorUpdate, ) => void; diff --git a/src/core/worker/WorkerMessages.ts b/src/core/worker/WorkerMessages.ts index 3f24796c0..059fbe3f7 100644 --- a/src/core/worker/WorkerMessages.ts +++ b/src/core/worker/WorkerMessages.ts @@ -1,12 +1,12 @@ -import { ClientID, GameStartInfo, Turn } from "../Schemas"; import { PlayerActions, PlayerBorderTiles, PlayerID, PlayerProfile, } from "../game/Game"; -import { GameUpdateViewData } from "../game/GameUpdates"; import { TileRef } from "../game/GameMap"; +import { GameUpdateViewData } from "../game/GameUpdates"; +import { ClientID, GameStartInfo, Turn } from "../Schemas"; export type WorkerMessageType = | "heartbeat" diff --git a/src/server/Archive.ts b/src/server/Archive.ts index bda347292..d6ebfae85 100644 --- a/src/server/Archive.ts +++ b/src/server/Archive.ts @@ -1,8 +1,8 @@ -import { AnalyticsRecord, GameID, GameRecord } from "../core/Schemas"; import { S3 } from "@aws-sdk/client-s3"; import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; -import { logger } from "./Logger"; +import { AnalyticsRecord, GameID, GameRecord } from "../core/Schemas"; import { replacer } from "../core/Util"; +import { logger } from "./Logger"; const config = getServerConfigFromServer(); diff --git a/src/server/Client.ts b/src/server/Client.ts index af38b3a82..ecac7f885 100644 --- a/src/server/Client.ts +++ b/src/server/Client.ts @@ -1,7 +1,7 @@ -import { ClientID, Winner } from "../core/Schemas"; -import { Tick } from "../core/game/Game"; -import { TokenPayload } from "../core/ApiSchemas"; import WebSocket from "ws"; +import { TokenPayload } from "../core/ApiSchemas"; +import { Tick } from "../core/game/Game"; +import { ClientID, Winner } from "../core/Schemas"; export class Client { public lastPing: number = Date.now(); diff --git a/src/server/Cloudflare.ts b/src/server/Cloudflare.ts index 2de807f05..6ca1f1fd0 100644 --- a/src/server/Cloudflare.ts +++ b/src/server/Cloudflare.ts @@ -1,8 +1,8 @@ -import { promises as fs } from "fs"; -import { logger } from "./Logger"; import { spawn } from "child_process"; +import { promises as fs } from "fs"; import yaml from "js-yaml"; import { z } from "zod"; +import { logger } from "./Logger"; const log = logger.child({ module: "cloudflare", @@ -70,7 +70,7 @@ export class Cloudflare { const response = await fetch(url, { body: data ? JSON.stringify(data) : undefined, headers: { - "Authorization": `Bearer ${this.apiToken}`, + Authorization: `Bearer ${this.apiToken}`, "Content-Type": "application/json", }, method, @@ -185,7 +185,7 @@ export class Cloudflare { const tunnelConfig: CloudflaredConfig = { "credentials-file": this.credsPath, - "ingress": [ + ingress: [ ...Array.from(subdomainToService.entries()).map( ([subdomain, service]) => ({ hostname: `${subdomain}.${domain}`, @@ -196,7 +196,7 @@ export class Cloudflare { service: "http_status:404", }, ], - "tunnel": tunnelId, + tunnel: tunnelId, }; // Write config file diff --git a/src/server/GameManager.ts b/src/server/GameManager.ts index cf9865af1..a71d859ef 100644 --- a/src/server/GameManager.ts +++ b/src/server/GameManager.ts @@ -1,9 +1,9 @@ -import { Difficulty, GameMapType, GameMode, GameType } from "../core/game/Game"; -import { GameConfig, GameID } from "../core/Schemas"; -import { GamePhase, GameServer } from "./GameServer"; -import { Client } from "./Client"; import { Logger } from "winston"; import { ServerConfig } from "../core/configuration/Config"; +import { Difficulty, GameMapType, GameMode, GameType } from "../core/game/Game"; +import { GameConfig, GameID } from "../core/Schemas"; +import { Client } from "./Client"; +import { GamePhase, GameServer } from "./GameServer"; export class GameManager { private games: Map = new Map(); diff --git a/src/server/GameServer.ts b/src/server/GameServer.ts index dd8d0d81b..033a554c8 100644 --- a/src/server/GameServer.ts +++ b/src/server/GameServer.ts @@ -1,3 +1,9 @@ +import ipAnonymize from "ip-anonymize"; +import { Logger } from "winston"; +import WebSocket from "ws"; +import { z } from "zod"; +import { GameEnv, ServerConfig } from "../core/configuration/Config"; +import { GameType } from "../core/game/Game"; import { ClientID, ClientSendWinnerMessage, @@ -14,17 +20,11 @@ import { ServerTurnMessage, Turn, } from "../core/Schemas"; -import { GameEnv, ServerConfig } from "../core/configuration/Config"; -import { Client } from "./Client"; -import { GameType } from "../core/game/Game"; -import { Logger } from "winston"; -import WebSocket from "ws"; -import { archive } from "./Archive"; import { createGameRecord } from "../core/Util"; +import { archive } from "./Archive"; +import { Client } from "./Client"; import { gatekeeper } from "./Gatekeeper"; -import ipAnonymize from "ip-anonymize"; import { postJoinMessageHandler } from "./worker/websocket/handler/message/PostJoinHandler"; -import { z } from "zod"; export enum GamePhase { Lobby = "LOBBY", @@ -44,7 +44,8 @@ export class GameServer { public activeClients: Client[] = []; lobbyCreatorID: string | undefined; private readonly allClients: Map = new Map(); - private readonly clientsDisconnectedStatus: Map = new Map(); + private readonly clientsDisconnectedStatus: Map = + new Map(); private _hasStarted = false; private _startTime: number | null = null; diff --git a/src/server/Gatekeeper.ts b/src/server/Gatekeeper.ts index 047baa94b..dccf45cb9 100644 --- a/src/server/Gatekeeper.ts +++ b/src/server/Gatekeeper.ts @@ -1,9 +1,9 @@ // src/server/Security.ts import { NextFunction, Request, Response } from "express"; -import { fileURLToPath } from "url"; import fs from "fs"; import http from "http"; import path from "path"; +import { fileURLToPath } from "url"; export enum LimiterType { Get = "get", diff --git a/src/server/Logger.ts b/src/server/Logger.ts index 193b54c49..39fa6034c 100644 --- a/src/server/Logger.ts +++ b/src/server/Logger.ts @@ -1,14 +1,15 @@ -import * as dotenv from "dotenv"; import * as logsAPI from "@opentelemetry/api-logs"; +import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http"; import { LoggerProvider, SimpleLogRecordProcessor, } from "@opentelemetry/sdk-logs"; -import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http"; import { OpenTelemetryTransportV3 } from "@opentelemetry/winston-transport"; -import { getOtelResource } from "./OtelResource"; -import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; +import * as dotenv from "dotenv"; import winston from "winston"; +import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; +import { getOtelResource } from "./OtelResource"; + dotenv.config(); const config = getServerConfigFromServer(); diff --git a/src/server/MapPlaylist.ts b/src/server/MapPlaylist.ts index ab2b78492..80baee9e3 100644 --- a/src/server/MapPlaylist.ts +++ b/src/server/MapPlaylist.ts @@ -1,3 +1,4 @@ +import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; import { Difficulty, Duos, @@ -8,9 +9,8 @@ import { Quads, Trios, } from "../core/game/Game"; -import { GameConfig, TeamCountConfig } from "../core/Schemas"; import { PseudoRandom } from "../core/PseudoRandom"; -import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; +import { GameConfig, TeamCountConfig } from "../core/Schemas"; import { logger } from "./Logger"; const log = logger.child({}); @@ -106,7 +106,9 @@ export class MapPlaylist { log.info(`Generated map playlist in ${i + 1} attempts`); const next = this.mapsPlaylist.shift(); if (next !== undefined) return next; - log.error("Playlist unexpectedly empty after successful shuffle; using fallback."); + log.error( + "Playlist unexpectedly empty after successful shuffle; using fallback.", + ); return { map: GameMapType.World, mode: GameMode.FFA }; } } diff --git a/src/server/Master.ts b/src/server/Master.ts index b33ac5241..4d76404b9 100644 --- a/src/server/Master.ts +++ b/src/server/Master.ts @@ -1,18 +1,22 @@ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ -import { ApiEnvResponse, ApiPublicLobbiesResponse } from "../core/ExpressSchemas"; -import { LimiterType, gatekeeper } from "./Gatekeeper"; -import { GameInfo } from "../core/Schemas"; -import { ID } from "../core/BaseSchemas"; -import { MapPlaylist } from "./MapPlaylist"; + import cluster from "cluster"; import express from "express"; -import { fileURLToPath } from "url"; -import { generateID } from "../core/Util"; -import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; -import http from "http"; -import { logger } from "./Logger"; -import path from "path"; import rateLimit from "express-rate-limit"; +import http from "http"; +import path from "path"; +import { fileURLToPath } from "url"; +import { ID } from "../core/BaseSchemas"; +import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; +import { + ApiEnvResponse, + ApiPublicLobbiesResponse, +} from "../core/ExpressSchemas"; +import { GameInfo } from "../core/Schemas"; +import { generateID } from "../core/Util"; +import { gatekeeper, LimiterType } from "./Gatekeeper"; +import { logger } from "./Logger"; +import { MapPlaylist } from "./MapPlaylist"; const config = getServerConfigFromServer(); const playlist = new MapPlaylist(); diff --git a/src/server/OtelResource.ts b/src/server/OtelResource.ts index 8bd49d4d4..7bb93bfa8 100644 --- a/src/server/OtelResource.ts +++ b/src/server/OtelResource.ts @@ -1,9 +1,9 @@ +import { resourceFromAttributes } from "@opentelemetry/resources"; import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION, } from "@opentelemetry/semantic-conventions"; import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; -import { resourceFromAttributes } from "@opentelemetry/resources"; const config = getServerConfigFromServer(); diff --git a/src/server/PrivilegeRefresher.ts b/src/server/PrivilegeRefresher.ts index a8043fd3d..51c270a56 100644 --- a/src/server/PrivilegeRefresher.ts +++ b/src/server/PrivilegeRefresher.ts @@ -1,11 +1,11 @@ +import { base64url } from "jose"; +import { Logger } from "winston"; +import { CosmeticsSchema } from "../core/CosmeticSchemas"; import { FailOpenPrivilegeChecker, PrivilegeChecker, PrivilegeCheckerImpl, } from "./Privilege"; -import { CosmeticsSchema } from "../core/CosmeticSchemas"; -import { Logger } from "winston"; -import { base64url } from "jose"; // Refreshes the privilege checker every 5 minutes. // WARNING: This fails open if cosmetics.json is not available. diff --git a/src/server/Server.ts b/src/server/Server.ts index 5a9da8449..8a00653ea 100644 --- a/src/server/Server.ts +++ b/src/server/Server.ts @@ -1,8 +1,8 @@ -import * as dotenv from "dotenv"; -import { Cloudflare, TunnelConfig } from "./Cloudflare"; -import { GameEnv } from "../core/configuration/Config"; import cluster from "cluster"; +import * as dotenv from "dotenv"; +import { GameEnv } from "../core/configuration/Config"; import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; +import { Cloudflare, TunnelConfig } from "./Cloudflare"; import { startMaster } from "./Master"; import { startWorker } from "./Worker"; diff --git a/src/server/Worker.ts b/src/server/Worker.ts index 202dd184a..858e4f076 100644 --- a/src/server/Worker.ts +++ b/src/server/Worker.ts @@ -1,28 +1,28 @@ +import express, { NextFunction, Request, Response } from "express"; +import rateLimit from "express-rate-limit"; +import http from "http"; +import ipAnonymize from "ip-anonymize"; +import path from "path"; +import { fileURLToPath } from "url"; +import { WebSocket, WebSocketServer } from "ws"; +import { z } from "zod"; +import { ID } from "../core/BaseSchemas"; +import { GameEnv } from "../core/configuration/Config"; +import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; +import { GameType } from "../core/game/Game"; +import { GameRecord, GameRecordSchema } from "../core/Schemas"; import { CreateGameInputSchema, GameInputSchema, WorkerApiGameIdExists, } from "../core/WorkerSchemas"; -import { GameRecord, GameRecordSchema } from "../core/Schemas"; -import { LimiterType, gatekeeper } from "./Gatekeeper"; -import { WebSocket, WebSocketServer } from "ws"; import { archive, readGameRecord } from "./Archive"; -import express, { NextFunction, Request, Response } from "express"; -import { GameEnv } from "../core/configuration/Config"; import { GameManager } from "./GameManager"; -import { GameType } from "../core/game/Game"; -import { ID } from "../core/BaseSchemas"; -import { PrivilegeRefresher } from "./PrivilegeRefresher"; -import { fileURLToPath } from "url"; -import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; -import http from "http"; -import { initWorkerMetrics } from "./WorkerMetrics"; -import ipAnonymize from "ip-anonymize"; +import { gatekeeper, LimiterType } from "./Gatekeeper"; import { logger } from "./Logger"; -import path from "path"; +import { PrivilegeRefresher } from "./PrivilegeRefresher"; +import { initWorkerMetrics } from "./WorkerMetrics"; import { preJoinMessageHandler } from "./worker/websocket/handler/message/PreJoinHandler"; -import rateLimit from "express-rate-limit"; -import { z } from "zod"; const config = getServerConfigFromServer(); @@ -134,17 +134,9 @@ export async function startWorker() { const game = gm.createGame(id, gc, creatorClientID); log.info( - `Worker ${ - workerId - }: IP ${ - ipAnonymize(clientIP) - } creating ${ + `Worker ${workerId}: IP ${ipAnonymize(clientIP)} creating ${ game.isPublic() ? "Public" : "Private" - }${ - gc?.gameMode ? ` ${gc.gameMode}` : "" - } game with id ${ - id - }${ + }${gc?.gameMode ? ` ${gc.gameMode}` : ""} game with id ${id}${ creatorClientID ? `, creator: ${creatorClientID}` : "" }`, ); diff --git a/src/server/WorkerMetrics.ts b/src/server/WorkerMetrics.ts index e233f8ac9..2539546bf 100644 --- a/src/server/WorkerMetrics.ts +++ b/src/server/WorkerMetrics.ts @@ -1,9 +1,12 @@ -import * as dotenv from "dotenv"; -import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"; -import { getOtelResource, getPromLabels } from "./OtelResource"; -import { GameManager } from "./GameManager"; import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http"; +import { + MeterProvider, + PeriodicExportingMetricReader, +} from "@opentelemetry/sdk-metrics"; +import * as dotenv from "dotenv"; import { getServerConfigFromServer } from "../core/configuration/ConfigLoader"; +import { GameManager } from "./GameManager"; +import { getOtelResource, getPromLabels } from "./OtelResource"; dotenv.config(); diff --git a/src/server/jwt.ts b/src/server/jwt.ts index e259accbe..98ebb518f 100644 --- a/src/server/jwt.ts +++ b/src/server/jwt.ts @@ -1,19 +1,19 @@ +import { jwtVerify } from "jose"; +import { z } from "zod"; import { TokenPayload, TokenPayloadSchema, UserMeResponse, UserMeResponseSchema, } from "../core/ApiSchemas"; -import { PersistentIdSchema } from "../core/Schemas"; import { ServerConfig } from "../core/configuration/Config"; -import { jwtVerify } from "jose"; -import { z } from "zod"; +import { PersistentIdSchema } from "../core/Schemas"; type TokenVerificationResult = | { - persistentId: string; - claims: TokenPayload | null; - } + persistentId: string; + claims: TokenPayload | null; + } | false; export async function verifyClientToken( diff --git a/src/server/worker/websocket/handler/message/PostJoinHandler.ts b/src/server/worker/websocket/handler/message/PostJoinHandler.ts index 00b5b783a..cea44173a 100644 --- a/src/server/worker/websocket/handler/message/PostJoinHandler.ts +++ b/src/server/worker/websocket/handler/message/PostJoinHandler.ts @@ -1,3 +1,5 @@ +import { Logger } from "winston"; +import { z } from "zod"; import { ClientMessageSchema, ClientSendWinnerMessage, @@ -5,8 +7,6 @@ import { } from "../../../../../core/Schemas"; import { Client } from "../../../../Client"; import { GameServer } from "../../../../GameServer"; -import { Logger } from "winston"; -import { z } from "zod"; export async function postJoinMessageHandler( gs: GameServer, @@ -118,7 +118,9 @@ export async function postJoinMessageHandler( function handleWinner( gs: GameServer, log: Logger, - client: Client, clientMsg: ClientSendWinnerMessage) { + client: Client, + clientMsg: ClientSendWinnerMessage, +) { if ( gs.outOfSyncClients.has(client.clientID) || gs.kickedClients.has(client.clientID) || diff --git a/src/server/worker/websocket/handler/message/PreJoinHandler.ts b/src/server/worker/websocket/handler/message/PreJoinHandler.ts index c4896942d..7c869b54f 100644 --- a/src/server/worker/websocket/handler/message/PreJoinHandler.ts +++ b/src/server/worker/websocket/handler/message/PreJoinHandler.ts @@ -1,17 +1,17 @@ +import http from "http"; +import ipAnonymize from "ip-anonymize"; +import { WebSocket } from "ws"; +import { z } from "zod"; +import { getServerConfigFromServer } from "../../../../../core/configuration/ConfigLoader"; import { ClientMessageSchema, ServerErrorMessage, } from "../../../../../core/Schemas"; -import { getUserMe, verifyClientToken } from "../../../../jwt"; import { Client } from "../../../../Client"; import { GameManager } from "../../../../GameManager"; -import { PrivilegeRefresher } from "../../../../PrivilegeRefresher"; -import { WebSocket } from "ws"; -import { getServerConfigFromServer } from "../../../../../core/configuration/ConfigLoader"; -import http from "http"; -import ipAnonymize from "ip-anonymize"; +import { getUserMe, verifyClientToken } from "../../../../jwt"; import { logger } from "../../../../Logger"; -import { z } from "zod"; +import { PrivilegeRefresher } from "../../../../PrivilegeRefresher"; const config = getServerConfigFromServer(); @@ -62,13 +62,13 @@ async function handleJoinMessage( ): Promise< | undefined | { - success: true; - } + success: true; + } | { - success: false; - code: 1002; - error: string; - reason: + success: false; + code: 1002; + error: string; + reason: | "ClientJoinMessageSchema" | "Flag invalid" | "Flag restricted" @@ -78,19 +78,19 @@ async function handleJoinMessage( | "Pattern restricted" | "Pattern unlisted" | "Unauthorized"; - } + } | { - success: false; - code: 1011; - reason: "Internal server error"; - error: string; - } + success: false; + code: 1011; + reason: "Internal server error"; + error: string; + } > { const forwarded = req.headers["x-forwarded-for"]; const ip = Array.isArray(forwarded) ? forwarded[0] : // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - forwarded || req.socket.remoteAddress || "unknown"; + forwarded || req.socket.remoteAddress || "unknown"; try { // Parse and handle client messages @@ -121,8 +121,8 @@ async function handleJoinMessage( const expectedWorkerId = config.workerIndex(clientMsg.gameID); if (expectedWorkerId !== workerId) { log.warn( - `Worker mismatch: Game ${clientMsg.gameID - } should be on worker ${expectedWorkerId + `Worker mismatch: Game ${clientMsg.gameID} should be on worker ${ + expectedWorkerId }, but this is worker ${workerId}`, ); return; diff --git a/tests/AllianceExtensionExecution.test.ts b/tests/AllianceExtensionExecution.test.ts index 7b60df7ef..6ae6340ed 100644 --- a/tests/AllianceExtensionExecution.test.ts +++ b/tests/AllianceExtensionExecution.test.ts @@ -1,8 +1,8 @@ -import { Game, Player, PlayerType } from "../src/core/game/Game"; -import { playerInfo, setup } from "./util/Setup"; import { AllianceExtensionExecution } from "../src/core/execution/alliance/AllianceExtensionExecution"; import { AllianceRequestExecution } from "../src/core/execution/alliance/AllianceRequestExecution"; import { AllianceRequestReplyExecution } from "../src/core/execution/alliance/AllianceRequestReplyExecution"; +import { Game, Player, PlayerType } from "../src/core/game/Game"; +import { playerInfo, setup } from "./util/Setup"; let game: Game; let player1: Player; diff --git a/tests/Attack.test.ts b/tests/Attack.test.ts index 727fc955a..d5ff1e6a0 100644 --- a/tests/Attack.test.ts +++ b/tests/Attack.test.ts @@ -1,3 +1,6 @@ +import { AttackExecution } from "../src/core/execution/AttackExecution"; +import { SpawnExecution } from "../src/core/execution/SpawnExecution"; +import { TransportShipExecution } from "../src/core/execution/TransportShipExecution"; import { Game, Player, @@ -5,13 +8,10 @@ import { PlayerType, UnitType, } from "../src/core/game/Game"; -import { AttackExecution } from "../src/core/execution/AttackExecution"; -import { SpawnExecution } from "../src/core/execution/SpawnExecution"; -import { TestConfig } from "./util/TestConfig"; import { TileRef } from "../src/core/game/GameMap"; -import { TransportShipExecution } from "../src/core/execution/TransportShipExecution"; -import { constructionExecution } from "./util/utils"; import { setup } from "./util/Setup"; +import { TestConfig } from "./util/TestConfig"; +import { constructionExecution } from "./util/utils"; let game: Game; let attacker: Player; diff --git a/tests/AttackStats.test.ts b/tests/AttackStats.test.ts index 785851e9a..1955aec11 100644 --- a/tests/AttackStats.test.ts +++ b/tests/AttackStats.test.ts @@ -1,7 +1,7 @@ -import { GOLD_INDEX_WAR, GOLD_INDEX_WORK } from "../src/core/StatsSchemas"; -import { Game, Player, PlayerInfo, PlayerType } from "../src/core/game/Game"; import { AttackExecution } from "../src/core/execution/AttackExecution"; import { SpawnExecution } from "../src/core/execution/SpawnExecution"; +import { Game, Player, PlayerInfo, PlayerType } from "../src/core/game/Game"; +import { GOLD_INDEX_WAR, GOLD_INDEX_WORK } from "../src/core/StatsSchemas"; import { setup } from "./util/Setup"; let game: Game; diff --git a/tests/BotBehavior.test.ts b/tests/BotBehavior.test.ts index eb1ea8dd1..71b14ac0b 100644 --- a/tests/BotBehavior.test.ts +++ b/tests/BotBehavior.test.ts @@ -1,3 +1,5 @@ +import { AllianceExtensionExecution } from "../src/core/execution/alliance/AllianceExtensionExecution"; +import { BotBehavior } from "../src/core/execution/utils/BotBehavior"; import { AllianceRequest, Game, @@ -7,8 +9,6 @@ import { Relation, Tick, } from "../src/core/game/Game"; -import { AllianceExtensionExecution } from "../src/core/execution/alliance/AllianceExtensionExecution"; -import { BotBehavior } from "../src/core/execution/utils/BotBehavior"; import { PseudoRandom } from "../src/core/PseudoRandom"; import { setup } from "./util/Setup"; diff --git a/tests/Censor.test.ts b/tests/Censor.test.ts index fc23b7172..1e7067fc3 100644 --- a/tests/Censor.test.ts +++ b/tests/Censor.test.ts @@ -32,10 +32,10 @@ jest.mock("../src/client/Utils", () => ({ })); import { - MAX_USERNAME_LENGTH, - MIN_USERNAME_LENGTH, fixProfaneUsername, isProfaneUsername, + MAX_USERNAME_LENGTH, + MIN_USERNAME_LENGTH, sanitizeUsername, validateUsername, } from "../src/core/validations/username"; diff --git a/tests/Colors.test.ts b/tests/Colors.test.ts index 515d19337..c702d19c0 100644 --- a/tests/Colors.test.ts +++ b/tests/Colors.test.ts @@ -1,8 +1,8 @@ +import { Colord, colord } from "colord"; import { ColorAllocator, selectDistinctColorIndex, } from "../src/core/configuration/ColorAllocator"; -import { Colord, colord } from "colord"; import { blue, botColor, diff --git a/tests/DeleteUnitExecution.test.ts b/tests/DeleteUnitExecution.test.ts index f529e6112..c8486a1fe 100644 --- a/tests/DeleteUnitExecution.test.ts +++ b/tests/DeleteUnitExecution.test.ts @@ -1,3 +1,5 @@ +import { DeleteUnitExecution } from "../src/core/execution/DeleteUnitExecution"; +import { SpawnExecution } from "../src/core/execution/SpawnExecution"; import { Game, Player, @@ -6,8 +8,6 @@ import { Unit, UnitType, } from "../src/core/game/Game"; -import { DeleteUnitExecution } from "../src/core/execution/DeleteUnitExecution"; -import { SpawnExecution } from "../src/core/execution/SpawnExecution"; import { TileRef } from "../src/core/game/GameMap"; import { setup } from "./util/Setup"; diff --git a/tests/Disconnected.test.ts b/tests/Disconnected.test.ts index e2a601240..e03138efa 100644 --- a/tests/Disconnected.test.ts +++ b/tests/Disconnected.test.ts @@ -1,8 +1,8 @@ -import { Game, Player, PlayerInfo, PlayerType } from "../src/core/game/Game"; import { MarkDisconnectedExecution } from "../src/core/execution/MarkDisconnectedExecution"; import { SpawnExecution } from "../src/core/execution/SpawnExecution"; -import { executeTicks } from "./util/utils"; +import { Game, Player, PlayerInfo, PlayerType } from "../src/core/game/Game"; import { setup } from "./util/Setup"; +import { executeTicks } from "./util/utils"; let game: Game; let player1: Player; diff --git a/tests/Donate.test.ts b/tests/Donate.test.ts index 2523e7c82..bbbccd4f9 100644 --- a/tests/Donate.test.ts +++ b/tests/Donate.test.ts @@ -1,7 +1,7 @@ -import { PlayerInfo, PlayerType } from "../src/core/game/Game"; import { DonateGoldExecution } from "../src/core/execution/DonateGoldExecution"; import { DonateTroopsExecution } from "../src/core/execution/DonateTroopExecution"; import { SpawnExecution } from "../src/core/execution/SpawnExecution"; +import { PlayerInfo, PlayerType } from "../src/core/game/Game"; import { setup } from "./util/Setup"; describe("Donate troops to an ally", () => { diff --git a/tests/MissileSilo.test.ts b/tests/MissileSilo.test.ts index 7731b2549..1459a2543 100644 --- a/tests/MissileSilo.test.ts +++ b/tests/MissileSilo.test.ts @@ -1,3 +1,6 @@ +import { NukeExecution } from "../src/core/execution/NukeExecution"; +import { SpawnExecution } from "../src/core/execution/SpawnExecution"; +import { UpgradeStructureExecution } from "../src/core/execution/UpgradeStructureExecution"; import { Game, Player, @@ -5,12 +8,9 @@ import { PlayerType, UnitType, } from "../src/core/game/Game"; -import { constructionExecution, executeTicks } from "./util/utils"; -import { NukeExecution } from "../src/core/execution/NukeExecution"; -import { SpawnExecution } from "../src/core/execution/SpawnExecution"; import { TileRef } from "../src/core/game/GameMap"; -import { UpgradeStructureExecution } from "../src/core/execution/UpgradeStructureExecution"; import { setup } from "./util/Setup"; +import { constructionExecution, executeTicks } from "./util/utils"; let game: Game; let attacker: Player; diff --git a/tests/ShellRandom.test.ts b/tests/ShellRandom.test.ts index a8546c174..5c5590383 100644 --- a/tests/ShellRandom.test.ts +++ b/tests/ShellRandom.test.ts @@ -1,3 +1,6 @@ +import { DefensePostExecution } from "../src/core/execution/DefensePostExecution"; +import { ShellExecution } from "../src/core/execution/ShellExecution"; +import { WarshipExecution } from "../src/core/execution/WarshipExecution"; import { Game, Player, @@ -5,9 +8,6 @@ import { PlayerType, UnitType, } from "../src/core/game/Game"; -import { DefensePostExecution } from "../src/core/execution/DefensePostExecution"; -import { ShellExecution } from "../src/core/execution/ShellExecution"; -import { WarshipExecution } from "../src/core/execution/WarshipExecution"; import { setup } from "./util/Setup"; const coastX = 7; diff --git a/tests/TerritoryCapture.test.ts b/tests/TerritoryCapture.test.ts index 5724dea32..e46678c08 100644 --- a/tests/TerritoryCapture.test.ts +++ b/tests/TerritoryCapture.test.ts @@ -1,5 +1,5 @@ -import { Player, PlayerInfo, PlayerType } from "../src/core/game/Game"; import { SpawnExecution } from "../src/core/execution/SpawnExecution"; +import { Player, PlayerInfo, PlayerType } from "../src/core/game/Game"; import { setup } from "./util/Setup"; describe("Territory management", () => { diff --git a/tests/Warship.test.ts b/tests/Warship.test.ts index fbfc26e80..b883b6587 100644 --- a/tests/Warship.test.ts +++ b/tests/Warship.test.ts @@ -1,3 +1,5 @@ +import { MoveWarshipExecution } from "../src/core/execution/MoveWarshipExecution"; +import { WarshipExecution } from "../src/core/execution/WarshipExecution"; import { Game, Player, @@ -5,10 +7,8 @@ import { PlayerType, UnitType, } from "../src/core/game/Game"; -import { MoveWarshipExecution } from "../src/core/execution/MoveWarshipExecution"; -import { WarshipExecution } from "../src/core/execution/WarshipExecution"; -import { executeTicks } from "./util/utils"; import { setup } from "./util/Setup"; +import { executeTicks } from "./util/utils"; const coastX = 7; let game: Game; diff --git a/tests/client/graphics/RadialMenuElements.test.ts b/tests/client/graphics/RadialMenuElements.test.ts index 29d6b893d..df8c796d4 100644 --- a/tests/client/graphics/RadialMenuElements.test.ts +++ b/tests/client/graphics/RadialMenuElements.test.ts @@ -2,16 +2,16 @@ * @jest-environment jsdom */ import { - COLORS, - MenuElementParams, - Slot, attackMenuElement, buildMenuElement, + COLORS, + MenuElementParams, rootMenuElement, + Slot, } from "../../../src/client/graphics/layers/RadialMenuElements"; -import { GameView, PlayerView } from "../../../src/core/game/GameView"; -import { TileRef } from "../../../src/core/game/GameMap"; import { UnitType } from "../../../src/core/game/Game"; +import { TileRef } from "../../../src/core/game/GameMap"; +import { GameView, PlayerView } from "../../../src/core/game/GameView"; jest.mock("../../../src/client/Utils", () => ({ translateText: jest.fn((key: string) => key), diff --git a/tests/core/executions/NukeExecution.test.ts b/tests/core/executions/NukeExecution.test.ts index 789fb043c..5ed577f44 100644 --- a/tests/core/executions/NukeExecution.test.ts +++ b/tests/core/executions/NukeExecution.test.ts @@ -1,3 +1,4 @@ +import { NukeExecution } from "../../../src/core/execution/NukeExecution"; import { Game, Player, @@ -5,10 +6,9 @@ import { PlayerType, UnitType, } from "../../../src/core/game/Game"; -import { NukeExecution } from "../../../src/core/execution/NukeExecution"; +import { setup } from "../../util/Setup"; import { TestConfig } from "../../util/TestConfig"; import { executeTicks } from "../../util/utils"; -import { setup } from "../../util/Setup"; let game: Game; let player: Player; diff --git a/tests/core/executions/SAMLauncherExecution.test.ts b/tests/core/executions/SAMLauncherExecution.test.ts index a98eddf1e..c4f5ad557 100644 --- a/tests/core/executions/SAMLauncherExecution.test.ts +++ b/tests/core/executions/SAMLauncherExecution.test.ts @@ -1,3 +1,7 @@ +import { NukeExecution } from "../../../src/core/execution/NukeExecution"; +import { SAMLauncherExecution } from "../../../src/core/execution/SAMLauncherExecution"; +import { SpawnExecution } from "../../../src/core/execution/SpawnExecution"; +import { UpgradeStructureExecution } from "../../../src/core/execution/UpgradeStructureExecution"; import { Game, Player, @@ -5,12 +9,8 @@ import { PlayerType, UnitType, } from "../../../src/core/game/Game"; -import { constructionExecution, executeTicks } from "../../util/utils"; -import { NukeExecution } from "../../../src/core/execution/NukeExecution"; -import { SAMLauncherExecution } from "../../../src/core/execution/SAMLauncherExecution"; -import { SpawnExecution } from "../../../src/core/execution/SpawnExecution"; -import { UpgradeStructureExecution } from "../../../src/core/execution/UpgradeStructureExecution"; import { setup } from "../../util/Setup"; +import { constructionExecution, executeTicks } from "../../util/utils"; let game: Game; let attacker: Player; diff --git a/tests/core/executions/TradeShipExecution.test.ts b/tests/core/executions/TradeShipExecution.test.ts index 43879162d..0aab3fbce 100644 --- a/tests/core/executions/TradeShipExecution.test.ts +++ b/tests/core/executions/TradeShipExecution.test.ts @@ -1,5 +1,5 @@ -import { Game, Player, Unit } from "../../../src/core/game/Game"; import { TradeShipExecution } from "../../../src/core/execution/TradeShipExecution"; +import { Game, Player, Unit } from "../../../src/core/game/Game"; import { setup } from "../../util/Setup"; describe("TradeShipExecution", () => { diff --git a/tests/core/game/GameImpl.test.ts b/tests/core/game/GameImpl.test.ts index ae3039232..aabcf5c0f 100644 --- a/tests/core/game/GameImpl.test.ts +++ b/tests/core/game/GameImpl.test.ts @@ -1,13 +1,13 @@ +import { AttackExecution } from "../../../src/core/execution/AttackExecution"; +import { AllianceRequestExecution } from "../../../src/core/execution/alliance/AllianceRequestExecution"; +import { AllianceRequestReplyExecution } from "../../../src/core/execution/alliance/AllianceRequestReplyExecution"; +import { SpawnExecution } from "../../../src/core/execution/SpawnExecution"; import { Game, Player, PlayerInfo, PlayerType, } from "../../../src/core/game/Game"; -import { AllianceRequestExecution } from "../../../src/core/execution/alliance/AllianceRequestExecution"; -import { AllianceRequestReplyExecution } from "../../../src/core/execution/alliance/AllianceRequestReplyExecution"; -import { AttackExecution } from "../../../src/core/execution/AttackExecution"; -import { SpawnExecution } from "../../../src/core/execution/SpawnExecution"; import { TileRef } from "../../../src/core/game/GameMap"; import { setup } from "../../util/Setup"; diff --git a/tests/core/game/RailNetwork.test.ts b/tests/core/game/RailNetwork.test.ts index 9cd724f69..f900552ef 100644 --- a/tests/core/game/RailNetwork.test.ts +++ b/tests/core/game/RailNetwork.test.ts @@ -1,7 +1,10 @@ -import { RailNetworkImpl, StationManagerImpl } from "../../../src/core/game/RailNetworkImpl"; -import { Cluster } from "../../../src/core/game/TrainStation"; -import { Railroad } from "../../../src/core/game/Railroad"; import { Unit } from "../../../src/core/game/Game"; +import { + RailNetworkImpl, + StationManagerImpl, +} from "../../../src/core/game/RailNetworkImpl"; +import { Railroad } from "../../../src/core/game/Railroad"; +import { Cluster } from "../../../src/core/game/TrainStation"; // Mock types const createMockStation = (unitId: number): any => { diff --git a/tests/core/game/TrainStation.test.ts b/tests/core/game/TrainStation.test.ts index 738abf3f0..b0ed06165 100644 --- a/tests/core/game/TrainStation.test.ts +++ b/tests/core/game/TrainStation.test.ts @@ -1,6 +1,6 @@ -import { Cluster, TrainStation } from "../../../src/core/game/TrainStation"; -import { Game, Player, Unit, UnitType } from "../../../src/core/game/Game"; import { TrainExecution } from "../../../src/core/execution/TrainExecution"; +import { Game, Player, Unit, UnitType } from "../../../src/core/game/Game"; +import { Cluster, TrainStation } from "../../../src/core/game/TrainStation"; jest.mock("../../../src/core/game/Game"); jest.mock("../../../src/core/execution/TrainExecution"); diff --git a/tests/perf/AstarPerf.ts b/tests/perf/AstarPerf.ts index 457399ac1..b6a8a92dc 100644 --- a/tests/perf/AstarPerf.ts +++ b/tests/perf/AstarPerf.ts @@ -1,7 +1,7 @@ import Benchmark from "benchmark"; -import { PathFinder } from "../../src/core/pathfinding/PathFinding"; import { dirname } from "path"; import { fileURLToPath } from "url"; +import { PathFinder } from "../../src/core/pathfinding/PathFinding"; import { setup } from "../util/Setup"; const game = await setup( diff --git a/tests/util/Setup.ts b/tests/util/Setup.ts index e50904864..c170a2dd3 100644 --- a/tests/util/Setup.ts +++ b/tests/util/Setup.ts @@ -1,3 +1,6 @@ +import fs from "fs"; +import path from "path"; +import { z } from "zod"; import { Difficulty, Game, @@ -7,18 +10,15 @@ import { PlayerInfo, PlayerType, } from "../../src/core/game/Game"; +import { createGame } from "../../src/core/game/GameImpl"; import { - MapManifestSchema, genTerrainFromBin, + MapManifestSchema, } from "../../src/core/game/TerrainMapLoader"; +import { UserSettings } from "../../src/core/game/UserSettings"; import { GameConfig } from "../../src/core/Schemas"; import { TestConfig } from "./TestConfig"; import { TestServerConfig } from "./TestServerConfig"; -import { UserSettings } from "../../src/core/game/UserSettings"; -import { createGame } from "../../src/core/game/GameImpl"; -import fs from "fs"; -import path from "path"; -import { z } from "zod"; export async function setup( mapName: string, diff --git a/tests/util/TestConfig.ts b/tests/util/TestConfig.ts index 3b6bd9373..69b23f3cd 100644 --- a/tests/util/TestConfig.ts +++ b/tests/util/TestConfig.ts @@ -1,3 +1,5 @@ +import { NukeMagnitude } from "../../src/core/configuration/Config"; +import { DefaultConfig } from "../../src/core/configuration/DefaultConfig"; import { Game, Player, @@ -5,8 +7,6 @@ import { Tick, UnitType, } from "../../src/core/game/Game"; -import { DefaultConfig } from "../../src/core/configuration/DefaultConfig"; -import { NukeMagnitude } from "../../src/core/configuration/Config"; import { TileRef } from "../../src/core/game/GameMap"; export class TestConfig extends DefaultConfig { diff --git a/tests/util/TestServerConfig.ts b/tests/util/TestServerConfig.ts index 2f0a23ee1..86a277d65 100644 --- a/tests/util/TestServerConfig.ts +++ b/tests/util/TestServerConfig.ts @@ -1,7 +1,7 @@ -import { GameEnv, ServerConfig } from "../../src/core/configuration/Config"; -import { GameID } from "../../src/core/Schemas"; -import { GameMapType } from "../../src/core/game/Game"; import { JWK } from "jose"; +import { GameEnv, ServerConfig } from "../../src/core/configuration/Config"; +import { GameMapType } from "../../src/core/game/Game"; +import { GameID } from "../../src/core/Schemas"; export class TestServerConfig implements ServerConfig { allowedFlares(): string[] | undefined { diff --git a/tests/util/utils.ts b/tests/util/utils.ts index 3a8f3a2e3..dbdfb3d1d 100644 --- a/tests/util/utils.ts +++ b/tests/util/utils.ts @@ -3,8 +3,8 @@ // However buildUnit do not create executions (e.g.: WarshipExecution) // If you also need execution use function below. Does not work with things not -import { Game, Player, UnitType } from "../../src/core/game/Game"; import { ConstructionExecution } from "../../src/core/execution/ConstructionExecution"; +import { Game, Player, UnitType } from "../../src/core/game/Game"; // built via UI (e.g.: trade ships) export function constructionExecution( diff --git a/webpack.config.js b/webpack.config.js index a60ae5367..0820e8cd0 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,9 +1,9 @@ +import { execSync } from "child_process"; import CopyPlugin from "copy-webpack-plugin"; import ESLintPlugin from "eslint-webpack-plugin"; import HtmlWebpackPlugin from "html-webpack-plugin"; -import { execSync } from "child_process"; -import { fileURLToPath } from "url"; import path from "path"; +import { fileURLToPath } from "url"; import webpack from "webpack"; const __filename = fileURLToPath(import.meta.url); @@ -111,13 +111,13 @@ export default async (env, argv) => { // Add optimization for HTML minify: isProduction ? { - collapseWhitespace: true, - removeComments: true, - removeRedundantAttributes: true, - removeScriptTypeAttributes: true, - removeStyleLinkTypeAttributes: true, - useShortDoctype: true, - } + collapseWhitespace: true, + removeComments: true, + removeRedundantAttributes: true, + removeScriptTypeAttributes: true, + removeStyleLinkTypeAttributes: true, + useShortDoctype: true, + } : false, }), new webpack.DefinePlugin({ @@ -160,91 +160,91 @@ export default async (env, argv) => { devServer: isProduction ? {} : { - devMiddleware: { writeToDisk: true }, - static: { - directory: path.join(__dirname, "static"), + devMiddleware: { writeToDisk: true }, + static: { + directory: path.join(__dirname, "static"), + }, + historyApiFallback: true, + compress: true, + port: 9000, + proxy: [ + // WebSocket proxies + { + context: ["/socket"], + target: "ws://localhost:3000", + ws: true, + changeOrigin: true, + logLevel: "debug", + }, + // Worker WebSocket proxies - using direct paths without /socket suffix + { + context: ["/w0"], + target: "ws://localhost:3001", + ws: true, + secure: false, + changeOrigin: true, + logLevel: "debug", + }, + { + context: ["/w1"], + target: "ws://localhost:3002", + ws: true, + secure: false, + changeOrigin: true, + logLevel: "debug", + }, + { + context: ["/w2"], + target: "ws://localhost:3003", + ws: true, + secure: false, + changeOrigin: true, + logLevel: "debug", + }, + // Worker proxies for HTTP requests + { + context: ["/w0"], + target: "http://localhost:3001", + pathRewrite: { "^/w0": "" }, + secure: false, + changeOrigin: true, + logLevel: "debug", + }, + { + context: ["/w1"], + target: "http://localhost:3002", + pathRewrite: { "^/w1": "" }, + secure: false, + changeOrigin: true, + logLevel: "debug", + }, + { + context: ["/w2"], + target: "http://localhost:3003", + pathRewrite: { "^/w2": "" }, + secure: false, + changeOrigin: true, + logLevel: "debug", + }, + // Original API endpoints + { + context: [ + "/api/env", + "/api/game", + "/api/public_lobbies", + "/api/join_game", + "/api/start_game", + "/api/create_game", + "/api/archive_singleplayer_game", + "/api/auth/callback", + "/api/auth/discord", + "/api/kick_player", + ], + target: "http://localhost:3000", + secure: false, + changeOrigin: true, + }, + ], }, - historyApiFallback: true, - compress: true, - port: 9000, - proxy: [ - // WebSocket proxies - { - context: ["/socket"], - target: "ws://localhost:3000", - ws: true, - changeOrigin: true, - logLevel: "debug", - }, - // Worker WebSocket proxies - using direct paths without /socket suffix - { - context: ["/w0"], - target: "ws://localhost:3001", - ws: true, - secure: false, - changeOrigin: true, - logLevel: "debug", - }, - { - context: ["/w1"], - target: "ws://localhost:3002", - ws: true, - secure: false, - changeOrigin: true, - logLevel: "debug", - }, - { - context: ["/w2"], - target: "ws://localhost:3003", - ws: true, - secure: false, - changeOrigin: true, - logLevel: "debug", - }, - // Worker proxies for HTTP requests - { - context: ["/w0"], - target: "http://localhost:3001", - pathRewrite: { "^/w0": "" }, - secure: false, - changeOrigin: true, - logLevel: "debug", - }, - { - context: ["/w1"], - target: "http://localhost:3002", - pathRewrite: { "^/w1": "" }, - secure: false, - changeOrigin: true, - logLevel: "debug", - }, - { - context: ["/w2"], - target: "http://localhost:3003", - pathRewrite: { "^/w2": "" }, - secure: false, - changeOrigin: true, - logLevel: "debug", - }, - // Original API endpoints - { - context: [ - "/api/env", - "/api/game", - "/api/public_lobbies", - "/api/join_game", - "/api/start_game", - "/api/create_game", - "/api/archive_singleplayer_game", - "/api/auth/callback", - "/api/auth/discord", - "/api/kick_player", - ], - target: "http://localhost:3000", - secure: false, - changeOrigin: true, - }, - ], - }, }; };