From 4dd57c1605c7cfa53a14225f0530f8a22c083a52 Mon Sep 17 00:00:00 2001 From: Bagel03 <70449196+Bagel03@users.noreply.github.com> Date: Fri, 18 Nov 2022 10:20:54 -0500 Subject: [PATCH] Rerun tooling to combat agressive any --- src/ts/application.ts | 134 +++--- src/ts/core/animation_frame.ts | 22 +- src/ts/core/assert.ts | 8 +- src/ts/core/async_compression.ts | 36 +- src/ts/core/atlas_definitions.ts | 8 +- src/ts/core/background_resources_loader.ts | 88 ++-- src/ts/core/buffer_maintainer.ts | 48 +-- src/ts/core/buffer_utils.ts | 58 +-- src/ts/core/cachebust.ts | 2 +- src/ts/core/click_detector.ts | 60 +-- src/ts/core/config.ts | 18 +- src/ts/core/dpi_manager.ts | 28 +- src/ts/core/draw_utils.ts | 18 +- src/ts/core/explained_result.ts | 16 +- src/ts/core/factory.ts | 10 +- src/ts/core/game_state.ts | 50 +-- src/ts/core/global_registries.ts | 2 +- src/ts/core/globals.ts | 4 +- src/ts/core/input_distributor.ts | 52 +-- src/ts/core/input_receiver.ts | 2 +- src/ts/core/loader.ts | 50 +-- src/ts/core/logging.ts | 74 ++-- src/ts/core/lzstring.ts | 66 +-- src/ts/core/modal_dialog_elements.ts | 116 ++--- src/ts/core/modal_dialog_forms.ts | 68 +-- src/ts/core/polyfills.ts | 46 +- src/ts/core/query_parameters.ts | 6 +- src/ts/core/read_write_proxy.ts | 88 ++-- src/ts/core/rectangle.ts | 64 +-- src/ts/core/request_channel.ts | 18 +- src/ts/core/restriction_manager.ts | 10 +- src/ts/core/rng.ts | 38 +- src/ts/core/sensitive_utils.encrypt.ts | 8 +- src/ts/core/signal.ts | 26 +- src/ts/core/singleton_factory.ts | 14 +- src/ts/core/sprites.ts | 130 +++--- src/ts/core/stale_area_detector.ts | 16 +- src/ts/core/state_manager.ts | 20 +- src/ts/core/steam_sso.ts | 40 +- src/ts/core/textual_game_state.ts | 24 +- src/ts/core/tracked_state.ts | 8 +- src/ts/core/utils.ts | 184 ++++---- src/ts/core/vector.ts | 50 +-- src/ts/game/achievement_proxy.ts | 26 +- src/ts/game/automatic_save.ts | 18 +- src/ts/game/base_item.ts | 10 +- src/ts/game/belt_path.ts | 400 +++++++++--------- src/ts/game/blueprint.ts | 68 +-- src/ts/game/building_codes.ts | 16 +- src/ts/game/buildings/analyzer.ts | 16 +- src/ts/game/buildings/balancer.ts | 28 +- src/ts/game/buildings/belt.ts | 62 +-- src/ts/game/buildings/block.ts | 8 +- src/ts/game/buildings/comparator.ts | 12 +- src/ts/game/buildings/constant_producer.ts | 8 +- src/ts/game/buildings/constant_signal.ts | 16 +- src/ts/game/buildings/cutter.ts | 18 +- src/ts/game/buildings/display.ts | 12 +- src/ts/game/buildings/filter.ts | 14 +- src/ts/game/buildings/goal_acceptor.ts | 8 +- src/ts/game/buildings/hub.ts | 18 +- src/ts/game/buildings/item_producer.ts | 8 +- src/ts/game/buildings/lever.ts | 14 +- src/ts/game/buildings/logic_gate.ts | 30 +- src/ts/game/buildings/miner.ts | 18 +- src/ts/game/buildings/mixer.ts | 12 +- src/ts/game/buildings/painter.ts | 24 +- src/ts/game/buildings/reader.ts | 14 +- src/ts/game/buildings/rotater.ts | 26 +- src/ts/game/buildings/stacker.ts | 12 +- src/ts/game/buildings/storage.ts | 14 +- src/ts/game/buildings/transistor.ts | 22 +- src/ts/game/buildings/trash.ts | 26 +- src/ts/game/buildings/underground_belt.ts | 60 +-- src/ts/game/buildings/virtual_processor.ts | 26 +- src/ts/game/buildings/wire.ts | 48 +-- src/ts/game/buildings/wire_tunnel.ts | 16 +- src/ts/game/camera.ts | 242 +++++------ src/ts/game/colors.ts | 20 +- src/ts/game/component.ts | 6 +- src/ts/game/component_registry.ts | 6 +- src/ts/game/components/belt.ts | 10 +- src/ts/game/components/belt_reader.ts | 8 +- src/ts/game/components/belt_underlays.ts | 4 +- src/ts/game/components/constant_signal.ts | 6 +- src/ts/game/components/display.ts | 2 +- src/ts/game/components/filter.ts | 8 +- src/ts/game/components/goal_acceptor.ts | 12 +- src/ts/game/components/hub.ts | 2 +- src/ts/game/components/item_acceptor.ts | 22 +- src/ts/game/components/item_ejector.ts | 26 +- src/ts/game/components/item_processor.ts | 12 +- src/ts/game/components/item_producer.ts | 2 +- src/ts/game/components/lever.ts | 6 +- src/ts/game/components/logic_gate.ts | 4 +- src/ts/game/components/miner.ts | 10 +- src/ts/game/components/static_map_entity.ts | 38 +- src/ts/game/components/storage.ts | 10 +- src/ts/game/components/underground_belt.ts | 16 +- src/ts/game/components/wire.ts | 6 +- src/ts/game/components/wire_tunnel.ts | 2 +- src/ts/game/components/wired_pins.ts | 12 +- src/ts/game/core.ts | 68 +-- src/ts/game/dynamic_tickrate.ts | 34 +- src/ts/game/entity.ts | 62 +-- src/ts/game/entity_manager.ts | 48 +-- src/ts/game/game_loading_overlay.ts | 18 +- src/ts/game/game_mode.ts | 12 +- src/ts/game/game_mode_registry.ts | 2 +- src/ts/game/game_speed_registry.ts | 2 +- src/ts/game/game_system.ts | 8 +- src/ts/game/game_system_manager.ts | 26 +- src/ts/game/game_system_with_filter.ts | 32 +- src/ts/game/hints.ts | 8 +- src/ts/game/hub_goals.ts | 132 +++--- src/ts/game/hud/base_hud_part.ts | 34 +- src/ts/game/hud/dynamic_dom_attach.ts | 16 +- src/ts/game/hud/hud.ts | 52 +-- src/ts/game/hud/parts/base_toolbar.ts | 106 ++--- src/ts/game/hud/parts/beta_overlay.ts | 4 +- src/ts/game/hud/parts/blueprint_placer.ts | 56 +-- src/ts/game/hud/parts/building_placer.ts | 266 ++++++------ .../game/hud/parts/building_placer_logic.ts | 208 ++++----- src/ts/game/hud/parts/buildings_toolbar.ts | 2 +- src/ts/game/hud/parts/color_blind_helper.ts | 38 +- src/ts/game/hud/parts/constant_signal_edit.ts | 50 +-- src/ts/game/hud/parts/debug_changes.ts | 20 +- src/ts/game/hud/parts/debug_info.ts | 52 +-- src/ts/game/hud/parts/entity_debugger.ts | 44 +- src/ts/game/hud/parts/game_menu.ts | 50 +-- src/ts/game/hud/parts/interactive_tutorial.ts | 142 +++---- src/ts/game/hud/parts/keybinding_overlay.ts | 82 ++-- src/ts/game/hud/parts/layer_preview.ts | 36 +- src/ts/game/hud/parts/lever_toggle.ts | 10 +- src/ts/game/hud/parts/mass_selector.ts | 134 +++--- src/ts/game/hud/parts/miner_highlight.ts | 48 +-- src/ts/game/hud/parts/modal_dialogs.ts | 56 +-- src/ts/game/hud/parts/next_puzzle.ts | 8 +- src/ts/game/hud/parts/notifications.ts | 22 +- src/ts/game/hud/parts/pinned_shapes.ts | 92 ++-- src/ts/game/hud/parts/puzzle_back_to_menu.ts | 8 +- .../hud/parts/puzzle_complete_notification.ts | 42 +- src/ts/game/hud/parts/puzzle_dlc_logo.ts | 6 +- .../game/hud/parts/puzzle_editor_controls.ts | 6 +- src/ts/game/hud/parts/puzzle_editor_review.ts | 100 ++--- .../game/hud/parts/puzzle_editor_settings.ts | 84 ++-- src/ts/game/hud/parts/puzzle_play_metadata.ts | 18 +- src/ts/game/hud/parts/puzzle_play_settings.ts | 18 +- src/ts/game/hud/parts/sandbox_controller.ts | 58 +-- src/ts/game/hud/parts/screenshot_exporter.ts | 44 +- src/ts/game/hud/parts/settings_menu.ts | 38 +- src/ts/game/hud/parts/shape_tooltip.ts | 38 +- src/ts/game/hud/parts/shape_viewer.ts | 40 +- src/ts/game/hud/parts/shop.ts | 92 ++-- .../game/hud/parts/standalone_advantages.ts | 30 +- src/ts/game/hud/parts/statistics.ts | 96 ++--- src/ts/game/hud/parts/statistics_handle.ts | 42 +- src/ts/game/hud/parts/tutorial_hints.ts | 20 +- src/ts/game/hud/parts/tutorial_video_offer.ts | 18 +- src/ts/game/hud/parts/unlock_notification.ts | 44 +- src/ts/game/hud/parts/vignette_overlay.ts | 4 +- src/ts/game/hud/parts/watermark.ts | 14 +- src/ts/game/hud/parts/waypoints.ts | 142 +++---- src/ts/game/hud/parts/wire_info.ts | 38 +- src/ts/game/hud/parts/wires_overlay.ts | 42 +- src/ts/game/hud/parts/wires_toolbar.ts | 2 +- src/ts/game/hud/trailer_maker.ts | 28 +- src/ts/game/item_registry.ts | 2 +- src/ts/game/item_resolver.ts | 10 +- src/ts/game/items/boolean_item.ts | 22 +- src/ts/game/items/color_item.ts | 20 +- src/ts/game/items/shape_item.ts | 16 +- src/ts/game/key_action_mapper.ts | 66 +-- src/ts/game/logic.ts | 166 ++++---- src/ts/game/map.ts | 78 ++-- src/ts/game/map_chunk.ts | 130 +++--- src/ts/game/map_chunk_aggregate.ts | 38 +- src/ts/game/map_chunk_view.ts | 98 ++--- src/ts/game/map_view.ts | 144 +++---- src/ts/game/meta_building.ts | 36 +- src/ts/game/meta_building_registry.ts | 22 +- src/ts/game/modes/levels.ts | 12 +- src/ts/game/modes/puzzle.ts | 34 +- src/ts/game/modes/puzzle_edit.ts | 6 +- src/ts/game/modes/puzzle_play.ts | 44 +- src/ts/game/modes/regular.ts | 66 +-- src/ts/game/production_analytics.ts | 46 +- src/ts/game/root.ts | 10 +- src/ts/game/shape_definition.ts | 240 +++++------ src/ts/game/shape_definition_manager.ts | 54 +-- src/ts/game/sound_proxy.ts | 22 +- src/ts/game/systems/belt.ts | 180 ++++---- src/ts/game/systems/belt_reader.ts | 24 +- src/ts/game/systems/belt_underlays.ts | 112 ++--- src/ts/game/systems/constant_producer.ts | 28 +- src/ts/game/systems/constant_signal.ts | 14 +- src/ts/game/systems/display.ts | 20 +- src/ts/game/systems/filter.ts | 36 +- src/ts/game/systems/goal_acceptor.ts | 38 +- src/ts/game/systems/hub.ts | 52 +-- src/ts/game/systems/item_acceptor.ts | 42 +- src/ts/game/systems/item_ejector.ts | 132 +++--- src/ts/game/systems/item_processor.ts | 210 ++++----- .../game/systems/item_processor_overlays.ts | 40 +- src/ts/game/systems/item_producer.ts | 14 +- src/ts/game/systems/lever.ts | 22 +- src/ts/game/systems/logic_gate.ts | 86 ++-- src/ts/game/systems/map_resources.ts | 50 +-- src/ts/game/systems/miner.ts | 74 ++-- src/ts/game/systems/static_map_entity.ts | 30 +- src/ts/game/systems/storage.ts | 36 +- src/ts/game/systems/underground_belt.ts | 126 +++--- src/ts/game/systems/wire.ts | 200 ++++----- src/ts/game/systems/wired_pins.ts | 82 ++-- src/ts/game/systems/zone.ts | 28 +- src/ts/game/theme.ts | 6 +- src/ts/game/time/base_game_speed.ts | 12 +- src/ts/game/time/fast_forward_game_speed.ts | 6 +- src/ts/game/time/game_time.ts | 32 +- src/ts/game/time/paused_game_speed.ts | 6 +- src/ts/game/time/regular_game_speed.ts | 4 +- src/ts/game/tutorial_goals.ts | 2 +- src/ts/game/tutorial_goals_mappings.ts | 10 +- src/ts/languages.ts | 2 +- src/ts/main.ts | 17 +- src/ts/mods/mod.ts | 2 +- src/ts/mods/mod_interface.ts | 168 ++++---- src/ts/mods/mod_signals.ts | 2 +- src/ts/mods/modloader.ts | 80 ++-- src/ts/platform/achievement_provider.ts | 140 +++--- src/ts/platform/ad_provider.ts | 2 +- src/ts/platform/ad_providers/adinplay.ts | 58 +-- src/ts/platform/ad_providers/crazygames.ts | 32 +- .../platform/ad_providers/gamedistribution.ts | 28 +- .../platform/ad_providers/no_ad_provider.ts | 4 +- src/ts/platform/analytics.ts | 8 +- src/ts/platform/api.ts | 32 +- src/ts/platform/browser/game_analytics.ts | 106 ++--- src/ts/platform/browser/google_analytics.ts | 22 +- .../browser/no_achievement_provider.ts | 10 +- src/ts/platform/browser/sound.ts | 64 +-- src/ts/platform/browser/storage.ts | 36 +- src/ts/platform/browser/storage_indexed_db.ts | 66 +-- src/ts/platform/browser/wrapper.ts | 62 +-- .../electron/steam_achievement_provider.ts | 16 +- src/ts/platform/electron/storage.ts | 10 +- src/ts/platform/electron/wrapper.ts | 44 +- src/ts/platform/game_analytics.ts | 10 +- src/ts/platform/sound.ts | 52 +-- src/ts/platform/storage.ts | 2 +- src/ts/platform/wrapper.ts | 20 +- src/ts/profile/application_settings.ts | 194 ++++----- src/ts/profile/setting_types.ts | 92 ++-- src/ts/savegame/puzzle_serializer.ts | 36 +- src/ts/savegame/savegame.ts | 36 +- src/ts/savegame/savegame_compressor.ts | 64 +-- src/ts/savegame/savegame_interface.ts | 20 +- .../savegame/savegame_interface_registry.ts | 6 +- src/ts/savegame/savegame_manager.ts | 70 +-- src/ts/savegame/savegame_serializer.ts | 24 +- src/ts/savegame/schemas/1000.ts | 6 +- src/ts/savegame/schemas/1001.ts | 22 +- src/ts/savegame/schemas/1002.ts | 22 +- src/ts/savegame/schemas/1003.ts | 12 +- src/ts/savegame/schemas/1004.ts | 18 +- src/ts/savegame/schemas/1005.ts | 26 +- src/ts/savegame/schemas/1006.ts | 40 +- src/ts/savegame/schemas/1007.ts | 18 +- src/ts/savegame/schemas/1008.ts | 12 +- src/ts/savegame/schemas/1009.ts | 12 +- src/ts/savegame/schemas/1010.ts | 10 +- src/ts/savegame/serialization.ts | 58 +-- src/ts/savegame/serialization_data_types.ts | 310 +++++++------- src/ts/savegame/serializer_internal.ts | 28 +- src/ts/states/about.ts | 14 +- src/ts/states/changelog.ts | 22 +- src/ts/states/ingame.ts | 84 ++-- src/ts/states/keybindings.ts | 70 +-- src/ts/states/login.ts | 28 +- src/ts/states/main_menu.ts | 258 +++++------ src/ts/states/mobile_warning.ts | 12 +- src/ts/states/mods.ts | 34 +- src/ts/states/preload.ts | 170 ++++---- src/ts/states/puzzle_menu.ts | 216 +++++----- src/ts/states/settings.ts | 74 ++-- src/ts/states/wegame_splash.ts | 6 +- src/ts/translations.ts | 31 +- ...kground_animation_frame_emittter.worker.ts | 12 +- src/ts/webworkers/compression.worker.ts | 22 +- 289 files changed, 6536 insertions(+), 6524 deletions(-) diff --git a/src/ts/application.ts b/src/ts/application.ts index 6436762f..c99b35c3 100644 --- a/src/ts/application.ts +++ b/src/ts/application.ts @@ -40,13 +40,13 @@ import { MOD_SIGNALS } from "./mods/mod_signals"; import { ModsState } from "./states/mods"; import type { AchievementProviderInterface } from "./platform/achievement_provider"; -import type { SoundInterface } from "./platform/sound"; +import type { SoundInterface } from "./platform/sound"; import type { StorageInterface } from "./platform/storage"; -const logger: any = createLogger("application"); +const logger = createLogger("application"); // Set the name of the hidden property and the change event for visibility -let pageHiddenPropName: any, pageVisibilityEventName: any; +let pageHiddenPropName: string, pageVisibilityEventName: string; if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support pageHiddenPropName = "hidden"; @@ -62,9 +62,7 @@ if (typeof document.hidden !== "undefined") { } export class Application { - public unloaded = true; - - // Global stuff + public unloaded = false; public settings = new ApplicationSettings(this); public ticker = new AnimationFrame(); public stateMgr = new StateManager(this); @@ -72,44 +70,28 @@ export class Application { public inputMgr = new InputDistributor(this); public backgroundResourceLoader = new BackgroundResourcesLoader(this); public clientApi = new ClientAPI(this); - - // Restrictions (Like demo etc) public restrictionMgr = new RestrictionManager(this); - - // Platform dependent stuff public storage: StorageInterface = null; - public sound: SoundInterface = new SoundImplBrowser(this); - public platformWrapper: PlatformWrapperInterface = G_IS_STANDALONE ? new PlatformWrapperImplElectron(this) : new PlatformWrapperImplBrowser(this); - public achievementProvider: AchievementProviderInterface = new NoAchievementProvider(this); - public adProvider: AdProviderInterface = new NoAdProvider(this); - public analytics: AnalyticsInterface = new GoogleAnalyticsImpl(this); - public gameAnalytics = new ShapezGameAnalytics(this); - - // Track if the window is focused (only relevant for browser) + public sound: SoundInterface = null; + public platformWrapper: PlatformWrapperInterface = null; + public achievementProvider: AchievementProviderInterface = null; + public adProvider: AdProviderInterface = null; + public analytics: AnalyticsInterface = null; + public gameAnalytics: ShapezGameAnalytics = null; public focused = true; - - // Track if the window is visible public pageVisible = true; - - // Track if the app is paused (cordova) public applicationPaused = false; - public trackedIsRenderable = new TrackedState(this.onAppRenderableStateChanged, this); - public trackedIsPlaying = new TrackedState(this.onAppPlayingStateChanged, this); - - // Dimensions + public trackedIsRenderable: TypedTrackedState = new TrackedState(this.onAppRenderableStateChanged, this); + public trackedIsPlaying: TypedTrackedState = new TrackedState(this.onAppPlayingStateChanged, this); public screenWidth = 0; public screenHeight = 0; - // Store the timestamp where we last checked for a screen resize, since orientationchange is unreliable with cordova - public lastResizeCheck: number = null; - // Store the mouse position, or null if not available - public mousePosition: Vector = null; - - + public lastResizeCheck = null; + public mousePosition: Vector | null = null; /** * Boots the application */ - async boot(): Promise { + async boot() { console.log("Booting ..."); assert(!GLOBAL_APP, "Tried to construct application twice"); @@ -122,12 +104,11 @@ export class Application { try { await MODS.initMods(); } - catch (ex: any) { + catch (ex) { alert("Failed to load mods (launch with --dev for more info): \n\n" + ex); } - this.unloaded = false; - + this.initPlatformDependentInstances(); this.registerStates(); this.registerEventListeners(); @@ -151,11 +132,31 @@ export class Application { MOD_SIGNALS.appBooted.dispatch(); } + /** + * Initializes all platform instances + */ + initPlatformDependentInstances() { + logger.log("Creating platform dependent instances (standalone=", G_IS_STANDALONE, ")"); + + if (G_IS_STANDALONE) { + this.platformWrapper = new PlatformWrapperImplElectron(this); + } + else { + this.platformWrapper = new PlatformWrapperImplBrowser(this); + } + + // Start with empty ad provider + this.adProvider = new NoAdProvider(this); + this.sound = new SoundImplBrowser(this); + this.analytics = new GoogleAnalyticsImpl(this); + this.gameAnalytics = new ShapezGameAnalytics(this); + this.achievementProvider = new NoAchievementProvider(this); + } /** * Registers all game states */ - registerStates(): void { - const states: Array = [ + registerStates() { + const states: Array = [ WegameSplashState, PreloadState, MobileWarningState, @@ -169,6 +170,7 @@ export class Application { LoginState, ModsState, ]; + for (let i = 0; i < states.length; ++i) { this.stateMgr.register(states[i]); } @@ -177,7 +179,7 @@ export class Application { /** * Registers all event listeners */ - registerEventListeners(): void { + registerEventListeners() { window.addEventListener("focus", this.onFocus.bind(this)); window.addEventListener("blur", this.onBlur.bind(this)); @@ -191,19 +193,17 @@ export class Application { // Unload events window.addEventListener("beforeunload", this.onBeforeUnload.bind(this), true); - document.addEventListener(pageVisibilityEventName, this.handleVisibilityChange.bind(this), false); // Track touches so we can update the focus appropriately document.addEventListener("touchstart", this.updateFocusAfterUserInteraction.bind(this), true); document.addEventListener("touchend", this.updateFocusAfterUserInteraction.bind(this), true); } - /** * Checks the focus after a touch */ - updateFocusAfterUserInteraction(event: TouchEvent): void { - const target = (event.target as HTMLElement); + updateFocusAfterUserInteraction(event: TouchEvent) { + const target = event.target as HTMLElement; if (!target || !target.tagName) { // Safety check logger.warn("Invalid touchstart/touchend event:", event); @@ -222,16 +222,16 @@ export class Application { // If we click an input field, focus it now if (target.tagName.toLowerCase() === "input") { // We *really* need the focus - waitNextFrame().then((): any => target.focus()); + waitNextFrame().then(() => target.focus()); } } /** * Handles a page visibility change event */ - handleVisibilityChange(event: Event): void { + handleVisibilityChange(event: Event) { window.focus(); - const pageVisible: any = !document[pageHiddenPropName]; + const pageVisible = !document[pageHiddenPropName]; if (pageVisible !== this.pageVisible) { this.pageVisible = pageVisible; logger.log("Visibility changed:", this.pageVisible); @@ -242,35 +242,35 @@ export class Application { /** * Handles a mouse move event */ - handleMousemove(event: MouseEvent): void { + handleMousemove(event: MouseEvent) { this.mousePosition = new Vector(event.clientX, event.clientY); } /** * Internal on focus handler */ - onFocus(): void { + onFocus() { this.focused = true; } /** * Internal blur handler */ - onBlur(): void { + onBlur() { this.focused = false; } /** * Returns if the app is currently visible */ - isRenderable(): boolean { + isRenderable() { return !this.applicationPaused && this.pageVisible; } - onAppRenderableStateChanged(renderable: boolean): void { + onAppRenderableStateChanged(renderable: boolean) { logger.log("Application renderable:", renderable); window.focus(); - const currentState: any = this.stateMgr.getCurrentState(); + const currentState = this.stateMgr.getCurrentState(); if (!renderable) { if (currentState) { currentState.onAppPause(); @@ -286,11 +286,11 @@ export class Application { this.sound.onPageRenderableStateChanged(renderable); } - onAppPlayingStateChanged(playing: boolean): void { + onAppPlayingStateChanged(playing: boolean) { try { this.adProvider.setPlayStatus(playing); } - catch (ex: any) { + catch (ex) { console.warn("Play status changed"); } } @@ -298,10 +298,9 @@ export class Application { /** * Internal before-unload handler */ - onBeforeUnload(event: BeforeUnloadEvent): void { + onBeforeUnload(event) { logSection("BEFORE UNLOAD HANDLER", "#f77"); - const currentState: GameState = this.stateMgr.getCurrentState(); - + const currentState = this.stateMgr.getCurrentState(); if (!G_IS_DEV && currentState && currentState.getHasUnloadConfirmation()) { if (!G_IS_STANDALONE) { // Need to show a "Are you sure you want to exit" @@ -310,7 +309,6 @@ export class Application { } } } - /** * Deinitializes the application */ @@ -321,12 +319,12 @@ export class Application { /** * Background frame update callback */ - onBackgroundFrame(dt: number): void { + onBackgroundFrame(dt: number) { if (this.isRenderable()) { return; } - const currentState: any = this.stateMgr.getCurrentState(); + const currentState = this.stateMgr.getCurrentState(); if (currentState) { currentState.onBackgroundTick(dt); } @@ -335,12 +333,12 @@ export class Application { /** * Frame update callback */ - onFrameEmitted(dt: number): void { + onFrameEmitted(dt: number) { if (!this.isRenderable()) { return; } - const time: any = performance.now(); + const time = performance.now(); // Periodically check for resizes, this is expensive (takes 2-3ms so only do it once in a while!) if (!this.lastResizeCheck || time - this.lastResizeCheck > 1000) { @@ -348,7 +346,7 @@ export class Application { this.lastResizeCheck = time; } - const currentState: any = this.stateMgr.getCurrentState(); + const currentState = this.stateMgr.getCurrentState(); this.trackedIsPlaying.set(currentState && currentState.getIsIngame()); if (currentState) { currentState.onRender(dt); @@ -358,19 +356,19 @@ export class Application { /** * Checks if the app resized. Only does this once in a while */ - checkResize(forceUpdate: boolean = false): void { + checkResize(forceUpdate: boolean = false) { const w = window.innerWidth; const h = window.innerHeight; if (this.screenWidth !== w || this.screenHeight !== h || forceUpdate) { this.screenWidth = w; this.screenHeight = h; - const currentState: GameState = this.stateMgr.getCurrentState(); + const currentState = this.stateMgr.getCurrentState(); if (currentState) { currentState.onResized(this.screenWidth, this.screenHeight); } - const scale: number = this.getEffectiveUiScale(); - waitNextFrame().then((): any => document.documentElement.style.setProperty("--ui-scale", `${scale}`)); + const scale = this.getEffectiveUiScale(); + waitNextFrame().then(() => document.documentElement.style.setProperty("--ui-scale", `${scale}`)); window.focus(); } } @@ -385,7 +383,7 @@ export class Application { /** * Callback after ui scale has changed */ - updateAfterUiScaleChanged(): void { + updateAfterUiScaleChanged() { this.checkResize(true); } } diff --git a/src/ts/core/animation_frame.ts b/src/ts/core/animation_frame.ts index 0f998971..b77f76a4 100644 --- a/src/ts/core/animation_frame.ts +++ b/src/ts/core/animation_frame.ts @@ -2,9 +2,9 @@ import { Signal } from "./signal"; // @ts-ignore import BackgroundAnimationFrameEmitterWorker from "../webworkers/background_animation_frame_emittter.worker"; import { createLogger } from "./logging"; -const logger: any = createLogger("animation_frame"); -const maxDtMs: any = 1000; -const resetDtMs: any = 16; +const logger = createLogger("animation_frame"); +const maxDtMs = 1000; +const resetDtMs = 16; export class AnimationFrame { public frameEmitted = new Signal(); public bgFrameEmitted = new Signal(); @@ -14,33 +14,33 @@ export class AnimationFrame { public backgroundWorker = new BackgroundAnimationFrameEmitterWorker(); constructor() { - this.backgroundWorker.addEventListener("error", (err: any): any => { + this.backgroundWorker.addEventListener("error", err => { logger.error("Error in background fps worker:", err); }); this.backgroundWorker.addEventListener("message", this.handleBackgroundTick.bind(this)); } - handleBackgroundTick(): any { - const time: any = performance.now(); - let dt: any = time - this.bgLastTime; + handleBackgroundTick() { + const time = performance.now(); + let dt = time - this.bgLastTime; if (dt > maxDtMs) { dt = resetDtMs; } this.bgFrameEmitted.dispatch(dt); this.bgLastTime = time; } - start(): any { + start() { assertAlways(window.requestAnimationFrame, "requestAnimationFrame is not supported!"); this.handleAnimationFrame(); } - handleAnimationFrame(time: any): any { - let dt: any = time - this.lastTime; + handleAnimationFrame(time) { + let dt = time - this.lastTime; if (dt > maxDtMs) { dt = resetDtMs; } try { this.frameEmitted.dispatch(dt); } - catch (ex: any) { + catch (ex) { console.error(ex); } this.lastTime = time; diff --git a/src/ts/core/assert.ts b/src/ts/core/assert.ts index 80fd8315..4d86d4aa 100644 --- a/src/ts/core/assert.ts +++ b/src/ts/core/assert.ts @@ -1,13 +1,13 @@ import { createLogger } from "./logging"; -const logger: any = createLogger("assert"); -let assertionErrorShown: any = false; -function initAssert(): any { +const logger = createLogger("assert"); +let assertionErrorShown = false; +function initAssert() { /** * Expects a given condition to be true * @param {} failureMessage */ // @ts-ignore - window.assert = function (condition: Boolean, ...failureMessage: ...String): any { + window.assert = function (condition: Boolean, ...failureMessage: ...String) { if (!condition) { logger.error("assertion failed:", ...failureMessage); if (!assertionErrorShown) { diff --git a/src/ts/core/async_compression.ts b/src/ts/core/async_compression.ts index 0a9ae747..9d5a19f3 100644 --- a/src/ts/core/async_compression.ts +++ b/src/ts/core/async_compression.ts @@ -2,15 +2,15 @@ import CompressionWorker from "../webworkers/compression.worker"; import { createLogger } from "./logging"; import { round2Digits } from "./utils"; -const logger: any = createLogger("async_compression"); -export let compressionPrefix: any = String.fromCodePoint(1); -function checkCryptPrefix(prefix: any): any { +const logger = createLogger("async_compression"); +export let compressionPrefix = String.fromCodePoint(1); +function checkCryptPrefix(prefix) { try { window.localStorage.setItem("prefix_test", prefix); window.localStorage.removeItem("prefix_test"); return true; } - catch (ex: any) { + catch (ex) { logger.warn("Prefix '" + prefix + "' not available"); return false; } @@ -36,27 +36,27 @@ class AsynCompression { } = {}; constructor() { - this.worker.addEventListener("message", (event: any): any => { - const { jobId, result }: any = event.data; - const jobData: any = this.currentJobs[jobId]; + this.worker.addEventListener("message", event => { + const { jobId, result } = event.data; + const jobData = this.currentJobs[jobId]; if (!jobData) { logger.error("Failed to resolve job result, job id", jobId, "is not known"); return; } - const duration: any = performance.now() - jobData.startTime; + const duration = performance.now() - jobData.startTime; logger.log("Got job", jobId, "response within", round2Digits(duration), "ms: ", result.length, "bytes"); - const resolver: any = jobData.resolver; + const resolver = jobData.resolver; delete this.currentJobs[jobId]; resolver(result); }); - this.worker.addEventListener("error", (err: any): any => { + this.worker.addEventListener("error", err => { logger.error("Got error from webworker:", err, "aborting all jobs"); - const failureCalls: any = []; - for (const jobId: any in this.currentJobs) { + const failureCalls = []; + for (const jobId in this.currentJobs) { failureCalls.push(this.currentJobs[jobId].errorHandler); } this.currentJobs = {}; - for (let i: any = 0; i < failureCalls.length; ++i) { + for (let i = 0; i < failureCalls.length; ++i) { failureCalls[i](err); } }); @@ -64,7 +64,7 @@ class AsynCompression { /** * Compresses any object */ - compressObjectAsync(obj: any): any { + compressObjectAsync(obj: any) { logger.log("Compressing object async (optimized)"); return this.internalQueueJob("compressObject", { obj, @@ -76,9 +76,9 @@ class AsynCompression { * {} */ internalQueueJob(job: string, data: any): Promise { - const jobId: any = ++this.currentJobId; - return new Promise((resolve: any, reject: any): any => { - const errorHandler: any = (err: any): any => { + const jobId = ++this.currentJobId; + return new Promise((resolve, reject) => { + const errorHandler = err => { logger.error("Failed to compress job", jobId, ":", err); reject(err); }; @@ -92,4 +92,4 @@ class AsynCompression { }); } } -export const asyncCompressor: any = new AsynCompression(); +export const asyncCompressor = new AsynCompression(); diff --git a/src/ts/core/atlas_definitions.ts b/src/ts/core/atlas_definitions.ts index 5f286336..84822a40 100644 --- a/src/ts/core/atlas_definitions.ts +++ b/src/ts/core/atlas_definitions.ts @@ -34,7 +34,7 @@ export class AtlasDefinition { constructor({ frames, meta }) { } - getFullSourcePath(): any { + getFullSourcePath() { return this.sourceFileName; } } @@ -42,6 +42,6 @@ export const atlasFiles: AtlasDefinition[] = require // @ts-ignore .context("../../../res_built/atlas/", false, /.*\.json/i) .keys() - .map((f: any): any => f.replace(/^\.\//gi, "")) - .map((f: any): any => require("../../../res_built/atlas/" + f)) - .map((data: any): any => new AtlasDefinition(data)); + .map(f => f.replace(/^\.\//gi, "")) + .map(f => require("../../../res_built/atlas/" + f)) + .map(data => new AtlasDefinition(data)); diff --git a/src/ts/core/background_resources_loader.ts b/src/ts/core/background_resources_loader.ts index 7a209e47..8eb8d42d 100644 --- a/src/ts/core/background_resources_loader.ts +++ b/src/ts/core/background_resources_loader.ts @@ -10,18 +10,18 @@ import { Loader } from "./loader"; import { createLogger } from "./logging"; import { Signal } from "./signal"; import { clamp, getLogoSprite, timeoutPromise } from "./utils"; -const logger: any = createLogger("background_loader"); -const MAIN_MENU_ASSETS: any = { +const logger = createLogger("background_loader"); +const MAIN_MENU_ASSETS = { sprites: [getLogoSprite()], sounds: [SOUNDS.uiClick, SOUNDS.uiError, SOUNDS.dialogError, SOUNDS.dialogOk], atlas: [], css: [], }; -const INGAME_ASSETS: any = { +const INGAME_ASSETS = { sprites: [], sounds: [ ...Array.from(Object.values(MUSIC)), - ...Array.from(Object.values(SOUNDS)).filter((sound: any): any => !MAIN_MENU_ASSETS.sounds.includes(sound)), + ...Array.from(Object.values(SOUNDS)).filter(sound => !MAIN_MENU_ASSETS.sounds.includes(sound)), ], atlas: atlasFiles, css: ["async-resources.css"], @@ -30,10 +30,10 @@ if (G_IS_STANDALONE) { MAIN_MENU_ASSETS.sounds = [...Array.from(Object.values(MUSIC)), ...Array.from(Object.values(SOUNDS))]; INGAME_ASSETS.sounds = []; } -const LOADER_TIMEOUT_PER_RESOURCE: any = 180000; +const LOADER_TIMEOUT_PER_RESOURCE = 180000; // Cloudflare does not send content-length headers with brotli compression, // so store the actual (compressed) file sizes so we can show a progress bar. -const HARDCODED_FILE_SIZES: any = { +const HARDCODED_FILE_SIZES = { "async-resources.css": 2216145, }; export class BackgroundResourcesLoader { @@ -44,19 +44,19 @@ export class BackgroundResourcesLoader { constructor(app) { } - getMainMenuPromise(): any { + getMainMenuPromise() { if (this.mainMenuPromise) { return this.mainMenuPromise; } logger.log("⏰ Loading main menu assets"); return (this.mainMenuPromise = this.loadAssets(MAIN_MENU_ASSETS)); } - getIngamePromise(): any { + getIngamePromise() { if (this.ingamePromise) { return this.ingamePromise; } logger.log("⏰ Loading ingame assets"); - const promise: any = this.loadAssets(INGAME_ASSETS).then((): any => initSpriteCache()); + const promise = this.loadAssets(INGAME_ASSETS).then(() => initSpriteCache()); return (this.ingamePromise = promise); } async loadAssets({ sprites, sounds, atlas, css }: { @@ -64,50 +64,50 @@ export class BackgroundResourcesLoader { sounds: string[]; atlas: AtlasDefinition[]; css: string[]; - }): any { + }) { let promiseFunctions: ((progressHandler: (progress: number) => void) => Promise)[] = []; // CSS - for (let i: any = 0; i < css.length; ++i) { - promiseFunctions.push((progress: any): any => timeoutPromise(this.internalPreloadCss(css[i], progress), LOADER_TIMEOUT_PER_RESOURCE).catch((err: any): any => { + for (let i = 0; i < css.length; ++i) { + promiseFunctions.push(progress => timeoutPromise(this.internalPreloadCss(css[i], progress), LOADER_TIMEOUT_PER_RESOURCE).catch(err => { logger.error("Failed to load css:", css[i], err); throw new Error("HUD Stylesheet " + css[i] + " failed to load: " + err); })); } // ATLAS FILES - for (let i: any = 0; i < atlas.length; ++i) { - promiseFunctions.push((progress: any): any => timeoutPromise(Loader.preloadAtlas(atlas[i], progress), LOADER_TIMEOUT_PER_RESOURCE).catch((err: any): any => { + for (let i = 0; i < atlas.length; ++i) { + promiseFunctions.push(progress => timeoutPromise(Loader.preloadAtlas(atlas[i], progress), LOADER_TIMEOUT_PER_RESOURCE).catch(err => { logger.error("Failed to load atlas:", atlas[i].sourceFileName, err); throw new Error("Atlas " + atlas[i].sourceFileName + " failed to load: " + err); })); } // HUD Sprites - for (let i: any = 0; i < sprites.length; ++i) { - promiseFunctions.push((progress: any): any => timeoutPromise(Loader.preloadCSSSprite(sprites[i], progress), LOADER_TIMEOUT_PER_RESOURCE).catch((err: any): any => { + for (let i = 0; i < sprites.length; ++i) { + promiseFunctions.push(progress => timeoutPromise(Loader.preloadCSSSprite(sprites[i], progress), LOADER_TIMEOUT_PER_RESOURCE).catch(err => { logger.error("Failed to load css sprite:", sprites[i], err); throw new Error("HUD Sprite " + sprites[i] + " failed to load: " + err); })); } // SFX & Music - for (let i: any = 0; i < sounds.length; ++i) { - promiseFunctions.push((progress: any): any => timeoutPromise(this.app.sound.loadSound(sounds[i]), LOADER_TIMEOUT_PER_RESOURCE).catch((err: any): any => { + for (let i = 0; i < sounds.length; ++i) { + promiseFunctions.push(progress => timeoutPromise(this.app.sound.loadSound(sounds[i]), LOADER_TIMEOUT_PER_RESOURCE).catch(err => { logger.warn("Failed to load sound, will not be available:", sounds[i], err); })); } - const originalAmount: any = promiseFunctions.length; - const start: any = performance.now(); + const originalAmount = promiseFunctions.length; + const start = performance.now(); logger.log("⏰ Preloading", originalAmount, "assets"); - let progress: any = 0; + let progress = 0; this.resourceStateChangedSignal.dispatch({ progress }); - let promises: any = []; - for (let i: any = 0; i < promiseFunctions.length; i++) { - let lastIndividualProgress: any = 0; - const progressHandler: any = (individualProgress: any): any => { - const delta: any = clamp(individualProgress) - lastIndividualProgress; + let promises = []; + for (let i = 0; i < promiseFunctions.length; i++) { + let lastIndividualProgress = 0; + const progressHandler = individualProgress => { + const delta = clamp(individualProgress) - lastIndividualProgress; lastIndividualProgress = clamp(individualProgress); progress += delta / originalAmount; this.resourceStateChangedSignal.dispatch({ progress }); }; - promises.push(promiseFunctions[i](progressHandler).then((): any => { + promises.push(promiseFunctions[i](progressHandler).then(() => { progressHandler(1); })); } @@ -117,28 +117,28 @@ export class BackgroundResourcesLoader { /** * Shows an error when a resource failed to load and allows to reload the game */ - showLoaderError(dialogs: any, err: any): any { + showLoaderError(dialogs, err) { if (G_IS_STANDALONE) { dialogs .showWarning(T.dialogs.resourceLoadFailed.title, T.dialogs.resourceLoadFailed.descSteamDemo + "
" + err, ["retry"]) - .retry.add((): any => window.location.reload()); + .retry.add(() => window.location.reload()); } else { dialogs .showWarning(T.dialogs.resourceLoadFailed.title, T.dialogs.resourceLoadFailed.descWeb.replace("", `${T.dialogs.resourceLoadFailed.demoLinkText}`) + "
" + err, ["retry"]) - .retry.add((): any => window.location.reload()); + .retry.add(() => window.location.reload()); } } - preloadWithProgress(src: any, progressHandler: any): any { - return new Promise((resolve: any, reject: any): any => { - const xhr: any = new XMLHttpRequest(); - let notifiedNotComputable: any = false; - const fullUrl: any = cachebust(src); + preloadWithProgress(src, progressHandler) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + let notifiedNotComputable = false; + const fullUrl = cachebust(src); xhr.open("GET", fullUrl, true); xhr.responseType = "arraybuffer"; - xhr.onprogress = function (ev: any): any { + xhr.onprogress = function (ev) { if (ev.lengthComputable) { progressHandler(ev.loaded / ev.total); } @@ -158,7 +158,7 @@ export class BackgroundResourcesLoader { } } }; - xhr.onloadend = function (): any { + xhr.onloadend = function () { if (!xhr.status.toString().match(/^2/)) { reject(fullUrl + ": " + xhr.status + " " + xhr.statusText); } @@ -166,22 +166,22 @@ export class BackgroundResourcesLoader { if (!notifiedNotComputable) { progressHandler(1); } - const options: any = {}; - const headers: any = xhr.getAllResponseHeaders(); - const contentType: any = headers.match(/^Content-Type:\s*(.*?)$/im); + const options = {}; + const headers = xhr.getAllResponseHeaders(); + const contentType = headers.match(/^Content-Type:\s*(.*?)$/im); if (contentType && contentType[1]) { options.type = contentType[1].split(";")[0]; } - const blob: any = new Blob([this.response], options); + const blob = new Blob([this.response], options); resolve(window.URL.createObjectURL(blob)); } }; xhr.send(); }); } - internalPreloadCss(src: any, progressHandler: any): any { - return this.preloadWithProgress(src, progressHandler).then((blobSrc: any): any => { - var styleElement: any = document.createElement("link"); + internalPreloadCss(src, progressHandler) { + return this.preloadWithProgress(src, progressHandler).then(blobSrc => { + var styleElement = document.createElement("link"); styleElement.href = blobSrc; styleElement.rel = "stylesheet"; styleElement.setAttribute("media", "all"); diff --git a/src/ts/core/buffer_maintainer.ts b/src/ts/core/buffer_maintainer.ts index 76f96654..821f03bc 100644 --- a/src/ts/core/buffer_maintainer.ts +++ b/src/ts/core/buffer_maintainer.ts @@ -8,8 +8,8 @@ export type CacheEntry = { lastUse: number; }; -const logger: any = createLogger("buffers"); -const bufferGcDurationSeconds: any = 0.5; +const logger = createLogger("buffers"); +const bufferGcDurationSeconds = 0.5; export class BufferMaintainer { public root = root; public cache: Map> = new Map(); @@ -22,17 +22,17 @@ export class BufferMaintainer { /** * Returns the buffer stats */ - getStats(): any { - let stats: any = { + getStats() { + let stats = { rootKeys: 0, subKeys: 0, vramBytes: 0, }; - this.cache.forEach((subCache: any, key: any): any => { + this.cache.forEach((subCache, key) => { ++stats.rootKeys; - subCache.forEach((cacheEntry: any, subKey: any): any => { + subCache.forEach((cacheEntry, subKey) => { ++stats.subKeys; - const canvas: any = cacheEntry.canvas; + const canvas = cacheEntry.canvas; stats.vramBytes += canvas.width * canvas.height * 4; }); }); @@ -42,14 +42,14 @@ export class BufferMaintainer { * Goes to the next buffer iteration, clearing all buffers which were not used * for a few iterations */ - garbargeCollect(): any { - let totalKeys: any = 0; - let deletedKeys: any = 0; - const minIteration: any = this.iterationIndex; - this.cache.forEach((subCache: any, key: any): any => { - let unusedSubKeys: any = []; + garbargeCollect() { + let totalKeys = 0; + let deletedKeys = 0; + const minIteration = this.iterationIndex; + this.cache.forEach((subCache, key) => { + let unusedSubKeys = []; // Filter sub cache - subCache.forEach((cacheEntry: any, subKey: any): any => { + subCache.forEach((cacheEntry, subKey) => { if (cacheEntry.lastUse < minIteration || // @ts-ignore cacheEntry.canvas._contextLost) { @@ -62,7 +62,7 @@ export class BufferMaintainer { } }); // Delete unused sub keys - for (let i: any = 0; i < unusedSubKeys.length; ++i) { + for (let i = 0; i < unusedSubKeys.length; ++i) { subCache.delete(unusedSubKeys[i]); } }); @@ -91,8 +91,8 @@ export class BufferMaintainer { // } ++this.iterationIndex; } - update(): any { - const now: any = this.root.time.realtimeNow(); + update() { + const now = this.root.time.realtimeNow(); if (now - this.lastIteration > bufferGcDurationSeconds) { this.lastIteration = now; this.garbargeCollect(); @@ -112,21 +112,21 @@ export class BufferMaintainer { additionalParams: object=; }): HTMLCanvasElement { // First, create parent key - let parent: any = this.cache.get(key); + let parent = this.cache.get(key); if (!parent) { parent = new Map(); this.cache.set(key, parent); } // Now search for sub key - const cacheHit: any = parent.get(subKey); + const cacheHit = parent.get(subKey); if (cacheHit) { cacheHit.lastUse = this.iterationIndex; return cacheHit.canvas; } // Need to generate new buffer - const effectiveWidth: any = w * dpi; - const effectiveHeight: any = h * dpi; - const [canvas, context]: any = makeOffscreenBuffer(effectiveWidth, effectiveHeight, { + const effectiveWidth = w * dpi; + const effectiveHeight = h * dpi; + const [canvas, context] = makeOffscreenBuffer(effectiveWidth, effectiveHeight, { reusable: true, label: "buffer-" + key + "/" + subKey, smooth: true, @@ -147,12 +147,12 @@ export class BufferMaintainer { key: string; subKey: string; }): ?HTMLCanvasElement { - let parent: any = this.cache.get(key); + let parent = this.cache.get(key); if (!parent) { return null; } // Now search for sub key - const cacheHit: any = parent.get(subKey); + const cacheHit = parent.get(subKey); if (cacheHit) { return cacheHit.canvas; } diff --git a/src/ts/core/buffer_utils.ts b/src/ts/core/buffer_utils.ts index 7a47c598..8902a18d 100644 --- a/src/ts/core/buffer_utils.ts +++ b/src/ts/core/buffer_utils.ts @@ -1,11 +1,11 @@ import { globalConfig } from "./config"; import { fastArrayDelete } from "./utils"; import { createLogger } from "./logging"; -const logger: any = createLogger("buffer_utils"); +const logger = createLogger("buffer_utils"); /** * Enables images smoothing on a context */ -export function enableImageSmoothing(context: CanvasRenderingContext2D): any { +export function enableImageSmoothing(context: CanvasRenderingContext2D) { context.imageSmoothingEnabled = true; context.webkitImageSmoothingEnabled = true; // @ts-ignore @@ -14,7 +14,7 @@ export function enableImageSmoothing(context: CanvasRenderingContext2D): any { /** * Disables image smoothing on a context */ -export function disableImageSmoothing(context: CanvasRenderingContext2D): any { +export function disableImageSmoothing(context: CanvasRenderingContext2D) { context.imageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; } @@ -31,14 +31,14 @@ const freeCanvasBuckets: Map> = new Map(); /** * Track statistics */ -const stats: any = { +const stats = { vramUsage: 0, backlogVramUsage: 0, bufferCount: 0, numReused: 0, numCreated: 0, }; -export function getBufferVramUsageBytes(canvas: HTMLCanvasElement): any { +export function getBufferVramUsageBytes(canvas: HTMLCanvasElement) { assert(canvas, "no canvas given"); assert(Number.isFinite(canvas.width), "bad canvas width: " + canvas.width); assert(Number.isFinite(canvas.height), "bad canvas height" + canvas.height); @@ -47,9 +47,9 @@ export function getBufferVramUsageBytes(canvas: HTMLCanvasElement): any { /** * Returns stats on the allocated buffers */ -export function getBufferStats(): any { - let numBuffersFree: any = 0; - freeCanvasBuckets.forEach((bucket: any): any => { +export function getBufferStats() { + let numBuffersFree = 0; + freeCanvasBuckets.forEach(bucket => { numBuffersFree += bucket.length; }); return { @@ -61,10 +61,10 @@ export function getBufferStats(): any { /** * Clears the backlog buffers if they grew too much */ -export function clearBufferBacklog(): any { - freeCanvasBuckets.forEach((bucket: any): any => { +export function clearBufferBacklog() { + freeCanvasBuckets.forEach(bucket => { while (bucket.length > 500) { - const entry: any = bucket[bucket.length - 1]; + const entry = bucket[bucket.length - 1]; stats.backlogVramUsage -= getBufferVramUsageBytes(entry.canvas); delete entry.canvas; delete entry.context; @@ -76,7 +76,7 @@ export function clearBufferBacklog(): any { * Creates a new offscreen buffer * {} */ -export function makeOffscreenBuffer(w: Number, h: Number, { smooth = true, reusable = true, label = "buffer" }: any): [ +export function makeOffscreenBuffer(w: Number, h: Number, { smooth = true, reusable = true, label = "buffer" }): [ HTMLCanvasElement, CanvasRenderingContext2D ] { @@ -89,18 +89,18 @@ export function makeOffscreenBuffer(w: Number, h: Number, { smooth = true, reusa w = Math.max(1, w); h = Math.max(1, h); } - const recommendedSize: any = 1024 * 1024; + const recommendedSize = 1024 * 1024; if (w * h > recommendedSize) { logger.warn("Creating huge buffer:", w, "x", h, "with label", label); } w = Math.floor(w); h = Math.floor(h); - let canvas: any = null; - let context: any = null; + let canvas = null; + let context = null; // Ok, search in cache first - const bucket: any = freeCanvasBuckets.get(w * h) || []; - for (let i: any = 0; i < bucket.length; ++i) { - const { canvas: useableCanvas, context: useableContext }: any = bucket[i]; + const bucket = freeCanvasBuckets.get(w * h) || []; + for (let i = 0; i < bucket.length; ++i) { + const { canvas: useableCanvas, context: useableContext } = bucket[i]; if (useableCanvas.width === w && useableCanvas.height === h) { // Ok we found one canvas = useableCanvas; @@ -126,12 +126,12 @@ export function makeOffscreenBuffer(w: Number, h: Number, { smooth = true, reusa canvas.height = h; // Initial state context.save(); - canvas.addEventListener("webglcontextlost", (): any => { + canvas.addEventListener("webglcontextlost", () => { console.warn("canvas::webglcontextlost", canvas); // @ts-ignore canvas._contextLost = true; }); - canvas.addEventListener("contextlost", (): any => { + canvas.addEventListener("contextlost", () => { console.warn("canvas::contextlost", canvas); // @ts-ignore canvas._contextLost = true; @@ -155,20 +155,20 @@ export function makeOffscreenBuffer(w: Number, h: Number, { smooth = true, reusa /** * Frees a canvas */ -export function registerCanvas(canvas: HTMLCanvasElement, context: any): any { +export function registerCanvas(canvas: HTMLCanvasElement, context) { registeredCanvas.push({ canvas, context }); stats.bufferCount += 1; - const bytesUsed: any = getBufferVramUsageBytes(canvas); + const bytesUsed = getBufferVramUsageBytes(canvas); stats.vramUsage += bytesUsed; } /** * Frees a canvas */ -export function freeCanvas(canvas: HTMLCanvasElement): any { +export function freeCanvas(canvas: HTMLCanvasElement) { assert(canvas, "Canvas is empty"); - let index: any = -1; - let data: any = null; - for (let i: any = 0; i < registeredCanvas.length; ++i) { + let index = -1; + let data = null; + for (let i = 0; i < registeredCanvas.length; ++i) { if (registeredCanvas[i].canvas === canvas) { index = i; data = registeredCanvas[i]; @@ -180,8 +180,8 @@ export function freeCanvas(canvas: HTMLCanvasElement): any { return; } fastArrayDelete(registeredCanvas, index); - const key: any = canvas.width * canvas.height; - const bucket: any = freeCanvasBuckets.get(key); + const key = canvas.width * canvas.height; + const bucket = freeCanvasBuckets.get(key); if (bucket) { bucket.push(data); } @@ -189,7 +189,7 @@ export function freeCanvas(canvas: HTMLCanvasElement): any { freeCanvasBuckets.set(key, [data]); } stats.bufferCount -= 1; - const bytesUsed: any = getBufferVramUsageBytes(canvas); + const bytesUsed = getBufferVramUsageBytes(canvas); stats.vramUsage -= bytesUsed; stats.backlogVramUsage += bytesUsed; } diff --git a/src/ts/core/cachebust.ts b/src/ts/core/cachebust.ts index 5ceabaec..cb7d7f8e 100644 --- a/src/ts/core/cachebust.ts +++ b/src/ts/core/cachebust.ts @@ -1,7 +1,7 @@ /** * Generates a cachebuster string. This only modifies the path in the browser version */ -export function cachebust(path: string): any { +export function cachebust(path: string) { if (G_IS_BROWSER && !G_IS_STANDALONE && !G_IS_DEV) { return "/v/" + G_BUILD_COMMIT_HASH + "/" + path; } diff --git a/src/ts/core/click_detector.ts b/src/ts/core/click_detector.ts index 246dbf6e..a64f98d4 100644 --- a/src/ts/core/click_detector.ts +++ b/src/ts/core/click_detector.ts @@ -5,17 +5,17 @@ import { Vector } from "./vector"; import { IS_MOBILE, SUPPORT_TOUCH } from "./config"; import { SOUNDS } from "../platform/sound"; import { GLOBAL_APP } from "./globals"; -const logger: any = createLogger("click_detector"); -export const MAX_MOVE_DISTANCE_PX: any = IS_MOBILE ? 20 : 80; +const logger = createLogger("click_detector"); +export const MAX_MOVE_DISTANCE_PX = IS_MOBILE ? 20 : 80; // For debugging -const registerClickDetectors: any = G_IS_DEV && true; +const registerClickDetectors = G_IS_DEV && true; if (registerClickDetectors) { window.activeClickDetectors = []; } // Store active click detectors so we can cancel them const ongoingClickDetectors: Array = []; // Store when the last touch event was registered, to avoid accepting a touch *and* a click event -export let clickDetectorGlobals: any = { +export let clickDetectorGlobals = { lastTouchTime: -1000, }; export type ClickDetectorConstructorArgs = { @@ -59,10 +59,10 @@ export class ClickDetector { /** * Cleans up all event listeners of this detector */ - cleanup(): any { + cleanup() { if (this.element) { if (registerClickDetectors) { - const index: any = window.activeClickDetectors.indexOf(this); + const index = window.activeClickDetectors.indexOf(this); if (index < 0) { logger.error("Click detector cleanup but is not active"); } @@ -70,7 +70,7 @@ export class ClickDetector { window.activeClickDetectors.splice(index, 1); } } - const options: any = this.internalGetEventListenerOptions(); + const options = this.internalGetEventListenerOptions(); if (SUPPORT_TOUCH) { this.element.removeEventListener("touchstart", this.handlerTouchStart, options); this.element.removeEventListener("touchend", this.handlerTouchEnd, options); @@ -97,14 +97,14 @@ export class ClickDetector { } } // INTERNAL METHODS - internalPreventClick(event: Event): any { + internalPreventClick(event: Event) { window.focus(); event.preventDefault(); } /** * Internal method to get the options to pass to an event listener */ - internalGetEventListenerOptions(): any { + internalGetEventListenerOptions() { return { capture: this.consumeEvents, passive: !this.preventDefault, @@ -113,8 +113,8 @@ export class ClickDetector { /** * Binds the click detector to an element */ - internalBindTo(element: HTMLElement): any { - const options: any = this.internalGetEventListenerOptions(); + internalBindTo(element: HTMLElement) { + const options = this.internalGetEventListenerOptions(); this.handlerTouchStart = this.internalOnPointerDown.bind(this); this.handlerTouchEnd = this.internalOnPointerEnd.bind(this); this.handlerTouchMove = this.internalOnPointerMove.bind(this); @@ -145,13 +145,13 @@ export class ClickDetector { /** * Returns if the bound element is currently in the DOM. */ - internalIsDomElementAttached(): any { + internalIsDomElementAttached() { return this.element && document.documentElement.contains(this.element); } /** * Checks if the given event is relevant for this detector */ - internalEventPreHandler(event: TouchEvent | MouseEvent, expectedRemainingTouches: any = 1): any { + internalEventPreHandler(event: TouchEvent | MouseEvent, expectedRemainingTouches = 1) { if (!this.element) { // Already cleaned up return false; @@ -191,7 +191,7 @@ export class ClickDetector { logger.warn("Got unexpected target touches:", event.targetTouches.length, "->", event.targetTouches); return new Vector(0, 0); } - const touch: any = event.changedTouches[0]; + const touch = event.changedTouches[0]; return new Vector(touch.clientX, touch.clientY); } if (event instanceof MouseEvent) { @@ -203,7 +203,7 @@ export class ClickDetector { /** * Cacnels all ongoing events on this detector */ - cancelOngoingEvents(): any { + cancelOngoingEvents() { if (this.applyCssClass && this.element) { this.element.classList.remove(this.applyCssClass); } @@ -215,15 +215,15 @@ export class ClickDetector { /** * Internal pointer down handler */ - internalOnPointerDown(event: TouchEvent | MouseEvent): any { + internalOnPointerDown(event: TouchEvent | MouseEvent) { window.focus(); if (!this.internalEventPreHandler(event, 1)) { return false; } - const position: any = (this.constructor as typeof ClickDetector).extractPointerPosition(event); + const position = this.constructor as typeof ClickDetector).extractPointerPosition(event); if (event instanceof MouseEvent) { - const isRightClick: any = event.button === 2; + const isRightClick = event.button === 2; if (isRightClick) { // Ignore right clicks this.rightClick.dispatch(position, event); @@ -262,20 +262,20 @@ export class ClickDetector { /** * Internal pointer move handler */ - internalOnPointerMove(event: TouchEvent | MouseEvent): any { + internalOnPointerMove(event: TouchEvent | MouseEvent) { if (!this.internalEventPreHandler(event, 1)) { return false; } this.touchmove.dispatch(event); - const pos: any = (this.constructor as typeof ClickDetector).extractPointerPosition(event); + const pos = this.constructor as typeof ClickDetector).extractPointerPosition(event); this.touchmoveSimple.dispatch(pos.x, pos.y); return false; } /** * Internal pointer end handler */ - internalOnPointerEnd(event: TouchEvent | MouseEvent): any { + internalOnPointerEnd(event: TouchEvent | MouseEvent) { window.focus(); if (!this.internalEventPreHandler(event, 0)) { return false; @@ -285,25 +285,25 @@ export class ClickDetector { return false; } if (event instanceof MouseEvent) { - const isRightClick: any = event.button === 2; + const isRightClick = event.button === 2; if (isRightClick) { return; } } - const index: any = ongoingClickDetectors.indexOf(this); + const index = ongoingClickDetectors.indexOf(this); if (index < 0) { logger.warn("Got pointer end but click detector is not in pressed state"); } else { fastArrayDelete(ongoingClickDetectors, index); } - let dispatchClick: any = false; - let dispatchClickPos: any = null; + let dispatchClick = false; + let dispatchClickPos = null; // Check for correct down position, otherwise must have pinched or so if (this.clickDownPosition) { - const pos: any = (this.constructor as typeof ClickDetector).extractPointerPosition(event); - const distance: any = pos.distance(this.clickDownPosition); + const pos = this.constructor as typeof ClickDetector).extractPointerPosition(event); + const distance = pos.distance(this.clickDownPosition); if (!IS_MOBILE || distance <= this.maxDistance) { dispatchClick = true; dispatchClickPos = pos; @@ -323,8 +323,8 @@ export class ClickDetector { this.touchend.dispatch(event); this.touchendSimple.dispatch(); if (dispatchClick) { - const detectors: any = ongoingClickDetectors.slice(); - for (let i: any = 0; i < detectors.length; ++i) { + const detectors = ongoingClickDetectors.slice(); + for (let i = 0; i < detectors.length; ++i) { detectors[i].cancelOngoingEvents(); } this.click.dispatch(dispatchClickPos, event); @@ -335,7 +335,7 @@ export class ClickDetector { /** * Internal touch cancel handler */ - internalOnTouchCancel(event: TouchEvent | MouseEvent): any { + internalOnTouchCancel(event: TouchEvent | MouseEvent) { if (!this.internalEventPreHandler(event, 0)) { return false; } diff --git a/src/ts/core/config.ts b/src/ts/core/config.ts index d4476068..a7ab9099 100644 --- a/src/ts/core/config.ts +++ b/src/ts/core/config.ts @@ -1,14 +1,14 @@ /* typehints:start */ import type { Application } from "../application"; /* typehints:end */ -export const IS_DEBUG: any = G_IS_DEV && +export const IS_DEBUG = G_IS_DEV && typeof window !== "undefined" && window.location.port === "3005" && (window.location.host.indexOf("localhost:") >= 0 || window.location.host.indexOf("192.168.0.") >= 0) && window.location.search.indexOf("nodebug") < 0; -export const SUPPORT_TOUCH: any = false; -const smoothCanvas: any = true; -export const THIRDPARTY_URLS: any = { +export const SUPPORT_TOUCH = false; +const smoothCanvas = true; +export const THIRDPARTY_URLS = { discord: "https://discord.gg/HN7EVzV", github: "https://github.com/tobspr-games/shapez.io", reddit: "https://www.reddit.com/r/shapezio", @@ -25,13 +25,13 @@ export const THIRDPARTY_URLS: any = { }, modBrowser: "https://shapez.mod.io/", }; -export function openStandaloneLink(app: Application, campaign: string): any { - const discount: any = globalConfig.currentDiscount > 0 ? "_discount" + globalConfig.currentDiscount : ""; - const event: any = campaign + discount; +export function openStandaloneLink(app: Application, campaign: string) { + const discount = globalConfig.currentDiscount > 0 ? "_discount" + globalConfig.currentDiscount : ""; + const event = campaign + discount; app.platformWrapper.openExternalLink(THIRDPARTY_URLS.standaloneCampaignLink.replace("$campaign", event)); app.gameAnalytics.noteMinor("g.stdlink." + event); } -export const globalConfig: any = { +export const globalConfig = { // Size of a single tile in Pixels. // NOTICE: Update webpack.production.config too! tileSize: 32, @@ -106,7 +106,7 @@ export const globalConfig: any = { analyticsApiKey: "baf6a50f0cc7dfdec5a0e21c88a1c69a4b34bc4a", }, }; -export const IS_MOBILE: any = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); +export const IS_MOBILE = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); // Automatic calculations globalConfig.minerSpeedItemsPerSecond = globalConfig.beltSpeedItemsPerSecond / 5; globalConfig.mapChunkWorldSize = globalConfig.mapChunkSize * globalConfig.tileSize; diff --git a/src/ts/core/dpi_manager.ts b/src/ts/core/dpi_manager.ts index bd5c627b..fd4d1fc5 100644 --- a/src/ts/core/dpi_manager.ts +++ b/src/ts/core/dpi_manager.ts @@ -33,8 +33,8 @@ export function smoothenDpi(dpi: number): number { /** * Prepares a context for hihg dpi rendering */ -export function prepareHighDPIContext(context: CanvasRenderingContext2D, smooth: any = true): any { - const dpi: any = getDeviceDPI(); +export function prepareHighDPIContext(context: CanvasRenderingContext2D, smooth = true) { + const dpi = getDeviceDPI(); context.scale(dpi, dpi); if (smooth) { context.imageSmoothingEnabled = true; @@ -50,12 +50,12 @@ export function prepareHighDPIContext(context: CanvasRenderingContext2D, smooth: /** * Resizes a high dpi canvas */ -export function resizeHighDPICanvas(canvas: HTMLCanvasElement, w: number, h: number, smooth: any = true): any { - const dpi: any = getDeviceDPI(); - const wNumber: any = Math.floor(w); - const hNumber: any = Math.floor(h); - const targetW: any = Math.floor(wNumber * dpi); - const targetH: any = Math.floor(hNumber * dpi); +export function resizeHighDPICanvas(canvas: HTMLCanvasElement, w: number, h: number, smooth = true) { + const dpi = getDeviceDPI(); + const wNumber = Math.floor(w); + const hNumber = Math.floor(h); + const targetW = Math.floor(wNumber * dpi); + const targetH = Math.floor(hNumber * dpi); if (targetW !== canvas.width || targetH !== canvas.height) { // console.log("Resize Canvas from", canvas.width, canvas.height, "to", targetW, targetH) canvas.width = targetW; @@ -68,9 +68,9 @@ export function resizeHighDPICanvas(canvas: HTMLCanvasElement, w: number, h: num /** * Resizes a canvas */ -export function resizeCanvas(canvas: HTMLCanvasElement, w: number, h: number, setStyle: any = true): any { - const actualW: any = Math.ceil(w); - const actualH: any = Math.ceil(h); +export function resizeCanvas(canvas: HTMLCanvasElement, w: number, h: number, setStyle = true) { + const actualW = Math.ceil(w); + const actualH = Math.ceil(h); if (actualW !== canvas.width || actualH !== canvas.height) { canvas.width = actualW; canvas.height = actualH; @@ -84,9 +84,9 @@ export function resizeCanvas(canvas: HTMLCanvasElement, w: number, h: number, se /** * Resizes a canvas and makes sure its cleared */ -export function resizeCanvasAndClear(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number): any { - const actualW: any = Math.ceil(w); - const actualH: any = Math.ceil(h); +export function resizeCanvasAndClear(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number) { + const actualW = Math.ceil(w); + const actualH = Math.ceil(h); if (actualW !== canvas.width || actualH !== canvas.height) { canvas.width = actualW; canvas.height = actualH; diff --git a/src/ts/core/draw_utils.ts b/src/ts/core/draw_utils.ts index 8d16d439..16bd6f3f 100644 --- a/src/ts/core/draw_utils.ts +++ b/src/ts/core/draw_utils.ts @@ -4,9 +4,9 @@ export type DrawParameters = import("./draw_parameters").DrawParameters; import { globalConfig } from "./config"; import { createLogger } from "./logging"; import { Rectangle } from "./rectangle"; -const logger: any = createLogger("draw_utils"); -export function initDrawUtils(): any { - CanvasRenderingContext2D.prototype.beginRoundedRect = function (x: any, y: any, w: any, h: any, r: any): any { +const logger = createLogger("draw_utils"); +export function initDrawUtils() { + CanvasRenderingContext2D.prototype.beginRoundedRect = function (x, y, w, h, r) { this.beginPath(); if (r < 0.05) { this.rect(x, y, w, h); @@ -24,7 +24,7 @@ export function initDrawUtils(): any { this.arcTo(x, y + h, x, y, r); this.arcTo(x, y, x + w, y, r); }; - CanvasRenderingContext2D.prototype.beginCircle = function (x: any, y: any, r: any): any { + CanvasRenderingContext2D.prototype.beginCircle = function (x, y, r) { this.beginPath(); if (r < 0.05) { this.rect(x, y, 1, 1); @@ -42,7 +42,7 @@ export function drawRotatedSprite({ parameters, sprite, x, y, angle, size, offse size: number; offsetX: number=; offsetY: number=; -}): any { +}) { if (angle === 0) { sprite.drawCachedCentered(parameters, x + offsetX, y + offsetY, size); return; @@ -53,7 +53,7 @@ export function drawRotatedSprite({ parameters, sprite, x, y, angle, size, offse parameters.context.rotate(-angle); parameters.context.translate(-x, -y); } -let warningsShown: any = 0; +let warningsShown = 0; /** * Draws a sprite with clipping */ @@ -66,9 +66,9 @@ export function drawSpriteClipped({ parameters, sprite, x, y, w, h, originalW, o h: number; originalW: number; originalH: number; -}): any { - const rect: any = new Rectangle(x, y, w, h); - const intersection: any = rect.getIntersection(parameters.visibleRect); +}) { + const rect = new Rectangle(x, y, w, h); + const intersection = rect.getIntersection(parameters.visibleRect); if (!intersection) { // Clipped if (++warningsShown % 200 === 1) { diff --git a/src/ts/core/explained_result.ts b/src/ts/core/explained_result.ts index 415fff3d..b5d68fef 100644 --- a/src/ts/core/explained_result.ts +++ b/src/ts/core/explained_result.ts @@ -4,25 +4,25 @@ export class ExplainedResult { constructor(result = true, reason = null, additionalProps = {}) { // Copy additional props - for (const key: any in additionalProps) { + for (const key in additionalProps) { this[key] = additionalProps[key]; } } - isGood(): any { + isGood() { return !!this.result; } - isBad(): any { + isBad() { return !this.result; } - static good(): any { + static good() { return new ExplainedResult(true); } - static bad(reason: any, additionalProps: any): any { + static bad(reason, additionalProps) { return new ExplainedResult(false, reason, additionalProps); } - static requireAll(...args: any): any { - for (let i: any = 0; i < args.length; ++i) { - const subResult: any = args[i].call(); + static requireAll(...args) { + for (let i = 0; i < args.length; ++i) { + const subResult = args[i].call(); if (!subResult.isGood()) { return subResult; } diff --git a/src/ts/core/factory.ts b/src/ts/core/factory.ts index b144bb5b..cdb34713 100644 --- a/src/ts/core/factory.ts +++ b/src/ts/core/factory.ts @@ -1,5 +1,5 @@ import { createLogger } from "./logging"; -const logger: any = createLogger("factory"); +const logger = createLogger("factory"); // simple factory pattern export class Factory { public id = id; @@ -9,12 +9,12 @@ export class Factory { constructor(id) { } - getId(): any { + getId() { return this.id; } - register(entry: any): any { + register(entry) { // Extract id - const id: any = entry.getId(); + const id = entry.getId(); assert(id, "Factory: Invalid id for class: " + entry); // Check duplicates assert(!this.idToEntry[id], "Duplicate factory entry for " + id); @@ -35,7 +35,7 @@ export class Factory { * {} */ findById(id: string): object { - const entry: any = this.idToEntry[id]; + const entry = this.idToEntry[id]; if (!entry) { logger.error("Object with id", id, "is not registered on factory", this.id, "!"); assert(false, "Factory: Object with id '" + id + "' is not registered!"); diff --git a/src/ts/core/game_state.ts b/src/ts/core/game_state.ts index 912cd10d..b5698290 100644 --- a/src/ts/core/game_state.ts +++ b/src/ts/core/game_state.ts @@ -9,7 +9,7 @@ import { InputReceiver } from "./input_receiver"; import { waitNextFrame } from "./utils"; import { RequestChannel } from "./request_channel"; import { MUSIC } from "../platform/sound"; -const logger: any = createLogger("game_state"); +const logger = createLogger("game_state"); /** * Basic state of the game state machine. This is the base of the whole game */ @@ -46,7 +46,7 @@ export class GameState { /** * Transfers to a new state */ - moveToState(stateKey: string, payload: any = {}, skipFadeOut: any = false): any { + moveToState(stateKey: string, payload = {}, skipFadeOut = false) { if (this.fadingOut) { logger.warn("Skipping move to '" + stateKey + "' since already fading out"); return; @@ -54,13 +54,13 @@ export class GameState { // Clean up event listeners this.internalCleanUpClickDetectors(); // Fading - const fadeTime: any = this.internalGetFadeInOutTime(); - const doFade: any = !skipFadeOut && this.getHasFadeOut() && fadeTime !== 0; + const fadeTime = this.internalGetFadeInOutTime(); + const doFade = !skipFadeOut && this.getHasFadeOut() && fadeTime !== 0; logger.log("Moving to", stateKey, "(fading=", doFade, ")"); if (doFade) { this.htmlElement.classList.remove("arrived"); this.fadingOut = true; - setTimeout((): any => { + setTimeout(() => { this.stateManager.moveToState(stateKey, payload); }, fadeTime); } @@ -72,8 +72,8 @@ export class GameState { * Tracks clicks on a given element and calls the given callback *on this state*. * If you want to call another function wrap it inside a lambda. */ - trackClicks(element: Element, handler: function():void, args: import("./click_detector").ClickDetectorConstructorArgs= = {}): any { - const detector: any = new ClickDetector(element, args); + trackClicks(element: Element, handler: function():void, args: import("./click_detector").ClickDetectorConstructorArgs= = {}) { + const detector = new ClickDetector(element, args); detector.click.add(handler, this); if (G_IS_DEV) { // Append a source so we can check where the click detector is from @@ -85,43 +85,43 @@ export class GameState { /** * Cancels all promises on the api as well as our async channel */ - cancelAllAsyncOperations(): any { + cancelAllAsyncOperations() { this.asyncChannel.cancelAll(); } //// CALLBACKS //// /** * Callback when entering the state, to be overriddemn */ - onEnter(payload: any): any { } + onEnter(payload: any) { } /** * Callback when leaving the state */ - onLeave(): any { } + onLeave() { } /** * Callback when the app got paused (on android, this means in background) */ - onAppPause(): any { } + onAppPause() { } /** * Callback when the app got resumed (on android, this means in foreground again) */ - onAppResume(): any { } + onAppResume() { } /** * Render callback */ - onRender(dt: number): any { } + onRender(dt: number) { } /** * Background tick callback, called while the game is inactiev */ - onBackgroundTick(dt: number): any { } + onBackgroundTick(dt: number) { } /** * Called when the screen resized */ - onResized(w: number, h: number): any { } + onResized(w: number, h: number) { } /** * Internal backbutton handler, called when the hardware back button is pressed or * the escape key is pressed */ - onBackButton(): any { } + onBackButton() { } //// INTERFACE //// /** * Should return how many mulliseconds to fade in / out the state. Not recommended to override! @@ -169,7 +169,7 @@ export class GameState { * Returns if the state has an unload confirmation, this is the * "Are you sure you want to leave the page" message. */ - getHasUnloadConfirmation(): any { + getHasUnloadConfirmation() { return false; } /** @@ -198,7 +198,7 @@ export class GameState { /** * Internal callback from the manager. Do not override! */ - internalRegisterCallback(stateManager: StateManager, app: any): any { + internalRegisterCallback(stateManager: StateManager, app) { assert(stateManager, "No state manager"); assert(app, "No app"); this.stateManager = stateManager; @@ -207,13 +207,13 @@ export class GameState { /** * Internal callback when entering the state. Do not override! */ - internalEnterCallback(payload: any, callCallback: boolean = true): any { + internalEnterCallback(payload: any, callCallback: boolean = true) { logSection(this.key, "#26a69a"); this.app.inputMgr.pushReciever(this.inputReciever); this.htmlElement = this.getDivElement(); this.htmlElement.classList.add("active"); // Apply classes in the next frame so the css transition keeps up - waitNextFrame().then((): any => { + waitNextFrame().then(() => { if (this.htmlElement) { this.htmlElement.classList.remove("fadingOut"); this.htmlElement.classList.remove("fadingIn"); @@ -227,7 +227,7 @@ export class GameState { /** * Internal callback when the state is left. Do not override! */ - internalLeaveCallback(): any { + internalLeaveCallback() { this.onLeave(); this.htmlElement.classList.remove("active"); this.app.inputMgr.popReciever(this.inputReciever); @@ -237,21 +237,21 @@ export class GameState { /** * Internal app pause callback */ - internalOnAppPauseCallback(): any { + internalOnAppPauseCallback() { this.onAppPause(); } /** * Internal app resume callback */ - internalOnAppResumeCallback(): any { + internalOnAppResumeCallback() { this.onAppResume(); } /** * Cleans up all click detectors */ - internalCleanUpClickDetectors(): any { + internalCleanUpClickDetectors() { if (this.clickDetectors) { - for (let i: any = 0; i < this.clickDetectors.length; ++i) { + for (let i = 0; i < this.clickDetectors.length; ++i) { this.clickDetectors[i].cleanup(); } this.clickDetectors = []; diff --git a/src/ts/core/global_registries.ts b/src/ts/core/global_registries.ts index e8b59b0e..72612406 100644 --- a/src/ts/core/global_registries.ts +++ b/src/ts/core/global_registries.ts @@ -17,6 +17,6 @@ export let gItemRegistry: FactoryTemplate = new Factory("item"); // Helpers export function initBuildingsByCategory(buildings: { [idx: string]: Array>; -}): any { +}) { gBuildingsByCategory = buildings; } diff --git a/src/ts/core/globals.ts b/src/ts/core/globals.ts index a1144998..923515c5 100644 --- a/src/ts/core/globals.ts +++ b/src/ts/core/globals.ts @@ -6,11 +6,11 @@ import type { Application } from "../application"; * It would be nicer to have no globals, but this is the only one. I promise! */ export let GLOBAL_APP: Application = null; -export function setGlobalApp(app: Application): any { +export function setGlobalApp(app: Application) { assert(!GLOBAL_APP, "Create application twice!"); GLOBAL_APP = app; } -export const BUILD_OPTIONS: any = { +export const BUILD_OPTIONS = { HAVE_ASSERT: G_HAVE_ASSERT, APP_ENVIRONMENT: G_APP_ENVIRONMENT, IS_DEV: G_IS_DEV, diff --git a/src/ts/core/input_distributor.ts b/src/ts/core/input_distributor.ts index d25b2f78..e3f0c2e6 100644 --- a/src/ts/core/input_distributor.ts +++ b/src/ts/core/input_distributor.ts @@ -5,7 +5,7 @@ import type { InputReceiver } from "./input_receiver"; import { Signal, STOP_PROPAGATION } from "./signal"; import { createLogger } from "./logging"; import { arrayDeleteValue, fastArrayDeleteValue } from "./utils"; -const logger: any = createLogger("input_distributor"); +const logger = createLogger("input_distributor"); export class InputDistributor { public app = app; public recieverStack: Array = []; @@ -18,16 +18,16 @@ export class InputDistributor { /** * Attaches a new filter which can filter and reject events */ - installFilter(filter: function(: boolean):boolean): any { + installFilter(filter: function(: boolean):boolean) { this.filters.push(filter); } /** * Removes an attached filter */ - dismountFilter(filter: function(: boolean):boolean): any { + dismountFilter(filter: function(: boolean):boolean) { fastArrayDeleteValue(this.filters, filter); } - pushReciever(reciever: InputReceiver): any { + pushReciever(reciever: InputReceiver) { if (this.isRecieverAttached(reciever)) { assert(false, "Can not add reciever " + reciever.context + " twice"); logger.error("Can not add reciever", reciever.context, "twice"); @@ -35,48 +35,48 @@ export class InputDistributor { } this.recieverStack.push(reciever); if (this.recieverStack.length > 10) { - logger.error("Reciever stack is huge, probably some dead receivers arround:", this.recieverStack.map((x: any): any => x.context)); + logger.error("Reciever stack is huge, probably some dead receivers arround:", this.recieverStack.map(x => x.context)); } } - popReciever(reciever: InputReceiver): any { + popReciever(reciever: InputReceiver) { if (this.recieverStack.indexOf(reciever) < 0) { assert(false, "Can not pop reciever " + reciever.context + " since its not contained"); logger.error("Can not pop reciever", reciever.context, "since its not contained"); return; } if (this.recieverStack[this.recieverStack.length - 1] !== reciever) { - logger.warn("Popping reciever", reciever.context, "which is not on top of the stack. Stack is: ", this.recieverStack.map((x: any): any => x.context)); + logger.warn("Popping reciever", reciever.context, "which is not on top of the stack. Stack is: ", this.recieverStack.map(x => x.context)); } arrayDeleteValue(this.recieverStack, reciever); } - isRecieverAttached(reciever: InputReceiver): any { + isRecieverAttached(reciever: InputReceiver) { return this.recieverStack.indexOf(reciever) >= 0; } - isRecieverOnTop(reciever: InputReceiver): any { + isRecieverOnTop(reciever: InputReceiver) { return (this.isRecieverAttached(reciever) && this.recieverStack[this.recieverStack.length - 1] === reciever); } - makeSureAttachedAndOnTop(reciever: InputReceiver): any { + makeSureAttachedAndOnTop(reciever: InputReceiver) { this.makeSureDetached(reciever); this.pushReciever(reciever); } - makeSureDetached(reciever: InputReceiver): any { + makeSureDetached(reciever: InputReceiver) { if (this.isRecieverAttached(reciever)) { arrayDeleteValue(this.recieverStack, reciever); } } - destroyReceiver(reciever: InputReceiver): any { + destroyReceiver(reciever: InputReceiver) { this.makeSureDetached(reciever); reciever.cleanup(); } // Internal - getTopReciever(): any { + getTopReciever() { if (this.recieverStack.length > 0) { return this.recieverStack[this.recieverStack.length - 1]; } return null; } - bindToEvents(): any { + bindToEvents() { window.addEventListener("popstate", this.handleBackButton.bind(this), false); document.addEventListener("backbutton", this.handleBackButton.bind(this), false); window.addEventListener("keydown", this.handleKeyMouseDown.bind(this)); @@ -86,23 +86,23 @@ export class InputDistributor { window.addEventListener("blur", this.handleBlur.bind(this)); document.addEventListener("paste", this.handlePaste.bind(this)); } - forwardToReceiver(eventId: any, payload: any = null): any { + forwardToReceiver(eventId, payload = null) { // Check filters - for (let i: any = 0; i < this.filters.length; ++i) { + for (let i = 0; i < this.filters.length; ++i) { if (!this.filters[i](eventId)) { return STOP_PROPAGATION; } } - const reciever: any = this.getTopReciever(); + const reciever = this.getTopReciever(); if (!reciever) { logger.warn("Dismissing event because not reciever was found:", eventId); return; } - const signal: any = reciever[eventId]; + const signal = reciever[eventId]; assert(signal instanceof Signal, "Not a valid event id"); return signal.dispatch(payload); } - handleBackButton(event: Event): any { + handleBackButton(event: Event) { event.preventDefault(); event.stopPropagation(); this.forwardToReceiver("backButton"); @@ -110,16 +110,16 @@ export class InputDistributor { /** * Handles when the page got blurred */ - handleBlur(): any { + handleBlur() { this.forwardToReceiver("pageBlur", {}); this.keysDown.clear(); } - handlePaste(ev: any): any { + handlePaste(ev) { this.forwardToReceiver("paste", ev); } - handleKeyMouseDown(event: KeyboardEvent | MouseEvent): any { - const keyCode: any = event instanceof MouseEvent ? event.button + 1 : event.keyCode; + handleKeyMouseDown(event: KeyboardEvent | MouseEvent) { + const keyCode = event instanceof MouseEvent ? event.button + 1 : event.keyCode; if (keyCode === 4 || // MB4 keyCode === 5 || // MB5 keyCode === 9 || // TAB @@ -130,7 +130,7 @@ export class InputDistributor { ) { event.preventDefault(); } - const isInitial: any = !this.keysDown.has(keyCode); + const isInitial = !this.keysDown.has(keyCode); this.keysDown.add(keyCode); if (this.forwardToReceiver("keydown", { keyCode: keyCode, @@ -149,8 +149,8 @@ export class InputDistributor { return this.forwardToReceiver("backButton"); } } - handleKeyMouseUp(event: KeyboardEvent | MouseEvent): any { - const keyCode: any = event instanceof MouseEvent ? event.button + 1 : event.keyCode; + handleKeyMouseUp(event: KeyboardEvent | MouseEvent) { + const keyCode = event instanceof MouseEvent ? event.button + 1 : event.keyCode; this.keysDown.delete(keyCode); this.forwardToReceiver("keyup", { keyCode: keyCode, diff --git a/src/ts/core/input_receiver.ts b/src/ts/core/input_receiver.ts index 7c28eb25..23b3ce89 100644 --- a/src/ts/core/input_receiver.ts +++ b/src/ts/core/input_receiver.ts @@ -10,7 +10,7 @@ export class InputReceiver { constructor(context = "unknown") { } - cleanup(): any { + cleanup() { this.backButton.removeAll(); this.keydown.removeAll(); this.keyup.removeAll(); diff --git a/src/ts/core/loader.ts b/src/ts/core/loader.ts index 1e4dee9f..040e1696 100644 --- a/src/ts/core/loader.ts +++ b/src/ts/core/loader.ts @@ -5,8 +5,8 @@ import { createLogger } from "./logging"; export type Application = import("../application").Application; export type AtlasDefinition = import("./atlas_definitions").AtlasDefinition; -const logger: any = createLogger("loader"); -const missingSpriteIds: any = {}; +const logger = createLogger("loader"); +const missingSpriteIds = {}; class LoaderImpl { public app = null; public sprites: Map = new Map(); @@ -14,7 +14,7 @@ class LoaderImpl { constructor() { } - linkAppAfterBoot(app: Application): any { + linkAppAfterBoot(app: Application) { this.app = app; this.makeSpriteNotFoundCanvas(); } @@ -23,7 +23,7 @@ class LoaderImpl { * {} */ getSpriteInternal(key: string): BaseSprite { - const sprite: any = this.sprites.get(key); + const sprite = this.sprites.get(key); if (!sprite) { if (!missingSpriteIds[key]) { // Only show error once @@ -39,7 +39,7 @@ class LoaderImpl { * {} */ getSprite(key: string): AtlasSprite { - const sprite: any = this.getSpriteInternal(key); + const sprite = this.getSpriteInternal(key); assert(sprite instanceof AtlasSprite || sprite === this.spriteNotFoundSprite, "Not an atlas sprite"); return sprite as AtlasSprite); } @@ -48,7 +48,7 @@ class LoaderImpl { * {} */ getRegularSprite(key: string): RegularSprite { - const sprite: any = this.getSpriteInternal(key); + const sprite = this.getSpriteInternal(key); assert(sprite instanceof RegularSprite || sprite === this.spriteNotFoundSprite, "Not a regular sprite"); return sprite as RegularSprite); } @@ -58,14 +58,14 @@ class LoaderImpl { */ internalPreloadImage(key: string, progressHandler: (progress: number) => void): Promise { return this.app.backgroundResourceLoader - .preloadWithProgress("res/" + key, (progress: any): any => { + .preloadWithProgress("res/" + key, progress => { progressHandler(progress); }) - .then((url: any): any => { - return new Promise((resolve: any, reject: any): any => { - const image: any = new Image(); - image.addEventListener("load", (): any => resolve(image)); - image.addEventListener("error", (err: any): any => reject("Failed to load sprite " + key + ": " + err)); + .then(url => { + return new Promise((resolve, reject) => { + const image = new Image(); + image.addEventListener("load", () => resolve(image)); + image.addEventListener("error", err => reject("Failed to load sprite " + key + ": " + err)); image.src = url; }); }); @@ -75,7 +75,7 @@ class LoaderImpl { * {} */ preloadCSSSprite(key: string, progressHandler: (progress: number) => void): Promise { - return this.internalPreloadImage(key, progressHandler).then((image: any): any => { + return this.internalPreloadImage(key, progressHandler).then(image => { if (key.indexOf("game_misc") >= 0) { // Allow access to regular sprites this.sprites.set(key, new RegularSprite(image, image.width, image.height)); @@ -88,17 +88,17 @@ class LoaderImpl { * {} */ preloadAtlas(atlas: AtlasDefinition, progressHandler: (progress: number) => void): Promise { - return this.internalPreloadImage(atlas.getFullSourcePath(), progressHandler).then((image: any): any => { + return this.internalPreloadImage(atlas.getFullSourcePath(), progressHandler).then(image => { // @ts-ignore image.label = atlas.sourceFileName; return this.internalParseAtlas(atlas, image); }); } - internalParseAtlas({ meta: { scale }, sourceData }: AtlasDefinition, loadedImage: HTMLImageElement): any { + internalParseAtlas({ meta: { scale }, sourceData }: AtlasDefinition, loadedImage: HTMLImageElement) { this.rawImages.push(loadedImage); - for (const spriteName: any in sourceData) { - const { frame, sourceSize, spriteSourceSize }: any = sourceData[spriteName]; - let sprite: any = (this.sprites.get(spriteName) as AtlasSprite); + for (const spriteName in sourceData) { + const { frame, sourceSize, spriteSourceSize } = sourceData[spriteName]; + let sprite = this.sprites.get(spriteName) as AtlasSprite); if (!sprite) { sprite = new AtlasSprite(spriteName); this.sprites.set(spriteName, sprite); @@ -106,7 +106,7 @@ class LoaderImpl { if (sprite.frozen) { continue; } - const link: any = new SpriteAtlasLink({ + const link = new SpriteAtlasLink({ packedX: frame.x, packedY: frame.y, packedW: frame.w, @@ -123,9 +123,9 @@ class LoaderImpl { /** * Makes the canvas which shows the question mark, shown when a sprite was not found */ - makeSpriteNotFoundCanvas(): any { - const dims: any = 128; - const [canvas, context]: any = makeOffscreenBuffer(dims, dims, { + makeSpriteNotFoundCanvas() { + const dims = 128; + const [canvas, context] = makeOffscreenBuffer(dims, dims, { smooth: false, label: "not-found-sprite", }); @@ -139,8 +139,8 @@ class LoaderImpl { // TODO: Not sure why this is set here // @ts-ignore canvas.src = "not-found"; - const sprite: any = new AtlasSprite("not-found"); - ["0.1", "0.25", "0.5", "0.75", "1"].forEach((resolution: any): any => { + const sprite = new AtlasSprite("not-found"); + ["0.1", "0.25", "0.5", "0.75", "1"].forEach(resolution => { sprite.linksByResolution[resolution] = new SpriteAtlasLink({ packedX: 0, packedY: 0, @@ -156,4 +156,4 @@ class LoaderImpl { this.spriteNotFoundSprite = sprite; } } -export const Loader: any = new LoaderImpl(); +export const Loader = new LoaderImpl(); diff --git a/src/ts/core/logging.ts b/src/ts/core/logging.ts index f9f5d144..3cff42d2 100644 --- a/src/ts/core/logging.ts +++ b/src/ts/core/logging.ts @@ -1,5 +1,5 @@ import { globalConfig } from "./config"; -const circularJson: any = require("circular-json"); +const circularJson = require("circular-json"); /* Logging functions - To be extended @@ -12,23 +12,23 @@ class Logger { constructor(context) { } - debug(...args: any): any { + debug(...args) { globalDebug(this.context, ...args); } - log(...args: any): any { + log(...args) { globalLog(this.context, ...args); } - warn(...args: any): any { + warn(...args) { globalWarn(this.context, ...args); } - error(...args: any): any { + error(...args) { globalError(this.context, ...args); } } -export function createLogger(context: any): any { +export function createLogger(context) { return new Logger(context); } -function prepareObjectForLogging(obj: any, maxDepth: any = 1): any { +function prepareObjectForLogging(obj, maxDepth = 1) { if (!window.Sentry) { // Not required without sentry return obj; @@ -36,9 +36,9 @@ function prepareObjectForLogging(obj: any, maxDepth: any = 1): any { if (typeof obj !== "object" && !Array.isArray(obj)) { return obj; } - const result: any = {}; - for (const key: any in obj) { - const val: any = obj[key]; + const result = {}; + for (const key in obj) { + const val = obj[key]; if (typeof val === "object") { if (maxDepth > 0) { result[key] = prepareObjectForLogging(val, maxDepth - 1); @@ -56,11 +56,11 @@ function prepareObjectForLogging(obj: any, maxDepth: any = 1): any { /** * Serializes an error */ -export function serializeError(err: Error | ErrorEvent): any { +export function serializeError(err: Error | ErrorEvent) { if (!err) { return null; } - const result: any = { + const result = { type: err.constructor.name, }; @@ -91,8 +91,8 @@ export function serializeError(err: Error | ErrorEvent): any { /** * Serializes an event */ -function serializeEvent(event: Event): any { - let result: any = { +function serializeEvent(event: Event) { + let result = { type: "{type.Event:" + typeof event + "}", }; result.eventType = event.type; @@ -101,7 +101,7 @@ function serializeEvent(event: Event): any { /** * Prepares a json payload */ -function preparePayload(key: string, value: any): any { +function preparePayload(key: string, value: any) { if (value instanceof Error || value instanceof ErrorEvent) { return serializeError(value); } @@ -116,44 +116,44 @@ function preparePayload(key: string, value: any): any { /** * Stringifies an object containing circular references and errors */ -export function stringifyObjectContainingErrors(payload: any): any { +export function stringifyObjectContainingErrors(payload: any) { return circularJson.stringify(payload, preparePayload); } -export function globalDebug(context: any, ...args: any): any { +export function globalDebug(context, ...args) { if (G_IS_DEV) { logInternal(context, console.log, prepareArgsForLogging(args)); } } -export function globalLog(context: any, ...args: any): any { +export function globalLog(context, ...args) { // eslint-disable-next-line no-console logInternal(context, console.log, prepareArgsForLogging(args)); } -export function globalWarn(context: any, ...args: any): any { +export function globalWarn(context, ...args) { // eslint-disable-next-line no-console logInternal(context, console.warn, prepareArgsForLogging(args)); } -export function globalError(context: any, ...args: any): any { +export function globalError(context, ...args) { args = prepareArgsForLogging(args); // eslint-disable-next-line no-console logInternal(context, console.error, args); if (window.Sentry) { - window.Sentry.withScope((scope: any): any => { + window.Sentry.withScope(scope => { scope.setExtra("args", args); window.Sentry.captureMessage(internalBuildStringFromArgs(args), "error"); }); } } -function prepareArgsForLogging(args: any): any { - let result: any = []; - for (let i: any = 0; i < args.length; ++i) { +function prepareArgsForLogging(args) { + let result = []; + for (let i = 0; i < args.length; ++i) { result.push(prepareObjectForLogging(args[i])); } return result; } -function internalBuildStringFromArgs(args: Array): any { - let result: any = []; - for (let i: any = 0; i < args.length; ++i) { - let arg: any = args[i]; +function internalBuildStringFromArgs(args: Array) { + let result = []; + for (let i = 0; i < args.length; ++i) { + let arg = args[i]; if (typeof arg === "string" || typeof arg === "number" || typeof arg === "boolean" || @@ -170,17 +170,17 @@ function internalBuildStringFromArgs(args: Array): any { } return result.join(" "); } -export function logSection(name: any, color: any): any { +export function logSection(name, color) { while (name.length <= 14) { name = " " + name + " "; } name = name.padEnd(19, " "); - const lineCss: any = "letter-spacing: -3px; color: " + color + "; font-size: 6px; background: #eee; color: #eee;"; - const line: any = "%c----------------------------"; + const lineCss = "letter-spacing: -3px; color: " + color + "; font-size: 6px; background: #eee; color: #eee;"; + const line = "%c----------------------------"; console.log("\n" + line + " %c" + name + " " + line + "\n", lineCss, "color: " + color, lineCss); } -function extractHandleContext(handle: any): any { - let context: any = handle || "unknown"; +function extractHandleContext(handle) { + let context = handle || "unknown"; if (handle && handle.constructor && handle.constructor.name) { @@ -195,11 +195,11 @@ function extractHandleContext(handle: any): any { } return context + ""; } -function logInternal(handle: any, consoleMethod: any, args: any): any { - const context: any = extractHandleContext(handle).padEnd(20, " "); - const labelColor: any = handle && handle.LOG_LABEL_COLOR ? handle.LOG_LABEL_COLOR : "#aaa"; +function logInternal(handle, consoleMethod, args) { + const context = extractHandleContext(handle).padEnd(20, " "); + const labelColor = handle && handle.LOG_LABEL_COLOR ? handle.LOG_LABEL_COLOR : "#aaa"; if (G_IS_DEV && globalConfig.debug.logTimestamps) { - const timestamp: any = "⏱ %c" + (Math.floor(performance.now()) + "").padEnd(6, " ") + ""; + const timestamp = "⏱ %c" + (Math.floor(performance.now()) + "").padEnd(6, " ") + ""; consoleMethod.call(console, timestamp + " %c" + context, "color: #7f7;", "color: " + labelColor + ";", ...args); } else { diff --git a/src/ts/core/lzstring.ts b/src/ts/core/lzstring.ts index c93f3bb3..0c12535a 100644 --- a/src/ts/core/lzstring.ts +++ b/src/ts/core/lzstring.ts @@ -7,45 +7,45 @@ // http://pieroxy.net/blog/pages/lz-string/testing.html // // LZ-based compression algorithm, version 1.4.4 -const fromCharCode: any = String.fromCharCode; -const hasOwnProperty: any = Object.prototype.hasOwnProperty; -const keyStrUriSafe: any = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; -const baseReverseDic: any = {}; -function getBaseValue(alphabet: any, character: any): any { +const fromCharCode = String.fromCharCode; +const hasOwnProperty = Object.prototype.hasOwnProperty; +const keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; +const baseReverseDic = {}; +function getBaseValue(alphabet, character) { if (!baseReverseDic[alphabet]) { baseReverseDic[alphabet] = {}; - for (let i: any = 0; i < alphabet.length; i++) { + for (let i = 0; i < alphabet.length; i++) { baseReverseDic[alphabet][alphabet.charAt(i)] = i; } } return baseReverseDic[alphabet][character]; } //compress into uint8array (UCS-2 big endian format) -export function compressU8(uncompressed: any): any { - let compressed: any = compress(uncompressed); - let buf: any = new Uint8Array(compressed.length * 2); // 2 bytes per character - for (let i: any = 0, TotalLen: any = compressed.length; i < TotalLen; i++) { - let current_value: any = compressed.charCodeAt(i); +export function compressU8(uncompressed) { + let compressed = compress(uncompressed); + let buf = new Uint8Array(compressed.length * 2); // 2 bytes per character + for (let i = 0, TotalLen = compressed.length; i < TotalLen; i++) { + let current_value = compressed.charCodeAt(i); buf[i * 2] = current_value >>> 8; buf[i * 2 + 1] = current_value % 256; } return buf; } // Compreses with header -export function compressU8WHeader(uncompressed: string, header: number): any { - let compressed: any = compress(uncompressed); - let buf: any = new Uint8Array(2 + compressed.length * 2); // 2 bytes per character +export function compressU8WHeader(uncompressed: string, header: number) { + let compressed = compress(uncompressed); + let buf = new Uint8Array(2 + compressed.length * 2); // 2 bytes per character buf[0] = header >>> 8; buf[1] = header % 256; - for (let i: any = 0, TotalLen: any = compressed.length; i < TotalLen; i++) { - let current_value: any = compressed.charCodeAt(i); + for (let i = 0, TotalLen = compressed.length; i < TotalLen; i++) { + let current_value = compressed.charCodeAt(i); buf[2 + i * 2] = current_value >>> 8; buf[2 + i * 2 + 1] = current_value % 256; } return buf; } //decompress from uint8array (UCS-2 big endian format) -export function decompressU8WHeader(compressed: Uint8Array): any { +export function decompressU8WHeader(compressed: Uint8Array) { // let buf = new Array(compressed.length / 2); // 2 bytes per character // for (let i = 0, TotalLen = buf.length; i < TotalLen; i++) { // buf[i] = compressed[i * 2] * 256 + compressed[i * 2 + 1]; @@ -54,42 +54,42 @@ export function decompressU8WHeader(compressed: Uint8Array): any { // buf.forEach(function (c) { // result.push(fromCharCode(c)); // }); - let result: any = []; - for (let i: any = 2, n: any = compressed.length; i < n; i += 2) { - const code: any = compressed[i] * 256 + compressed[i + 1]; + let result = []; + for (let i = 2, n = compressed.length; i < n; i += 2) { + const code = compressed[i] * 256 + compressed[i + 1]; result.push(fromCharCode(code)); } return decompress(result.join("")); } //compress into a string that is already URI encoded -export function compressX64(input: any): any { +export function compressX64(input) { if (input == null) return ""; - return _compress(input, 6, function (a: any): any { + return _compress(input, 6, function (a) { return keyStrUriSafe.charAt(a); }); } //decompress from an output of compressToEncodedURIComponent -export function decompressX64(input: any): any { +export function decompressX64(input) { if (input == null) return ""; if (input == "") return null; input = input.replace(/ /g, "+"); - return _decompress(input.length, 32, function (index: any): any { + return _decompress(input.length, 32, function (index) { return getBaseValue(keyStrUriSafe, input.charAt(index)); }); } -function compress(uncompressed: any): any { - return _compress(uncompressed, 16, function (a: any): any { +function compress(uncompressed) { + return _compress(uncompressed, 16, function (a) { return fromCharCode(a); }); } -function _compress(uncompressed: any, bitsPerChar: any, getCharFromInt: any): any { +function _compress(uncompressed, bitsPerChar, getCharFromInt) { if (uncompressed == null) return ""; - let i: any, value: any, context_dictionary: any = {}, context_dictionaryToCreate: any = {}, context_c: any = "", context_wc: any = "", context_w: any = "", context_enlargeIn: any = 2, // Compensate for the first entry which should not count - context_dictSize: any = 3, context_numBits: any = 2, context_data: any = [], context_data_val: any = 0, context_data_position: any = 0, ii: any; + let i, value, context_dictionary = {}, context_dictionaryToCreate = {}, context_c = "", context_wc = "", context_w = "", context_enlargeIn = 2, // Compensate for the first entry which should not count + context_dictSize = 3, context_numBits = 2, context_data = [], context_data_val = 0, context_data_position = 0, ii; for (ii = 0; ii < uncompressed.length; ii += 1) { context_c = uncompressed.charAt(ii); if (!hasOwnProperty.call(context_dictionary, context_c)) { @@ -300,17 +300,17 @@ function _compress(uncompressed: any, bitsPerChar: any, getCharFromInt: any): an } return context_data.join(""); } -function decompress(compressed: any): any { +function decompress(compressed) { if (compressed == null) return ""; if (compressed == "") return null; - return _decompress(compressed.length, 32768, function (index: any): any { + return _decompress(compressed.length, 32768, function (index) { return compressed.charCodeAt(index); }); } -function _decompress(length: any, resetValue: any, getNextValue: any): any { - let dictionary: any = [], next: any, enlargeIn: any = 4, dictSize: any = 4, numBits: any = 3, entry: any = "", result: any = [], i: any, w: any, bits: any, resb: any, maxpower: any, power: any, c: any, data: any = { val: getNextValue(0), position: resetValue, index: 1 }; +function _decompress(length, resetValue, getNextValue) { + let dictionary = [], next, enlargeIn = 4, dictSize = 4, numBits = 3, entry = "", result = [], i, w, bits, resb, maxpower, power, c, data = { val: getNextValue(0), position: resetValue, index: 1 }; for (i = 0; i < 3; i += 1) { dictionary[i] = i; } diff --git a/src/ts/core/modal_dialog_elements.ts b/src/ts/core/modal_dialog_elements.ts index f656ccfe..220b440b 100644 --- a/src/ts/core/modal_dialog_elements.ts +++ b/src/ts/core/modal_dialog_elements.ts @@ -21,9 +21,9 @@ import { T } from "../translations"; * * *************************************************** */ -const kbEnter: any = 13; -const kbCancel: any = 27; -const logger: any = createLogger("dialogs"); +const kbEnter = 13; +const kbCancel = 27; +const logger = createLogger("dialogs"); /** * Basic text based dialog */ @@ -48,11 +48,11 @@ export class Dialog { */ constructor({ app, title, contentHTML, buttons, type = "info", closeButton = false }) { - for (let i: any = 0; i < buttons.length; ++i) { + for (let i = 0; i < buttons.length; ++i) { if (G_IS_DEV && globalConfig.debug.disableTimedButtons) { this.buttonIds[i] = this.buttonIds[i].replace(":timeout", ""); } - const buttonId: any = this.buttonIds[i].split(":")[0]; + const buttonId = this.buttonIds[i].split(":")[0]; this.buttonSignals[buttonId] = new Signal(); } this.inputReciever.keydown.add(this.handleKeydown, this); @@ -65,7 +65,7 @@ export class Dialog { shift: boolean; alt: boolean; ctrl: boolean; - }): any { + }) { if (keyCode === kbEnter && this.enterHandler) { this.internalButtonHandler(this.enterHandler); return STOP_PROPAGATION; @@ -75,15 +75,15 @@ export class Dialog { return STOP_PROPAGATION; } } - internalButtonHandler(id: any, ...payload: any): any { + internalButtonHandler(id, ...payload) { this.app.inputMgr.popReciever(this.inputReciever); if (id !== "close-button") { this.buttonSignals[id].dispatch(...payload); } this.closeRequested.dispatch(); } - createElement(): any { - const elem: any = document.createElement("div"); + createElement() { + const elem = document.createElement("div"); elem.classList.add("ingameDialog"); this.dialogElem = document.createElement("div"); this.dialogElem.classList.add("dialogInner"); @@ -91,45 +91,45 @@ export class Dialog { this.dialogElem.classList.add(this.type); } elem.appendChild(this.dialogElem); - const title: any = document.createElement("h1"); + const title = document.createElement("h1"); title.innerText = this.title; title.classList.add("title"); this.dialogElem.appendChild(title); if (this.closeButton) { this.dialogElem.classList.add("hasCloseButton"); - const closeBtn: any = document.createElement("button"); + const closeBtn = document.createElement("button"); closeBtn.classList.add("closeButton"); - this.trackClicks(closeBtn, (): any => this.internalButtonHandler("close-button"), { + this.trackClicks(closeBtn, () => this.internalButtonHandler("close-button"), { applyCssClass: "pressedSmallElement", }); title.appendChild(closeBtn); - this.inputReciever.backButton.add((): any => this.internalButtonHandler("close-button")); + this.inputReciever.backButton.add(() => this.internalButtonHandler("close-button")); } - const content: any = document.createElement("div"); + const content = document.createElement("div"); content.classList.add("content"); content.innerHTML = this.contentHTML; this.dialogElem.appendChild(content); if (this.buttonIds.length > 0) { - const buttons: any = document.createElement("div"); + const buttons = document.createElement("div"); buttons.classList.add("buttons"); // Create buttons - for (let i: any = 0; i < this.buttonIds.length; ++i) { - const [buttonId, buttonStyle, rawParams]: any = this.buttonIds[i].split(":"); - const button: any = document.createElement("button"); + for (let i = 0; i < this.buttonIds.length; ++i) { + const [buttonId, buttonStyle, rawParams] = this.buttonIds[i].split(":"); + const button = document.createElement("button"); button.classList.add("button"); button.classList.add("styledButton"); button.classList.add(buttonStyle); button.innerText = T.dialogs.buttons[buttonId]; - const params: any = (rawParams || "").split("/"); - const useTimeout: any = params.indexOf("timeout") >= 0; - const isEnter: any = params.indexOf("enter") >= 0; - const isEscape: any = params.indexOf("escape") >= 0; + const params = (rawParams || "").split("/"); + const useTimeout = params.indexOf("timeout") >= 0; + const isEnter = params.indexOf("enter") >= 0; + const isEscape = params.indexOf("escape") >= 0; if (isEscape && this.closeButton) { logger.warn("Showing dialog with close button, and additional cancel button"); } if (useTimeout) { button.classList.add("timedButton"); - const timeout: any = setTimeout((): any => { + const timeout = setTimeout(() => { button.classList.remove("timedButton"); arrayDeleteValue(this.timeouts, timeout); }, 1000); @@ -138,7 +138,7 @@ export class Dialog { if (isEnter || isEscape) { // if (this.app.settings.getShowKeyboardShortcuts()) { // Show keybinding - const spacer: any = document.createElement("code"); + const spacer = document.createElement("code"); spacer.classList.add("keybinding"); spacer.innerHTML = getStringForKeyCode(isEnter ? kbEnter : kbCancel); button.appendChild(spacer); @@ -150,7 +150,7 @@ export class Dialog { this.escapeHandler = buttonId; } } - this.trackClicks(button, (): any => this.internalButtonHandler(buttonId)); + this.trackClicks(button, () => this.internalButtonHandler(buttonId)); buttons.appendChild(button); } this.dialogElem.appendChild(buttons); @@ -162,10 +162,10 @@ export class Dialog { this.app.inputMgr.pushReciever(this.inputReciever); return this.element; } - setIndex(index: any): any { + setIndex(index) { this.element.style.zIndex = index; } - destroy(): any { + destroy() { if (!this.element) { assert(false, "Tried to destroy dialog twice"); return; @@ -174,21 +174,21 @@ export class Dialog { // dispatched to the modal dialogs, it will not call the internalButtonHandler, // and thus our receiver stays attached the whole time this.app.inputMgr.destroyReceiver(this.inputReciever); - for (let i: any = 0; i < this.clickDetectors.length; ++i) { + for (let i = 0; i < this.clickDetectors.length; ++i) { this.clickDetectors[i].cleanup(); } this.clickDetectors = []; this.element.remove(); this.element = null; - for (let i: any = 0; i < this.timeouts.length; ++i) { + for (let i = 0; i < this.timeouts.length; ++i) { clearTimeout(this.timeouts[i]); } this.timeouts = []; } - hide(): any { + hide() { this.element.classList.remove("visible"); } - show(): any { + show() { this.element.classList.add("visible"); } /** @@ -196,7 +196,7 @@ export class Dialog { * {} */ trackClicks(elem: Element, handler: function():void, args: import("./click_detector").ClickDetectorConstructorArgs= = {}): ClickDetector { - const detector: any = new ClickDetector(elem, args); + const detector = new ClickDetector(elem, args); detector.click.add(handler, this); this.clickDetectors.push(detector); return detector; @@ -220,18 +220,18 @@ export class DialogLoading extends Dialog { this.inputReciever.backButton.removeAll(); this.inputReciever.context = "dialog-loading"; } - createElement(): any { - const elem: any = document.createElement("div"); + createElement() { + const elem = document.createElement("div"); elem.classList.add("ingameDialog"); elem.classList.add("loadingDialog"); this.element = elem; if (this.text) { - const text: any = document.createElement("div"); + const text = document.createElement("div"); text.classList.add("text"); text.innerText = this.text; elem.appendChild(text); } - const loader: any = document.createElement("div"); + const loader = document.createElement("div"); loader.classList.add("prefab_LoadingTextWithAnim"); loader.classList.add("loadingIndicator"); elem.appendChild(loader); @@ -244,10 +244,10 @@ export class DialogOptionChooser extends Dialog { public initialOption = options.active; constructor({ app, title, options }) { - let html: any = "
"; - options.options.forEach(({ value, text, desc = null, iconPrefix = null }: any): any => { - const descHtml: any = desc ? `${desc}` : ""; - let iconHtml: any = iconPrefix ? `` : ""; + let html = "
"; + options.options.forEach(({ value, text, desc = null, iconPrefix = null }) => { + const descHtml = desc ? `${desc}` : ""; + let iconHtml = iconPrefix ? `` : ""; html += `
${iconHtml} @@ -267,17 +267,17 @@ export class DialogOptionChooser extends Dialog { }); this.buttonSignals.optionSelected = new Signal(); } - createElement(): any { - const div: any = super.createElement(); + createElement() { + const div = super.createElement(); this.dialogElem.classList.add("optionChooserDialog"); - div.querySelectorAll("[data-optionvalue]").forEach((handle: any): any => { - const value: any = handle.getAttribute("data-optionvalue"); + div.querySelectorAll("[data-optionvalue]").forEach(handle => { + const value = handle.getAttribute("data-optionvalue"); if (!handle) { logger.error("Failed to bind option value in dialog:", value); return; } // Need click detector here to forward elements, otherwise scrolling does not work - const detector: any = new ClickDetector(handle, { + const detector = new ClickDetector(handle, { consumeEvents: false, preventDefault: false, clickSound: null, @@ -286,8 +286,8 @@ export class DialogOptionChooser extends Dialog { }); this.clickDetectors.push(detector); if (value !== this.initialOption) { - detector.click.add((): any => { - const selected: any = div.querySelector(".option.active"); + detector.click.add(() => { + const selected = div.querySelector(".option.active"); if (selected) { selected.classList.remove("active"); } @@ -309,9 +309,9 @@ export class DialogWithForm extends Dialog { public enterHandler = confirmButtonId; constructor({ app, title, desc, formElements, buttons = ["cancel", "ok:good"], confirmButtonId = "ok", closeButton = true, }) { - let html: any = ""; + let html = ""; html += desc + "
"; - for (let i: any = 0; i < formElements.length; ++i) { + for (let i = 0; i < formElements.length; ++i) { html += formElements[i].getHtml(); } super({ @@ -323,11 +323,11 @@ export class DialogWithForm extends Dialog { closeButton, }); } - internalButtonHandler(id: any, ...payload: any): any { + internalButtonHandler(id, ...payload) { if (id === this.confirmButtonId) { if (this.hasAnyInvalid()) { this.dialogElem.classList.remove("errorShake"); - waitNextFrame().then((): any => { + waitNextFrame().then(() => { if (this.dialogElem) { this.dialogElem.classList.add("errorShake"); } @@ -338,23 +338,23 @@ export class DialogWithForm extends Dialog { } super.internalButtonHandler(id, payload); } - hasAnyInvalid(): any { - for (let i: any = 0; i < this.formElements.length; ++i) { + hasAnyInvalid() { + for (let i = 0; i < this.formElements.length; ++i) { if (!this.formElements[i].isValid()) { return true; } } return false; } - createElement(): any { - const div: any = super.createElement(); - for (let i: any = 0; i < this.formElements.length; ++i) { - const elem: any = this.formElements[i]; + createElement() { + const div = super.createElement(); + for (let i = 0; i < this.formElements.length; ++i) { + const elem = this.formElements[i]; elem.bindEvents(div, this.clickDetectors); // elem.valueChosen.add(this.closeRequested.dispatch, this.closeRequested); elem.valueChosen.add(this.valueChosen.dispatch, this.valueChosen); } - waitNextFrame().then((): any => { + waitNextFrame().then(() => { this.formElements[this.formElements.length - 1].focus(); }); return div; diff --git a/src/ts/core/modal_dialog_forms.ts b/src/ts/core/modal_dialog_forms.ts index 3fc29f57..81375c58 100644 --- a/src/ts/core/modal_dialog_forms.ts +++ b/src/ts/core/modal_dialog_forms.ts @@ -18,18 +18,18 @@ export class FormElement { constructor(id, label) { } - getHtml(): any { + getHtml() { abstract; return ""; } - getFormElement(parent: any): any { + getFormElement(parent) { return parent.querySelector("[data-formId='" + this.id + "']"); } - bindEvents(parent: any, clickTrackers: any): any { + bindEvents(parent, clickTrackers) { abstract; } - focus(): any { } - isValid(): any { + focus() { } + isValid() { return true; } /** {} */ @@ -47,10 +47,10 @@ export class FormElementInput extends FormElement { constructor({ id, label = null, placeholder, defaultValue = "", inputType = "text", validator = null }) { super(id, label); } - getHtml(): any { - let classes: any = []; - let inputType: any = "text"; - let maxlength: any = 256; + getHtml() { + let classes = []; + let inputType = "text"; + let maxlength = 256; switch (this.inputType) { case "text": { classes.push("input-text"); @@ -85,25 +85,25 @@ export class FormElementInput extends FormElement {
`; } - bindEvents(parent: any, clickTrackers: any): any { + bindEvents(parent, clickTrackers) { this.element = this.getFormElement(parent); - this.element.addEventListener("input", (event: any): any => this.updateErrorState()); + this.element.addEventListener("input", event => this.updateErrorState()); this.updateErrorState(); } - updateErrorState(): any { + updateErrorState() { this.element.classList.toggle("errored", !this.isValid()); } - isValid(): any { + isValid() { return !this.validator || this.validator(this.element.value); } - getValue(): any { + getValue() { return this.element.value; } - setValue(value: any): any { + setValue(value) { this.element.value = value; this.updateErrorState(); } - focus(): any { + focus() { this.element.focus(); this.element.select(); } @@ -116,7 +116,7 @@ export class FormElementCheckbox extends FormElement { constructor({ id, label, defaultValue = true }) { super(id, label); } - getHtml(): any { + getHtml() { return `
${this.label ? `` : ""} @@ -126,23 +126,23 @@ export class FormElementCheckbox extends FormElement {
`; } - bindEvents(parent: any, clickTrackers: any): any { + bindEvents(parent, clickTrackers) { this.element = this.getFormElement(parent); - const detector: any = new ClickDetector(this.element, { + const detector = new ClickDetector(this.element, { consumeEvents: false, preventDefault: false, }); clickTrackers.push(detector); detector.click.add(this.toggle, this); } - getValue(): any { + getValue() { return this.value; } - toggle(): any { + toggle() { this.value = !this.value; this.element.classList.toggle("checked", this.value); } - focus(parent: any): any { } + focus(parent) { } } export class FormElementItemChooser extends FormElement { public items = items; @@ -152,8 +152,8 @@ export class FormElementItemChooser extends FormElement { constructor({ id, label, items = [] }) { super(id, label); } - getHtml(): any { - let classes: any = []; + getHtml() { + let classes = []; return `
${this.label ? `` : ""} @@ -161,29 +161,29 @@ export class FormElementItemChooser extends FormElement {
`; } - bindEvents(parent: HTMLElement, clickTrackers: Array): any { + bindEvents(parent: HTMLElement, clickTrackers: Array) { this.element = this.getFormElement(parent); - for (let i: any = 0; i < this.items.length; ++i) { - const item: any = this.items[i]; - const canvas: any = document.createElement("canvas"); + for (let i = 0; i < this.items.length; ++i) { + const item = this.items[i]; + const canvas = document.createElement("canvas"); canvas.width = 128; canvas.height = 128; - const context: any = canvas.getContext("2d"); + const context = canvas.getContext("2d"); item.drawFullSizeOnCanvas(context, 128); this.element.appendChild(canvas); - const detector: any = new ClickDetector(canvas, {}); + const detector = new ClickDetector(canvas, {}); clickTrackers.push(detector); - detector.click.add((): any => { + detector.click.add(() => { this.chosenItem = item; this.valueChosen.dispatch(item); }); } } - isValid(): any { + isValid() { return true; } - getValue(): any { + getValue() { return null; } - focus(): any { } + focus() { } } diff --git a/src/ts/core/polyfills.ts b/src/ts/core/polyfills.ts index cd7c7fcd..e59949fe 100644 --- a/src/ts/core/polyfills.ts +++ b/src/ts/core/polyfills.ts @@ -1,18 +1,18 @@ -function mathPolyfills(): any { +function mathPolyfills() { // Converts from degrees to radians. - Math.radians = function (degrees: any): any { + Math.radians = function (degrees) { return (degrees * Math.PI) / 180.0; }; // Converts from radians to degrees. - Math.degrees = function (radians: any): any { + Math.degrees = function (radians) { return (radians * 180.0) / Math.PI; }; } -function stringPolyfills(): any { +function stringPolyfills() { // https://github.com/uxitten/polyfill/blob/master/string.polyfill.js // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart if (!String.prototype.padStart) { - String.prototype.padStart = function padStart(targetLength: any, padString: any): any { + String.prototype.padStart = function padStart(targetLength, padString) { targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== "undefined" ? padString : " "); if (this.length >= targetLength) { @@ -30,7 +30,7 @@ function stringPolyfills(): any { // https://github.com/uxitten/polyfill/blob/master/string.polyfill.js // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd if (!String.prototype.padEnd) { - String.prototype.padEnd = function padEnd(targetLength: any, padString: any): any { + String.prototype.padEnd = function padEnd(targetLength, padString) { targetLength = targetLength >> 0; //floor if number or convert non-number to 0; padString = String(typeof padString !== "undefined" ? padString : " "); if (this.length > targetLength) { @@ -46,33 +46,33 @@ function stringPolyfills(): any { }; } } -function objectPolyfills(): any { +function objectPolyfills() { // https://github.com/tc39/proposal-object-values-entries/blob/master/polyfill.js // @ts-ignore - const reduce: any = Function.bind.call(Function.call, Array.prototype.reduce); + const reduce = Function.bind.call(Function.call, Array.prototype.reduce); // @ts-ignore - const isEnumerable: any = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable); + const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable); // @ts-ignore - const concat: any = Function.bind.call(Function.call, Array.prototype.concat); - const keys: any = Reflect.ownKeys; + const concat = Function.bind.call(Function.call, Array.prototype.concat); + const keys = Reflect.ownKeys; // @ts-ignore if (!Object.values) { // @ts-ignore - Object.values = function values(O: any): any { - return reduce(keys(O), (v: any, k: any): any => concat(v, typeof k === "string" && isEnumerable(O, k) ? [O[k]] : []), []); + Object.values = function values(O) { + return reduce(keys(O), (v, k) => concat(v, typeof k === "string" && isEnumerable(O, k) ? [O[k]] : []), []); }; } if (!Object.entries) { // @ts-ignore - Object.entries = function entries(O: any): any { - return reduce(keys(O), (e: any, k: any): any => concat(e, typeof k === "string" && isEnumerable(O, k) ? [[k, O[k]]] : []), []); + Object.entries = function entries(O) { + return reduce(keys(O), (e, k) => concat(e, typeof k === "string" && isEnumerable(O, k) ? [[k, O[k]]] : []), []); }; } } -function domPolyfills(): any { +function domPolyfills() { // from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md - (function (arr: any): any { - arr.forEach(function (item: any): any { + (function (arr) { + arr.forEach(function (item) { if (item.hasOwnProperty("remove")) { return; } @@ -80,22 +80,22 @@ function domPolyfills(): any { configurable: true, enumerable: true, writable: true, - value: function remove(): any { + value: function remove() { this.parentNode.removeChild(this); }, }); }); })([Element.prototype, CharacterData.prototype, DocumentType.prototype]); } -function initPolyfills(): any { +function initPolyfills() { mathPolyfills(); stringPolyfills(); objectPolyfills(); domPolyfills(); } -function initExtensions(): any { - String.prototype.replaceAll = function (search: any, replacement: any): any { - var target: any = this; +function initExtensions() { + String.prototype.replaceAll = function (search, replacement) { + var target = this; return target.split(search).join(replacement); }; } diff --git a/src/ts/core/query_parameters.ts b/src/ts/core/query_parameters.ts index 8b8f1ae0..3ef20184 100644 --- a/src/ts/core/query_parameters.ts +++ b/src/ts/core/query_parameters.ts @@ -1,6 +1,6 @@ -const queryString: any = require("query-string"); -const options: any = queryString.parse(location.search); -export let queryParamOptions: any = { +const queryString = require("query-string"); +const options = queryString.parse(location.search); +export let queryParamOptions = { embedProvider: null, abtVariant: null, campaign: null, diff --git a/src/ts/core/read_write_proxy.ts b/src/ts/core/read_write_proxy.ts index 3c409c8f..a3ff65ab 100644 --- a/src/ts/core/read_write_proxy.ts +++ b/src/ts/core/read_write_proxy.ts @@ -10,9 +10,9 @@ import { ExplainedResult } from "./explained_result"; import { decompressX64, compressX64 } from "./lzstring"; import { asyncCompressor, compressionPrefix } from "./async_compression"; import { compressObject, decompressObject } from "../savegame/savegame_compressor"; -const debounce: any = require("debounce-promise"); -const logger: any = createLogger("read_write_proxy"); -const salt: any = accessNestedPropertyReverse(globalConfig, ["file", "info"]); +const debounce = require("debounce-promise"); +const logger = createLogger("read_write_proxy"); +const salt = accessNestedPropertyReverse(globalConfig, ["file", "info"]); // Helper which only writes / reads if verify() works. Also performs migration export class ReadWriteProxy { public app: Application = app; @@ -23,47 +23,47 @@ export class ReadWriteProxy { constructor(app, filename) { // TODO: EXTREMELY HACKY! To verify we need to do this a step later if (G_IS_DEV && IS_DEBUG) { - setTimeout((): any => { + setTimeout(() => { assert(this.verify(this.getDefaultData()).result, "Verify() failed for default data: " + this.verify(this.getDefaultData()).reason); }); } } // -- Methods to override /** {} */ - verify(data: any): ExplainedResult { + verify(data): ExplainedResult { abstract; return ExplainedResult.bad(); } // Should return the default data - getDefaultData(): any { + getDefaultData() { abstract; return {}; } // Should return the current version as an integer - getCurrentVersion(): any { + getCurrentVersion() { abstract; return 0; } // Should migrate the data (Modify in place) /** {} */ - migrate(data: any): ExplainedResult { + migrate(data): ExplainedResult { abstract; return ExplainedResult.bad(); } // -- / Methods // Resets whole data, returns promise - resetEverythingAsync(): any { + resetEverythingAsync() { logger.warn("Reset data to default"); this.currentData = this.getDefaultData(); return this.writeAsync(); } - static serializeObject(obj: object): any { - const jsonString: any = JSON.stringify(compressObject(obj)); - const checksum: any = computeCrc(jsonString + salt); + static serializeObject(obj: object) { + const jsonString = JSON.stringify(compressObject(obj)); + const checksum = computeCrc(jsonString + salt); return compressionPrefix + compressX64(checksum + jsonString); } - static deserializeObject(text: object): any { - const decompressed: any = decompressX64(text.substr(compressionPrefix.length)); + static deserializeObject(text: object) { + const decompressed = decompressX64(text.substr(compressionPrefix.length)); if (!decompressed) { // LZ string decompression failure throw new Error("bad-content / decompression-failed"); @@ -73,17 +73,17 @@ export class ReadWriteProxy { throw new Error("bad-content / payload-too-small"); } // Compare stored checksum with actual checksum - const checksum: any = decompressed.substring(0, 40); - const jsonString: any = decompressed.substr(40); - const desiredChecksum: any = checksum.startsWith(CRC_PREFIX) + const checksum = decompressed.substring(0, 40); + const jsonString = decompressed.substr(40); + const desiredChecksum = checksum.startsWith(CRC_PREFIX) ? computeCrc(jsonString + salt) : sha1(jsonString + salt); if (desiredChecksum !== checksum) { // Checksum mismatch throw new Error("bad-content / checksum-mismatch"); } - const parsed: any = JSON.parse(jsonString); - const decoded: any = decompressObject(parsed); + const parsed = JSON.parse(jsonString); + const decoded = decompressObject(parsed); return decoded; } /** @@ -92,7 +92,7 @@ export class ReadWriteProxy { * {} */ writeAsync(): Promise { - const verifyResult: any = this.internalVerifyEntry(this.currentData); + const verifyResult = this.internalVerifyEntry(this.currentData); if (!verifyResult.result) { logger.error("Tried to write invalid data to", this.filename, "reason:", verifyResult.reason); return Promise.reject(verifyResult.reason); @@ -106,24 +106,24 @@ export class ReadWriteProxy { doWriteAsync(): Promise { return asyncCompressor .compressObjectAsync(this.currentData) - .then((compressed: any): any => { + .then(compressed => { return this.app.storage.writeFileAsync(this.filename, compressed); }) - .then((): any => { + .then(() => { logger.log("📄 Wrote", this.filename); }) - .catch((err: any): any => { + .catch(err => { logger.error("Failed to write", this.filename, ":", err); throw err; }); } // Reads the data asynchronously, fails if verify() fails - readAsync(): any { + readAsync() { // Start read request return (this.app.storage .readFileAsync(this.filename) // Check for errors during read - .catch((err: any): any => { + .catch(err => { if (err === FILE_NOT_FOUND) { logger.log("File not found, using default data"); // File not found or unreadable, assume default file @@ -133,13 +133,13 @@ export class ReadWriteProxy { }) // Decrypt data (if its encrypted) // @ts-ignore - .then((rawData: any): any => { + .then(rawData => { if (rawData == null) { // So, the file has not been found, use default data return JSON.stringify(compressObject(this.getDefaultData())); } if (rawData.startsWith(compressionPrefix)) { - const decompressed: any = decompressX64(rawData.substr(compressionPrefix.length)); + const decompressed = decompressX64(rawData.substr(compressionPrefix.length)); if (!decompressed) { // LZ string decompression failure return Promise.reject("bad-content / decompression-failed"); @@ -149,9 +149,9 @@ export class ReadWriteProxy { return Promise.reject("bad-content / payload-too-small"); } // Compare stored checksum with actual checksum - const checksum: any = decompressed.substring(0, 40); - const jsonString: any = decompressed.substr(40); - const desiredChecksum: any = checksum.startsWith(CRC_PREFIX) + const checksum = decompressed.substring(0, 40); + const jsonString = decompressed.substr(40); + const desiredChecksum = checksum.startsWith(CRC_PREFIX) ? computeCrc(jsonString + salt) : sha1(jsonString + salt); if (desiredChecksum !== checksum) { @@ -168,33 +168,33 @@ export class ReadWriteProxy { return rawData; }) // Parse JSON, this could throw but that's fine - .then((res: any): any => { + .then(res => { try { return JSON.parse(res); } - catch (ex: any) { + catch (ex) { logger.error("Failed to parse file content of", this.filename, ":", ex, "(content was:", res, ")"); throw new Error("invalid-serialized-data"); } }) // Decompress - .then((compressed: any): any => decompressObject(compressed)) + .then(compressed => decompressObject(compressed)) // Verify basic structure - .then((contents: any): any => { - const result: any = this.internalVerifyBasicStructure(contents); + .then(contents => { + const result = this.internalVerifyBasicStructure(contents); if (!result.isGood()) { return Promise.reject("verify-failed: " + result.reason); } return contents; }) // Check version and migrate if required - .then((contents: any): any => { + .then(contents => { if (contents.version > this.getCurrentVersion()) { return Promise.reject("stored-data-is-newer"); } if (contents.version < this.getCurrentVersion()) { logger.log("Trying to migrate data object from version", contents.version, "to", this.getCurrentVersion()); - const migrationResult: any = this.migrate(contents); // modify in place + const migrationResult = this.migrate(contents); // modify in place if (migrationResult.isBad()) { return Promise.reject("migration-failed: " + migrationResult.reason); } @@ -202,8 +202,8 @@ export class ReadWriteProxy { return contents; }) // Verify - .then((contents: any): any => { - const verifyResult: any = this.internalVerifyEntry(contents); + .then(contents => { + const verifyResult = this.internalVerifyEntry(contents); if (!verifyResult.result) { logger.error("Read invalid data from", this.filename, "reason:", verifyResult.reason, "contents:", contents); return Promise.reject("invalid-data: " + verifyResult.reason); @@ -211,13 +211,13 @@ export class ReadWriteProxy { return contents; }) // Store - .then((contents: any): any => { + .then(contents => { this.currentData = contents; logger.log("📄 Read data with version", this.currentData.version, "from", this.filename); return contents; }) // Catchall - .catch((err: any): any => { + .catch(err => { return Promise.reject("Failed to read " + this.filename + ": " + err); })); } @@ -230,7 +230,7 @@ export class ReadWriteProxy { } // Internal /** {} */ - internalVerifyBasicStructure(data: any): ExplainedResult { + internalVerifyBasicStructure(data): ExplainedResult { if (!data) { return ExplainedResult.bad("Data is empty"); } @@ -240,11 +240,11 @@ export class ReadWriteProxy { return ExplainedResult.good(); } /** {} */ - internalVerifyEntry(data: any): ExplainedResult { + internalVerifyEntry(data): ExplainedResult { if (data.version !== this.getCurrentVersion()) { return ExplainedResult.bad("Version mismatch, got " + data.version + " and expected " + this.getCurrentVersion()); } - const verifyStructureError: any = this.internalVerifyBasicStructure(data); + const verifyStructureError = this.internalVerifyBasicStructure(data); if (!verifyStructureError.isGood()) { return verifyStructureError; } diff --git a/src/ts/core/rectangle.ts b/src/ts/core/rectangle.ts index 59fd09ac..7df6a22a 100644 --- a/src/ts/core/rectangle.ts +++ b/src/ts/core/rectangle.ts @@ -12,29 +12,29 @@ export class Rectangle { /** * Creates a rectangle from top right bottom and left offsets */ - static fromTRBL(top: number, right: number, bottom: number, left: number): any { + static fromTRBL(top: number, right: number, bottom: number, left: number) { return new Rectangle(left, top, right - left, bottom - top); } /** * Constructs a new square rectangle */ - static fromSquare(x: number, y: number, size: number): any { + static fromSquare(x: number, y: number, size: number) { return new Rectangle(x, y, size, size); } - static fromTwoPoints(p1: Vector, p2: Vector): any { - const left: any = Math.min(p1.x, p2.x); - const top: any = Math.min(p1.y, p2.y); - const right: any = Math.max(p1.x, p2.x); - const bottom: any = Math.max(p1.y, p2.y); + static fromTwoPoints(p1: Vector, p2: Vector) { + const left = Math.min(p1.x, p2.x); + const top = Math.min(p1.y, p2.y); + const right = Math.max(p1.x, p2.x); + const bottom = Math.max(p1.y, p2.y); return new Rectangle(left, top, right - left, bottom - top); } - static centered(width: number, height: number): any { + static centered(width: number, height: number) { return new Rectangle(-Math.ceil(width / 2), -Math.ceil(height / 2), width, height); } /** * Returns if a intersects b */ - static intersects(a: Rectangle, b: Rectangle): any { + static intersects(a: Rectangle, b: Rectangle) { return a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom; } /** @@ -54,7 +54,7 @@ export class Rectangle { /** * Returns if this rectangle is equal to the other while taking an epsilon into account */ - equalsEpsilon(other: Rectangle, epsilon: number): any { + equalsEpsilon(other: Rectangle, epsilon: number) { return (epsilonCompare(this.x, other.x, epsilon) && epsilonCompare(this.y, other.y, epsilon) && epsilonCompare(this.w, other.w, epsilon) && @@ -106,28 +106,28 @@ export class Rectangle { /** * Sets the right side of the rect without moving it */ - setRight(right: number): any { + setRight(right: number) { this.w = right - this.x; } /** * Sets the bottom side of the rect without moving it */ - setBottom(bottom: number): any { + setBottom(bottom: number) { this.h = bottom - this.y; } /** * Sets the top side of the rect without scaling it */ - setTop(top: number): any { - const bottom: any = this.bottom(); + setTop(top: number) { + const bottom = this.bottom(); this.y = top; this.setBottom(bottom); } /** * Sets the left side of the rect without scaling it */ - setLeft(left: number): any { - const right: any = this.right(); + setLeft(left: number) { + const right = this.right(); this.x = left; this.setRight(right); } @@ -148,14 +148,14 @@ export class Rectangle { /** * Moves the rectangle by the given parameters */ - moveBy(x: number, y: number): any { + moveBy(x: number, y: number) { this.x += x; this.y += y; } /** * Moves the rectangle by the given vector */ - moveByVector(vec: Vector): any { + moveByVector(vec: Vector) { this.x += vec.x; this.y += vec.y; } @@ -163,7 +163,7 @@ export class Rectangle { * Scales every parameter (w, h, x, y) by the given factor. Useful to transform from world to * tile space and vice versa */ - allScaled(factor: number): any { + allScaled(factor: number) { return new Rectangle(this.x * factor, this.y * factor, this.w * factor, this.h * factor); } /** @@ -212,10 +212,10 @@ export class Rectangle { * {} */ getIntersection(rect: Rectangle): Rectangle | null { - const left: any = Math.max(this.x, rect.x); - const top: any = Math.max(this.y, rect.y); - const right: any = Math.min(this.x + this.w, rect.x + rect.w); - const bottom: any = Math.min(this.y + this.h, rect.y + rect.h); + const left = Math.max(this.x, rect.x); + const top = Math.max(this.y, rect.y); + const right = Math.min(this.x + this.w, rect.x + rect.w); + const bottom = Math.min(this.y + this.h, rect.y + rect.h); if (right <= left || bottom <= top) { return null; } @@ -224,14 +224,14 @@ export class Rectangle { /** * Returns whether the rectangle fully intersects the given rectangle */ - intersectsFully(rect: Rectangle): any { - const intersection: any = this.getIntersection(rect); + intersectsFully(rect: Rectangle) { + const intersection = this.getIntersection(rect); return intersection && Math.abs(intersection.w * intersection.h - rect.w * rect.h) < 0.001; } /** * Returns the union of this rectangle with another */ - getUnion(rect: Rectangle): any { + getUnion(rect: Rectangle) { if (this.isEmpty()) { // If this is rect is empty, return the other one return rect.clone(); @@ -241,16 +241,16 @@ export class Rectangle { return this.clone(); } // Find contained area - const left: any = Math.min(this.x, rect.x); - const top: any = Math.min(this.y, rect.y); - const right: any = Math.max(this.right(), rect.right()); - const bottom: any = Math.max(this.bottom(), rect.bottom()); + const left = Math.min(this.x, rect.x); + const top = Math.min(this.y, rect.y); + const right = Math.max(this.right(), rect.right()); + const bottom = Math.max(this.bottom(), rect.bottom()); return Rectangle.fromTRBL(top, right, bottom, left); } /** * Good for caching stuff */ - toCompareableString(): any { + toCompareableString() { return (round2Digits(this.x) + "/" + round2Digits(this.y) + @@ -262,7 +262,7 @@ export class Rectangle { /** * Good for printing stuff */ - toString(): any { + toString() { return ("[x:" + round2Digits(this.x) + "| y:" + diff --git a/src/ts/core/request_channel.ts b/src/ts/core/request_channel.ts index 86ff84d7..e59f6dc5 100644 --- a/src/ts/core/request_channel.ts +++ b/src/ts/core/request_channel.ts @@ -1,8 +1,8 @@ import { createLogger } from "./logging"; import { fastArrayDeleteValueIfContained } from "./utils"; -const logger: any = createLogger("request_channel"); +const logger = createLogger("request_channel"); // Thrown when a request is aborted -export const PROMISE_ABORTED: any = "promise-aborted"; +export const PROMISE_ABORTED = "promise-aborted"; export class RequestChannel { public pendingPromises: Array = []; @@ -14,9 +14,9 @@ export class RequestChannel { */ watch(promise: Promise): Promise { // log(this, "Added new promise:", promise, "(pending =", this.pendingPromises.length, ")"); - let cancelled: any = false; - const wrappedPromise: any = new Promise((resolve: any, reject: any): any => { - promise.then((result: any): any => { + let cancelled = false; + const wrappedPromise = new Promise((resolve, reject) => { + promise.then(result => { // Remove from pending promises fastArrayDeleteValueIfContained(this.pendingPromises, wrappedPromise); // If not cancelled, resolve promise with same payload @@ -27,7 +27,7 @@ export class RequestChannel { logger.warn("Not resolving because promise got cancelled"); // reject.call(this, PROMISE_ABORTED); } - }, (err: any): any => { + }, err => { // Remove from pending promises fastArrayDeleteValueIfContained(this.pendingPromises, wrappedPromise); // If not cancelled, reject promise with same payload @@ -42,17 +42,17 @@ export class RequestChannel { }); // Add cancel handler // @ts-ignore - wrappedPromise.cancel = function (): any { + wrappedPromise.cancel = function () { cancelled = true; }; this.pendingPromises.push(wrappedPromise); return wrappedPromise; } - cancelAll(): any { + cancelAll() { if (this.pendingPromises.length > 0) { logger.log("Cancel all pending promises (", this.pendingPromises.length, ")"); } - for (let i: any = 0; i < this.pendingPromises.length; ++i) { + for (let i = 0; i < this.pendingPromises.length; ++i) { // @ts-ignore this.pendingPromises[i].cancel(); } diff --git a/src/ts/core/restriction_manager.ts b/src/ts/core/restriction_manager.ts index d7cbb580..9fe9db31 100644 --- a/src/ts/core/restriction_manager.ts +++ b/src/ts/core/restriction_manager.ts @@ -11,23 +11,23 @@ export class RestrictionManager extends ReadWriteProxy { super(app, "restriction-flags.bin"); } // -- RW Proxy Impl - verify(data: any): any { + verify(data: any) { return ExplainedResult.good(); } - getDefaultData(): any { + getDefaultData() { return { version: this.getCurrentVersion(), }; } - getCurrentVersion(): any { + getCurrentVersion() { return 1; } - migrate(data: any): any { + migrate(data: any) { return ExplainedResult.good(); } - initialize(): any { + initialize() { return this.readAsync(); } // -- End RW Proxy Impl diff --git a/src/ts/core/rng.ts b/src/ts/core/rng.ts index 86419dbd..b9932c14 100644 --- a/src/ts/core/rng.ts +++ b/src/ts/core/rng.ts @@ -1,11 +1,11 @@ // ALEA RNG -function Mash(): any { - var n: any = 0xefc8249d; - return function (data: any): any { +function Mash() { + var n = 0xefc8249d; + return function (data) { data = data.toString(); - for (var i: any = 0; i < data.length; i++) { + for (var i = 0; i < data.length; i++) { n += data.charCodeAt(i); - var h: any = 0.02519603282416938 * n; + var h = 0.02519603282416938 * n; n = h >>> 0; h -= n; h *= n; @@ -16,13 +16,13 @@ function Mash(): any { return (n >>> 0) * 2.3283064365386963e-10; // 2^-32 }; } -function makeNewRng(seed: number | string): any { +function makeNewRng(seed: number | string) { // Johannes Baagøe , 2010 - var c: any = 1; - var mash: any = Mash(); - let s0: any = mash(" "); - let s1: any = mash(" "); - let s2: any = mash(" "); + var c = 1; + var mash = Mash(); + let s0 = mash(" "); + let s1 = mash(" "); + let s2 = mash(" "); s0 -= mash(seed); if (s0 < 0) { s0 += 1; @@ -36,16 +36,16 @@ function makeNewRng(seed: number | string): any { s2 += 1; } mash = null; - var random: any = function (): any { - var t: any = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32 + var random = function () { + var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32 s0 = s1; s1 = s2; return (s2 = t - (c = t | 0)); }; - random.exportState = function (): any { + random.exportState = function () { return [s0, s1, s2, c]; }; - random.importState = function (i: any): any { + random.importState = function (i) { s0 = +i[0] || 0; s1 = +i[1] || 0; s2 = +i[2] || 0; @@ -61,7 +61,7 @@ export class RandomNumberGenerator { /** * Re-seeds the generator */ - reseed(seed: number | string): any { + reseed(seed: number | string) { this.internalRng = makeNewRng(seed || Math.random()); } /** @@ -73,8 +73,8 @@ export class RandomNumberGenerator { /** * Random choice of an array */ - choice(array: array): any { - const index: any = this.nextIntRange(0, array.length); + choice(array: array) { + const index = this.nextIntRange(0, array.length); return array[index]; } /** @@ -96,7 +96,7 @@ export class RandomNumberGenerator { /** * Updates the seed */ - setSeed(seed: number): any { + setSeed(seed: number) { this.internalRng = makeNewRng(seed); } } diff --git a/src/ts/core/sensitive_utils.encrypt.ts b/src/ts/core/sensitive_utils.encrypt.ts index 9bb4a77c..2d0d8915 100644 --- a/src/ts/core/sensitive_utils.encrypt.ts +++ b/src/ts/core/sensitive_utils.encrypt.ts @@ -1,18 +1,18 @@ import { createHash } from "rusha"; import crc32 from "crc/crc32"; import { decompressX64 } from "./lzstring"; -export function sha1(str: any): any { +export function sha1(str) { return createHash().update(str).digest("hex"); } // Window.location.host -export function getNameOfProvider(): any { +export function getNameOfProvider() { return window[decompressX64("DYewxghgLgliB2Q")][decompressX64("BYewzgLgdghgtgUyA")]; } // Distinguish legacy crc prefixes -export const CRC_PREFIX: any = "crc32".padEnd(32, "-"); +export const CRC_PREFIX = "crc32".padEnd(32, "-"); /** * Computes the crc for a given string */ -export function computeCrc(str: string): any { +export function computeCrc(str: string) { return CRC_PREFIX + crc32(str).toString(16).padStart(8, "0"); } diff --git a/src/ts/core/signal.ts b/src/ts/core/signal.ts index 1208a0ef..70c05cac 100644 --- a/src/ts/core/signal.ts +++ b/src/ts/core/signal.ts @@ -1,4 +1,4 @@ -export const STOP_PROPAGATION: any = "stop_propagation"; +export const STOP_PROPAGATION = "stop_propagation"; export class Signal { public receivers = []; public modifyCount = 0; @@ -8,7 +8,7 @@ export class Signal { /** * Adds a new signal listener */ - add(receiver: function, scope: object = null): any { + add(receiver: function, scope: object = null) { assert(receiver, "receiver is null"); this.receivers.push({ receiver, scope }); ++this.modifyCount; @@ -16,7 +16,7 @@ export class Signal { /** * Adds a new signal listener */ - addToTop(receiver: function, scope: object = null): any { + addToTop(receiver: function, scope: object = null) { assert(receiver, "receiver is null"); this.receivers.unshift({ receiver, scope }); ++this.modifyCount; @@ -25,11 +25,11 @@ export class Signal { * Dispatches the signal * @param {} payload */ - dispatch(): any { - const modifyState: any = this.modifyCount; - const n: any = this.receivers.length; - for (let i: any = 0; i < n; ++i) { - const { receiver, scope }: any = this.receivers[i]; + dispatch() { + const modifyState = this.modifyCount; + const n = this.receivers.length; + for (let i = 0; i < n; ++i) { + const { receiver, scope } = this.receivers[i]; if (receiver.apply(scope, arguments) === STOP_PROPAGATION) { return STOP_PROPAGATION; } @@ -42,10 +42,10 @@ export class Signal { /** * Removes a receiver */ - remove(receiver: function): any { - let index: any = null; - const n: any = this.receivers.length; - for (let i: any = 0; i < n; ++i) { + remove(receiver: function) { + let index = null; + const n = this.receivers.length; + for (let i = 0; i < n; ++i) { if (this.receivers[i].receiver === receiver) { index = i; break; @@ -58,7 +58,7 @@ export class Signal { /** * Removes all receivers */ - removeAll(): any { + removeAll() { this.receivers = []; ++this.modifyCount; } diff --git a/src/ts/core/singleton_factory.ts b/src/ts/core/singleton_factory.ts index 266801e5..0b6fc192 100644 --- a/src/ts/core/singleton_factory.ts +++ b/src/ts/core/singleton_factory.ts @@ -1,5 +1,5 @@ import { createLogger } from "./logging"; -const logger: any = createLogger("singleton_factory"); +const logger = createLogger("singleton_factory"); // simple factory pattern export class SingletonFactory { public id = id; @@ -8,14 +8,14 @@ export class SingletonFactory { constructor(id) { } - getId(): any { + getId() { return this.id; } - register(classHandle: any): any { + register(classHandle) { // First, construct instance - const instance: any = new classHandle(); + const instance = new classHandle(); // Extract id - const id: any = instance.getId(); + const id = instance.getId(); assert(id, "Factory: Invalid id for class " + classHandle.name + ": " + id); // Check duplicates assert(!this.idToEntry[id], "Duplicate factory entry for " + id); @@ -35,7 +35,7 @@ export class SingletonFactory { * {} */ findById(id: string): object { - const entry: any = this.idToEntry[id]; + const entry = this.idToEntry[id]; if (!entry) { logger.error("Object with id", id, "is not registered!"); assert(false, "Factory: Object with id '" + id + "' is not registered!"); @@ -49,7 +49,7 @@ export class SingletonFactory { * {} */ findByClass(classHandle: object): object { - for (let i: any = 0; i < this.entries.length; ++i) { + for (let i = 0; i < this.entries.length; ++i) { if (this.entries[i] instanceof classHandle) { return this.entries[i]; } diff --git a/src/ts/core/sprites.ts b/src/ts/core/sprites.ts index d76e3464..0f08dfe0 100644 --- a/src/ts/core/sprites.ts +++ b/src/ts/core/sprites.ts @@ -1,9 +1,9 @@ import { DrawParameters } from "./draw_parameters"; import { Rectangle } from "./rectangle"; import { round3Digits } from "./utils"; -export const ORIGINAL_SPRITE_SCALE: any = "0.75"; -export const FULL_CLIP_RECT: any = new Rectangle(0, 0, 1, 1); -const EXTRUDE: any = 0.1; +export const ORIGINAL_SPRITE_SCALE = "0.75"; +export const FULL_CLIP_RECT = new Rectangle(0, 0, 1, 1); +const EXTRUDE = 0.1; export class BaseSprite { /** * Returns the raw handle @@ -17,7 +17,7 @@ export class BaseSprite { /** * Draws the sprite */ - draw(context: CanvasRenderingContext2D, x: number, y: number, w: number, h: number): any { + draw(context: CanvasRenderingContext2D, x: number, y: number, w: number, h: number) { // eslint-disable-line no-unused-vars abstract; } @@ -49,18 +49,18 @@ export class AtlasSprite extends BaseSprite { constructor(spriteName = "sprite") { super(); } - getRawTexture(): any { + getRawTexture() { return this.linksByResolution[ORIGINAL_SPRITE_SCALE].atlas; } /** * Draws the sprite onto a regular context using no contexts * @see {BaseSprite.draw} */ - draw(context: any, x: any, y: any, w: any, h: any): any { + draw(context, x, y, w, h) { if (G_IS_DEV) { assert(context instanceof CanvasRenderingContext2D, "Not a valid context"); } - const link: any = this.linksByResolution[ORIGINAL_SPRITE_SCALE]; + const link = this.linksByResolution[ORIGINAL_SPRITE_SCALE]; if (!link) { throw new Error("draw: Link for " + this.spriteName + @@ -70,30 +70,30 @@ export class AtlasSprite extends BaseSprite { Object.keys(this.linksByResolution) + ")"); } - const width: any = w || link.w; - const height: any = h || link.h; - const scaleW: any = width / link.w; - const scaleH: any = height / link.h; + const width = w || link.w; + const height = h || link.h; + const scaleW = width / link.w; + const scaleH = height / link.h; context.drawImage(link.atlas, link.packedX, link.packedY, link.packedW, link.packedH, x + link.packOffsetX * scaleW, y + link.packOffsetY * scaleH, link.packedW * scaleW, link.packedH * scaleH); } - drawCachedCentered(parameters: DrawParameters, x: number, y: number, size: number, clipping: boolean= = true): any { + drawCachedCentered(parameters: DrawParameters, x: number, y: number, size: number, clipping: boolean= = true) { this.drawCached(parameters, x - size / 2, y - size / 2, size, size, clipping); } - drawCentered(context: CanvasRenderingContext2D, x: number, y: number, size: number): any { + drawCentered(context: CanvasRenderingContext2D, x: number, y: number, size: number) { this.draw(context, x - size / 2, y - size / 2, size, size); } /** * Draws the sprite */ - drawCached(parameters: DrawParameters, x: number, y: number, w: number = null, h: number = null, clipping: boolean= = true): any { + drawCached(parameters: DrawParameters, x: number, y: number, w: number = null, h: number = null, clipping: boolean= = true) { if (G_IS_DEV) { assert(parameters instanceof DrawParameters, "Not a valid context"); assert(!!w && w > 0, "Not a valid width:" + w); assert(!!h && h > 0, "Not a valid height:" + h); } - const visibleRect: any = parameters.visibleRect; - const scale: any = parameters.desiredAtlasScale; - const link: any = this.linksByResolution[scale]; + const visibleRect = parameters.visibleRect; + const scale = parameters.desiredAtlasScale; + const link = this.linksByResolution[scale]; if (!link) { throw new Error("drawCached: Link for " + this.spriteName + @@ -103,19 +103,19 @@ export class AtlasSprite extends BaseSprite { Object.keys(this.linksByResolution) + ")"); } - const scaleW: any = w / link.w; - const scaleH: any = h / link.h; - let destX: any = x + link.packOffsetX * scaleW; - let destY: any = y + link.packOffsetY * scaleH; - let destW: any = link.packedW * scaleW; - let destH: any = link.packedH * scaleH; - let srcX: any = link.packedX; - let srcY: any = link.packedY; - let srcW: any = link.packedW; - let srcH: any = link.packedH; - let intersection: any = null; + const scaleW = w / link.w; + const scaleH = h / link.h; + let destX = x + link.packOffsetX * scaleW; + let destY = y + link.packOffsetY * scaleH; + let destW = link.packedW * scaleW; + let destH = link.packedH * scaleH; + let srcX = link.packedX; + let srcY = link.packedY; + let srcW = link.packedW; + let srcH = link.packedH; + let intersection = null; if (clipping) { - const rect: any = new Rectangle(destX, destY, destW, destH); + const rect = new Rectangle(destX, destY, destW, destH); intersection = rect.getIntersection(visibleRect); if (!intersection) { return; @@ -140,15 +140,15 @@ export class AtlasSprite extends BaseSprite { /** * Draws a subset of the sprite. Does NO culling */ - drawCachedWithClipRect(parameters: DrawParameters, x: number, y: number, w: number = null, h: number = null, clipRect: Rectangle= = FULL_CLIP_RECT): any { + drawCachedWithClipRect(parameters: DrawParameters, x: number, y: number, w: number = null, h: number = null, clipRect: Rectangle= = FULL_CLIP_RECT) { if (G_IS_DEV) { assert(parameters instanceof DrawParameters, "Not a valid context"); assert(!!w && w > 0, "Not a valid width:" + w); assert(!!h && h > 0, "Not a valid height:" + h); assert(clipRect, "No clip rect given!"); } - const scale: any = parameters.desiredAtlasScale; - const link: any = this.linksByResolution[scale]; + const scale = parameters.desiredAtlasScale; + const link = this.linksByResolution[scale]; if (!link) { throw new Error("drawCachedWithClipRect: Link for " + this.spriteName + @@ -158,16 +158,16 @@ export class AtlasSprite extends BaseSprite { Object.keys(this.linksByResolution) + ")"); } - const scaleW: any = w / link.w; - const scaleH: any = h / link.h; - let destX: any = x + link.packOffsetX * scaleW + clipRect.x * w; - let destY: any = y + link.packOffsetY * scaleH + clipRect.y * h; - let destW: any = link.packedW * scaleW * clipRect.w; - let destH: any = link.packedH * scaleH * clipRect.h; - let srcX: any = link.packedX + clipRect.x * link.packedW; - let srcY: any = link.packedY + clipRect.y * link.packedH; - let srcW: any = link.packedW * clipRect.w; - let srcH: any = link.packedH * clipRect.h; + const scaleW = w / link.w; + const scaleH = h / link.h; + let destX = x + link.packOffsetX * scaleW + clipRect.x * w; + let destY = y + link.packOffsetY * scaleH + clipRect.y * h; + let destW = link.packedW * scaleW * clipRect.w; + let destH = link.packedH * scaleH * clipRect.h; + let srcX = link.packedX + clipRect.x * link.packedW; + let srcY = link.packedY + clipRect.y * link.packedH; + let srcW = link.packedW * clipRect.w; + let srcH = link.packedH * clipRect.h; parameters.context.drawImage(link.atlas, // atlas src pos srcX, srcY, @@ -179,15 +179,15 @@ export class AtlasSprite extends BaseSprite { /** * Renders into an html element */ - renderToHTMLElement(element: HTMLElement, w: number = 1, h: number = 1): any { + renderToHTMLElement(element: HTMLElement, w: number = 1, h: number = 1) { element.style.position = "relative"; element.innerHTML = this.getAsHTML(w, h); } /** * Returns the html to render as icon */ - getAsHTML(w: number, h: number): any { - const link: any = this.linksByResolution["0.5"]; + getAsHTML(w: number, h: number) { + const link = this.linksByResolution["0.5"]; if (!link) { throw new Error("getAsHTML: Link for " + this.spriteName + @@ -197,30 +197,30 @@ export class AtlasSprite extends BaseSprite { ")"); } // Find out how much we have to scale it so that it fits - const scaleX: any = w / link.w; - const scaleY: any = h / link.h; + const scaleX = w / link.w; + const scaleY = h / link.h; // Find out how big the scaled atlas is - const atlasW: any = link.atlas.width * scaleX; - const atlasH: any = link.atlas.height * scaleY; + const atlasW = link.atlas.width * scaleX; + const atlasH = link.atlas.height * scaleY; // @ts-ignore - const srcSafe: any = link.atlas.src.replaceAll("\\", "/"); + const srcSafe = link.atlas.src.replaceAll("\\", "/"); // Find out how big we render the sprite - const widthAbsolute: any = scaleX * link.packedW; - const heightAbsolute: any = scaleY * link.packedH; + const widthAbsolute = scaleX * link.packedW; + const heightAbsolute = scaleY * link.packedH; // Compute the position in the relative container - const leftRelative: any = (link.packOffsetX * scaleX) / w; - const topRelative: any = (link.packOffsetY * scaleY) / h; - const widthRelative: any = widthAbsolute / w; - const heightRelative: any = heightAbsolute / h; + const leftRelative = (link.packOffsetX * scaleX) / w; + const topRelative = (link.packOffsetY * scaleY) / h; + const widthRelative = widthAbsolute / w; + const heightRelative = heightAbsolute / h; // Scale the atlas relative to the width and height of the element - const bgW: any = atlasW / widthAbsolute; - const bgH: any = atlasH / heightAbsolute; + const bgW = atlasW / widthAbsolute; + const bgH = atlasH / heightAbsolute; // Figure out what the position of the atlas is - const bgX: any = link.packedX * scaleX; - const bgY: any = link.packedY * scaleY; + const bgX = link.packedX * scaleX; + const bgY = link.packedY * scaleY; // Fuck you, whoever thought its a good idea to make background-position work like it does now - const bgXRelative: any = -bgX / (widthAbsolute - atlasW); - const bgYRelative: any = -bgY / (heightAbsolute - atlasH); + const bgXRelative = -bgX / (widthAbsolute - atlasW); + const bgYRelative = -bgY / (heightAbsolute - atlasH); return ` , tilesAround: number): any { - const componentIds: any = components.map((component: any): any => component.getId()); + recomputeOnComponentsChanged(components: Array, tilesAround: number) { + const componentIds = components.map(component => component.getId()); /** * Internal checker method */ - const checker: any = (entity: Entity): any => { + const checker = (entity: Entity) => { if (!this.root.gameInitialized) { return; } // Check for all components - for (let i: any = 0; i < componentIds.length; ++i) { + for (let i = 0; i < componentIds.length; ++i) { if (entity.components[componentIds[i]]) { // Entity is relevant, compute affected area - const area: any = entity.components.StaticMapEntity.getTileSpaceBounds().expandedInAllDirections(tilesAround); + const area = entity.components.StaticMapEntity.getTileSpaceBounds().expandedInAllDirections(tilesAround); this.invalidate(area); return; } @@ -56,7 +56,7 @@ export class StaleAreaDetector { /** * Updates the stale area */ - update(): any { + update() { if (this.staleArea) { if (G_IS_DEV && globalConfig.debug.renderChanges) { logger.log(this.name, "is recomputing", this.staleArea.toString()); diff --git a/src/ts/core/state_manager.ts b/src/ts/core/state_manager.ts index a4d9826e..28a4b60a 100644 --- a/src/ts/core/state_manager.ts +++ b/src/ts/core/state_manager.ts @@ -5,7 +5,7 @@ import { GameState } from "./game_state"; import { createLogger } from "./logging"; import { waitNextFrame, removeAllChildren } from "./utils"; import { MOD_SIGNALS } from "../mods/mod_signals"; -const logger: any = createLogger("state_manager"); +const logger = createLogger("state_manager"); /** * This is the main state machine which drives the game states. */ @@ -21,18 +21,18 @@ export class StateManager { /** * Registers a new state class, should be a GameState derived class */ - register(stateClass: object): any { + register(stateClass: object) { // Create a dummy to retrieve the key - const dummy: any = new stateClass(); + const dummy = new stateClass(); assert(dummy instanceof GameState, "Not a state!"); - const key: any = dummy.getKey(); + const key = dummy.getKey(); assert(!this.stateClasses[key], `State '${key}' is already registered!`); this.stateClasses[key] = stateClass; } /** * Constructs a new state or returns the instance from the cache */ - constructState(key: string): any { + constructState(key: string) { if (this.stateClasses[key]) { return new this.stateClasses[key](); } @@ -41,7 +41,7 @@ export class StateManager { /** * Moves to a given state */ - moveToState(key: string, payload: any = {}): any { + moveToState(key: string, payload = {}) { if (window.APP_ERROR_OCCURED) { console.warn("Skipping state transition because of application crash"); return; @@ -53,7 +53,7 @@ export class StateManager { } this.currentState.internalLeaveCallback(); // Remove all references - for (const stateKey: any in this.currentState) { + for (const stateKey in this.currentState) { if (this.currentState.hasOwnProperty(stateKey)) { delete this.currentState[stateKey]; } @@ -71,13 +71,13 @@ export class StateManager { if (this.currentState.getRemovePreviousContent()) { document.body.innerHTML = this.currentState.internalGetFullHtml(); } - const dialogParent: any = document.createElement("div"); + const dialogParent = document.createElement("div"); dialogParent.classList.add("modalDialogParent"); document.body.appendChild(dialogParent); try { this.currentState.internalEnterCallback(payload); } - catch (ex: any) { + catch (ex) { console.error(ex); throw ex; } @@ -88,7 +88,7 @@ export class StateManager { key, }, key); MOD_SIGNALS.stateEntered.dispatch(this.currentState); - waitNextFrame().then((): any => { + waitNextFrame().then(() => { document.body.classList.add("arrived"); }); return true; diff --git a/src/ts/core/steam_sso.ts b/src/ts/core/steam_sso.ts index 6a3b0e57..26a1aabb 100644 --- a/src/ts/core/steam_sso.ts +++ b/src/ts/core/steam_sso.ts @@ -1,45 +1,45 @@ import { T } from "../translations"; import { openStandaloneLink } from "./config"; -export let WEB_STEAM_SSO_AUTHENTICATED: any = false; -export async function authorizeViaSSOToken(app: any, dialogs: any): any { +export let WEB_STEAM_SSO_AUTHENTICATED = false; +export async function authorizeViaSSOToken(app, dialogs) { if (G_IS_STANDALONE) { return; } if (window.location.search.includes("sso_logout_silent")) { window.localStorage.setItem("steam_sso_auth_token", ""); window.location.replace("/"); - return new Promise((): any => null); + return new Promise(() => null); } if (window.location.search.includes("sso_logout")) { - const { ok }: any = dialogs.showWarning(T.dialogs.steamSsoError.title, T.dialogs.steamSsoError.desc); + const { ok } = dialogs.showWarning(T.dialogs.steamSsoError.title, T.dialogs.steamSsoError.desc); window.localStorage.setItem("steam_sso_auth_token", ""); - ok.add((): any => window.location.replace("/")); - return new Promise((): any => null); + ok.add(() => window.location.replace("/")); + return new Promise(() => null); } if (window.location.search.includes("steam_sso_no_ownership")) { - const { ok, getStandalone }: any = dialogs.showWarning(T.dialogs.steamSsoNoOwnership.title, T.dialogs.steamSsoNoOwnership.desc, ["ok", "getStandalone:good"]); + const { ok, getStandalone } = dialogs.showWarning(T.dialogs.steamSsoNoOwnership.title, T.dialogs.steamSsoNoOwnership.desc, ["ok", "getStandalone:good"]); window.localStorage.setItem("steam_sso_auth_token", ""); - getStandalone.add((): any => { + getStandalone.add(() => { openStandaloneLink(app, "sso_ownership"); window.location.replace("/"); }); - ok.add((): any => window.location.replace("/")); - return new Promise((): any => null); + ok.add(() => window.location.replace("/")); + return new Promise(() => null); } - const token: any = window.localStorage.getItem("steam_sso_auth_token"); + const token = window.localStorage.getItem("steam_sso_auth_token"); if (!token) { return Promise.resolve(); } - const apiUrl: any = app.clientApi.getEndpoint(); + const apiUrl = app.clientApi.getEndpoint(); console.warn("Authorizing via token:", token); - const verify: any = async (): any => { - const token: any = window.localStorage.getItem("steam_sso_auth_token"); + const verify = async () => { + const token = window.localStorage.getItem("steam_sso_auth_token"); if (!token) { window.location.replace("?sso_logout"); return; } try { - const response: any = await Promise.race([ + const response = await Promise.race([ fetch(apiUrl + "/v1/sso/refresh", { method: "POST", body: token, @@ -47,11 +47,11 @@ export async function authorizeViaSSOToken(app: any, dialogs: any): any { "x-api-key": "d5c54aaa491f200709afff082c153ef2", }, }), - new Promise((resolve: any, reject: any): any => { - setTimeout((): any => reject("timeout exceeded"), 20000); + new Promise((resolve, reject) => { + setTimeout(() => reject("timeout exceeded"), 20000); }), ]); - const responseText: any = await response.json(); + const responseText = await response.json(); if (!responseText.token) { console.warn("Failed to register"); window.localStorage.setItem("steam_sso_auth_token", ""); @@ -62,11 +62,11 @@ export async function authorizeViaSSOToken(app: any, dialogs: any): any { app.clientApi.token = responseText.token; WEB_STEAM_SSO_AUTHENTICATED = true; } - catch (ex: any) { + catch (ex) { console.warn("Auth failure", ex); window.localStorage.setItem("steam_sso_auth_token", ""); window.location.replace("/"); - return new Promise((): any => null); + return new Promise(() => null); } }; await verify(); diff --git a/src/ts/core/textual_game_state.ts b/src/ts/core/textual_game_state.ts index 7796e232..32595b62 100644 --- a/src/ts/core/textual_game_state.ts +++ b/src/ts/core/textual_game_state.ts @@ -22,7 +22,7 @@ export class TextualGameState extends GameState { /** * Should return the states HTML content. */ - getMainContentHTML(): any { + getMainContentHTML() { return ""; } /** @@ -38,7 +38,7 @@ export class TextualGameState extends GameState { * Back button handler, can be overridden. Per default it goes back to the main menu, * or if coming from the game it moves back to the game again. */ - onBackButton(): any { + onBackButton() { if (this.backToStateId) { this.moveToState(this.backToStateId, this.backToStatePayload); } @@ -49,13 +49,13 @@ export class TextualGameState extends GameState { /** * Returns the default state to go back to */ - getDefaultPreviousState(): any { + getDefaultPreviousState() { return "MainMenuState"; } /** * Goes to a new state, telling him to go back to this state later */ - moveToStateAddGoBack(stateId: string): any { + moveToStateAddGoBack(stateId: string) { this.moveToState(stateId, { backToStateId: this.key, backToStatePayload: { @@ -68,9 +68,9 @@ export class TextualGameState extends GameState { * Removes all click detectors, except the one on the back button. Useful when regenerating * content. */ - clearClickDetectorsExceptHeader(): any { - for (let i: any = 0; i < this.clickDetectors.length; ++i) { - const detector: any = this.clickDetectors[i]; + clearClickDetectorsExceptHeader() { + for (let i = 0; i < this.clickDetectors.length; ++i) { + const detector = this.clickDetectors[i]; if (detector.element === this.headerElement) { continue; } @@ -82,8 +82,8 @@ export class TextualGameState extends GameState { /** * Overrides the GameState implementation to provide our own html */ - internalGetFullHtml(): any { - let headerHtml: any = ""; + internalGetFullHtml() { + let headerHtml = ""; if (this.getStateHeaderTitle()) { headerHtml = `
@@ -103,14 +103,14 @@ export class TextualGameState extends GameState { /** * Overrides the GameState leave callback to cleanup stuff */ - internalLeaveCallback(): any { + internalLeaveCallback() { super.internalLeaveCallback(); this.dialogs.cleanup(); } /** * Overrides the GameState enter callback to setup required stuff */ - internalEnterCallback(payload: any): any { + internalEnterCallback(payload: any) { super.internalEnterCallback(payload, false); if (payload.backToStateId) { this.backToStateId = payload.backToStateId; @@ -126,7 +126,7 @@ export class TextualGameState extends GameState { this.trackClicks(this.headerElement, this.onBackButton); } this.dialogs = new HUDModalDialogs(null, this.app); - const dialogsElement: any = document.body.querySelector(".modalDialogParent"); + const dialogsElement = document.body.querySelector(".modalDialogParent"); this.dialogs.initializeToElement(dialogsElement); this.onEnter(payload); } diff --git a/src/ts/core/tracked_state.ts b/src/ts/core/tracked_state.ts index f01ef05d..7e9cc072 100644 --- a/src/ts/core/tracked_state.ts +++ b/src/ts/core/tracked_state.ts @@ -9,10 +9,10 @@ export class TrackedState { } } } - set(value: any, changeHandler: any = null, changeScope: any = null): any { + set(value, changeHandler = null, changeScope = null) { if (value !== this.lastSeenValue) { // Copy value since the changeHandler call could actually modify our lastSeenValue - const valueCopy: any = value; + const valueCopy = value; this.lastSeenValue = value; if (changeHandler) { if (changeScope) { @@ -30,10 +30,10 @@ export class TrackedState { } } } - setSilent(value: any): any { + setSilent(value) { this.lastSeenValue = value; } - get(): any { + get() { return this.lastSeenValue; } } diff --git a/src/ts/core/utils.ts b/src/ts/core/utils.ts index a871d91a..7b27b24d 100644 --- a/src/ts/core/utils.ts +++ b/src/ts/core/utils.ts @@ -1,7 +1,7 @@ import { T } from "../translations"; import { rando } from "@nastyox/rando.js"; import { WEB_STEAM_SSO_AUTHENTICATED } from "./steam_sso"; -const bigNumberSuffixTranslationKeys: any = ["thousands", "millions", "billions", "trillions"]; +const bigNumberSuffixTranslationKeys = ["thousands", "millions", "billions", "trillions"]; /** * Returns a platform name * {} @@ -20,8 +20,8 @@ export function getPlatformName(): "android" | "browser" | "ios" | "standalone" * {} */ export function make2DUndefinedArray(w: number, h: number): Array> { - const result: any = new Array(w); - for (let x: any = 0; x < w; ++x) { + const result = new Array(w); + for (let x = 0; x < w; ++x) { result[x] = new Array(h); } return result; @@ -29,21 +29,21 @@ export function make2DUndefinedArray(w: number, h: number): Array> { /** * Creates a new map (an empty object without any props) */ -export function newEmptyMap(): any { +export function newEmptyMap() { return Object.create(null); } /** * Returns a random integer in the range [start,end] */ -export function randomInt(start: number, end: number): any { +export function randomInt(start: number, end: number) { return rando(start, end); } /** * Access an object in a very annoying way, used for obsfuscation. */ -export function accessNestedPropertyReverse(obj: any, keys: Array): any { - let result: any = obj; - for (let i: any = keys.length - 1; i >= 0; --i) { +export function accessNestedPropertyReverse(obj: any, keys: Array) { + let result = obj; + for (let i = keys.length - 1; i >= 0; --i) { result = result[keys[i]]; } return result; @@ -59,14 +59,14 @@ export function randomChoice(arr: T[]): T { /** * Deletes from an array by swapping with the last element */ -export function fastArrayDelete(array: Array, index: number): any { +export function fastArrayDelete(array: Array, index: number) { if (index < 0 || index >= array.length) { throw new Error("Out of bounds"); } // When the element is not the last element if (index !== array.length - 1) { // Get the last element, and swap it with the one we want to delete - const last: any = array[array.length - 1]; + const last = array[array.length - 1]; array[index] = last; } // Finally remove the last element @@ -76,11 +76,11 @@ export function fastArrayDelete(array: Array, index: number): any { * Deletes from an array by swapping with the last element. Searches * for the value in the array first */ -export function fastArrayDeleteValue(array: Array, value: any): any { +export function fastArrayDeleteValue(array: Array, value: any) { if (array == null) { throw new Error("Tried to delete from non array!"); } - const index: any = array.indexOf(value); + const index = array.indexOf(value); if (index < 0) { console.error("Value", value, "not contained in array:", array, "!"); return value; @@ -90,11 +90,11 @@ export function fastArrayDeleteValue(array: Array, value: any): any { /** * @see fastArrayDeleteValue */ -export function fastArrayDeleteValueIfContained(array: Array, value: any): any { +export function fastArrayDeleteValueIfContained(array: Array, value: any) { if (array == null) { throw new Error("Tried to delete from non array!"); } - const index: any = array.indexOf(value); + const index = array.indexOf(value); if (index < 0) { return value; } @@ -103,7 +103,7 @@ export function fastArrayDeleteValueIfContained(array: Array, value: any): /** * Deletes from an array at the given index */ -export function arrayDelete(array: Array, index: number): any { +export function arrayDelete(array: Array, index: number) { if (index < 0 || index >= array.length) { throw new Error("Out of bounds"); } @@ -112,11 +112,11 @@ export function arrayDelete(array: Array, index: number): any { /** * Deletes the given value from an array */ -export function arrayDeleteValue(array: Array, value: any): any { +export function arrayDeleteValue(array: Array, value: any) { if (array == null) { throw new Error("Tried to delete from non array!"); } - const index: any = array.indexOf(value); + const index = array.indexOf(value); if (index < 0) { console.error("Value", value, "not contained in array:", array, "!"); return value; @@ -127,26 +127,26 @@ export function arrayDeleteValue(array: Array, value: any): any { * Compare two floats for epsilon equality * {} */ -export function epsilonCompare(a: number, b: number, epsilon: any = 1e-5): boolean { +export function epsilonCompare(a: number, b: number, epsilon = 1e-5): boolean { return Math.abs(a - b) < epsilon; } /** * Interpolates two numbers */ -export function lerp(a: number, b: number, x: number): any { +export function lerp(a: number, b: number, x: number) { return a * (1 - x) + b * x; } /** * Finds a value which is nice to display, e.g. 15669 -> 15000. Also handles fractional stuff */ -export function findNiceValue(num: number): any { +export function findNiceValue(num: number) { if (num > 1e8) { return num; } if (num < 0.00001) { return 0; } - let roundAmount: any = 1; + let roundAmount = 1; if (num > 50000) { roundAmount = 10000; } @@ -168,7 +168,7 @@ export function findNiceValue(num: number): any { else if (num > 20) { roundAmount = 5; } - const niceValue: any = Math.floor(num / roundAmount) * roundAmount; + const niceValue = Math.floor(num / roundAmount) * roundAmount; if (num >= 10) { return Math.round(niceValue); } @@ -181,7 +181,7 @@ export function findNiceValue(num: number): any { * Finds a nice integer value * @see findNiceValue */ -export function findNiceIntegerValue(num: number): any { +export function findNiceIntegerValue(num: number) { return Math.ceil(findNiceValue(num)); } /** @@ -189,7 +189,7 @@ export function findNiceIntegerValue(num: number): any { * {} */ export function formatBigNumber(num: number, separator: string= = T.global.decimalSeparator): string { - const sign: any = num < 0 ? "-" : ""; + const sign = num < 0 ? "-" : ""; num = Math.abs(num); if (num > 1e54) { return sign + T.global.infinite; @@ -205,17 +205,17 @@ export function formatBigNumber(num: number, separator: string= = T.global.decim return sign + "" + num; } else { - let leadingDigits: any = num; - let suffix: any = ""; - for (let suffixIndex: any = 0; suffixIndex < bigNumberSuffixTranslationKeys.length; ++suffixIndex) { + let leadingDigits = num; + let suffix = ""; + for (let suffixIndex = 0; suffixIndex < bigNumberSuffixTranslationKeys.length; ++suffixIndex) { leadingDigits = leadingDigits / 1000; suffix = T.global.suffix[bigNumberSuffixTranslationKeys[suffixIndex]]; if (leadingDigits < 1000) { break; } } - const leadingDigitsRounded: any = round1Digit(leadingDigits); - const leadingDigitsNoTrailingDecimal: any = leadingDigitsRounded + const leadingDigitsRounded = round1Digit(leadingDigits); + const leadingDigitsNoTrailingDecimal = leadingDigitsRounded .toString() .replace(".0", "") .replace(".", separator); @@ -233,8 +233,8 @@ export function formatBigNumberFull(num: number, divider: string= = T.global.tho if (num > 1e54) { return T.global.infinite; } - let rest: any = num; - let out: any = ""; + let rest = num; + let out = ""; while (rest >= 1000) { out = (rest % 1000).toString().padStart(3, "0") + divider + out; rest = Math.floor(rest / 1000); @@ -247,9 +247,9 @@ export function formatBigNumberFull(num: number, divider: string= = T.global.tho * {} */ export function waitNextFrame(): Promise { - return new Promise(function (resolve: any): any { - window.requestAnimationFrame(function (): any { - window.requestAnimationFrame(function (): any { + return new Promise(function (resolve) { + window.requestAnimationFrame(function () { + window.requestAnimationFrame(function () { resolve(); }); }); @@ -286,18 +286,18 @@ export function round4Digits(n: number): number { /** * Clamps a value between [min, max] */ -export function clamp(v: number, minimum: number= = 0, maximum: number= = 1): any { +export function clamp(v: number, minimum: number= = 0, maximum: number= = 1) { return Math.max(minimum, Math.min(maximum, v)); } /** * Helper method to create a new div element */ -export function makeDivElement(id: string= = null, classes: Array= = [], innerHTML: string= = ""): any { - const div: any = document.createElement("div"); +export function makeDivElement(id: string= = null, classes: Array= = [], innerHTML: string= = "") { + const div = document.createElement("div"); if (id) { div.id = id; } - for (let i: any = 0; i < classes.length; ++i) { + for (let i = 0; i < classes.length; ++i) { div.classList.add(classes[i]); } div.innerHTML = innerHTML; @@ -306,17 +306,17 @@ export function makeDivElement(id: string= = null, classes: Array= = [], /** * Helper method to create a new div */ -export function makeDiv(parent: Element, id: string= = null, classes: Array= = [], innerHTML: string= = ""): any { - const div: any = makeDivElement(id, classes, innerHTML); +export function makeDiv(parent: Element, id: string= = null, classes: Array= = [], innerHTML: string= = "") { + const div = makeDivElement(id, classes, innerHTML); parent.appendChild(div); return div; } /** * Helper method to create a new button element */ -export function makeButtonElement(classes: Array= = [], innerHTML: string= = ""): any { - const element: any = document.createElement("button"); - for (let i: any = 0; i < classes.length; ++i) { +export function makeButtonElement(classes: Array= = [], innerHTML: string= = "") { + const element = document.createElement("button"); + for (let i = 0; i < classes.length; ++i) { element.classList.add(classes[i]); } element.classList.add("styledButton"); @@ -326,17 +326,17 @@ export function makeButtonElement(classes: Array= = [], innerHTML: strin /** * Helper method to create a new button */ -export function makeButton(parent: Element, classes: Array= = [], innerHTML: string= = ""): any { - const element: any = makeButtonElement(classes, innerHTML); +export function makeButton(parent: Element, classes: Array= = [], innerHTML: string= = "") { + const element = makeButtonElement(classes, innerHTML); parent.appendChild(element); return element; } /** * Removes all children of the given element */ -export function removeAllChildren(elem: Element): any { +export function removeAllChildren(elem: Element) { if (elem) { - var range: any = document.createRange(); + var range = document.createRange(); range.selectNodeContents(elem); range.deleteContents(); } @@ -344,7 +344,7 @@ export function removeAllChildren(elem: Element): any { /** * Returns if the game supports this browser */ -export function isSupportedBrowser(): any { +export function isSupportedBrowser() { // please note, // that IE11 now returns undefined again for window.chrome // and new Opera 30 outputs true for window.chrome @@ -356,12 +356,12 @@ export function isSupportedBrowser(): any { return true; } // @ts-ignore - var isChromium: any = window.chrome; - var winNav: any = window.navigator; - var vendorName: any = winNav.vendor; + var isChromium = window.chrome; + var winNav = window.navigator; + var vendorName = winNav.vendor; // @ts-ignore - var isIEedge: any = winNav.userAgent.indexOf("Edge") > -1; - var isIOSChrome: any = winNav.userAgent.match("CriOS"); + var isIEedge = winNav.userAgent.indexOf("Edge") > -1; + var isIOSChrome = winNav.userAgent.match("CriOS"); if (isIOSChrome) { // is Google Chrome on IOS return false; @@ -383,10 +383,10 @@ export function isSupportedBrowser(): any { * {} */ export function formatSecondsToTimeAgo(secs: number): string { - const seconds: any = Math.floor(secs); - const minutes: any = Math.floor(seconds / 60); - const hours: any = Math.floor(minutes / 60); - const days: any = Math.floor(hours / 24); + const seconds = Math.floor(secs); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); if (seconds < 60) { if (seconds === 1) { return T.global.time.oneSecondAgo; @@ -417,34 +417,34 @@ export function formatSecondsToTimeAgo(secs: number): string { * {} */ export function formatSeconds(secs: number): string { - const trans: any = T.global.time; + const trans = T.global.time; secs = Math.ceil(secs); if (secs < 60) { return trans.secondsShort.replace("", "" + secs); } else if (secs < 60 * 60) { - const minutes: any = Math.floor(secs / 60); - const seconds: any = secs % 60; + const minutes = Math.floor(secs / 60); + const seconds = secs % 60; return trans.minutesAndSecondsShort .replace("", "" + seconds) .replace("", "" + minutes); } else { - const hours: any = Math.floor(secs / 3600); - const minutes: any = Math.floor(secs / 60) % 60; + const hours = Math.floor(secs / 3600); + const minutes = Math.floor(secs / 60) % 60; return trans.hoursAndMinutesShort.replace("", "" + minutes).replace("", "" + hours); } } /** * Formats a number like 2.51 to "2.5" */ -export function round1DigitLocalized(speed: number, separator: string= = T.global.decimalSeparator): any { +export function round1DigitLocalized(speed: number, separator: string= = T.global.decimalSeparator) { return round1Digit(speed).toString().replace(".", separator); } /** * Formats a number like 2.51 to "2.51 items / s" */ -export function formatItemsPerSecond(speed: number, double: boolean= = false, separator: string= = T.global.decimalSeparator): any { +export function formatItemsPerSecond(speed: number, double: boolean= = false, separator: string= = T.global.decimalSeparator) { return ((speed === 1.0 ? T.ingame.buildingPlacement.infoTexts.oneItemPerSecond : T.ingame.buildingPlacement.infoTexts.itemsPerSecond.replace("", round2Digits(speed).toString().replace(".", separator))) + (double ? " " + T.ingame.buildingPlacement.infoTexts.itemsPerSecondDouble : "")); @@ -462,7 +462,7 @@ export function formatItemsPerSecond(speed: number, double: boolean= = false, se * 7 mu * 8 ru */ -export function rotateFlatMatrix3x3(flatMatrix: Array): any { +export function rotateFlatMatrix3x3(flatMatrix: Array) { return [ flatMatrix[6], flatMatrix[3], @@ -480,7 +480,7 @@ export function rotateFlatMatrix3x3(flatMatrix: Array): any { * {} */ export function generateMatrixRotations(originalMatrix: Array): Object> { - const result: any = { + const result = { 0: originalMatrix, }; originalMatrix = rotateFlatMatrix3x3(originalMatrix); @@ -496,8 +496,8 @@ export function generateMatrixRotations(originalMatrix: Array): Object tag */ -export function fillInLinkIntoTranslation(translation: string, link: string): any { +export function fillInLinkIntoTranslation(translation: string, link: string) { return translation .replace("", "") .replace("", ""); @@ -533,8 +533,8 @@ export function fillInLinkIntoTranslation(translation: string, link: string): an /** * Generates a file download */ -export function generateFileDownload(filename: string, text: string): any { - var element: any = document.createElement("a"); +export function generateFileDownload(filename: string, text: string) { + var element = document.createElement("a"); element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(text)); element.setAttribute("download", filename); element.style.display = "none"; @@ -545,17 +545,17 @@ export function generateFileDownload(filename: string, text: string): any { /** * Starts a file chooser */ -export function startFileChoose(acceptedType: string = ".bin"): any { - var input: any = document.createElement("input"); +export function startFileChoose(acceptedType: string = ".bin") { + var input = document.createElement("input"); input.type = "file"; input.accept = acceptedType; - return new Promise((resolve: any): any => { - input.onchange = (_: any): any => resolve(input.files[0]); + return new Promise(resolve => { + input.onchange = _ => resolve(input.files[0]); input.click(); }); } -const MAX_ROMAN_NUMBER: any = 49; -const romanLiteralsCache: any = ["0"]; +const MAX_ROMAN_NUMBER = 49; +const romanLiteralsCache = ["0"]; /** * * {} @@ -568,7 +568,7 @@ export function getRomanNumber(number: number): string { if (number > MAX_ROMAN_NUMBER) { return String(number); } - function formatDigit(digit: any, unit: any, quintuple: any, decuple: any): any { + function formatDigit(digit, unit, quintuple, decuple) { switch (digit) { case 0: return ""; @@ -587,26 +587,26 @@ export function getRomanNumber(number: number): string { return quintuple + formatDigit(digit - 5, unit, quintuple, decuple); } } - let thousands: any = Math.floor(number / 1000); - let thousandsPart: any = ""; + let thousands = Math.floor(number / 1000); + let thousandsPart = ""; while (thousands > 0) { thousandsPart += "M"; thousands -= 1; } - const hundreds: any = Math.floor((number % 1000) / 100); - const hundredsPart: any = formatDigit(hundreds, "C", "D", "M"); - const tens: any = Math.floor((number % 100) / 10); - const tensPart: any = formatDigit(tens, "X", "L", "C"); - const units: any = number % 10; - const unitsPart: any = formatDigit(units, "I", "V", "X"); - const formatted: any = thousandsPart + hundredsPart + tensPart + unitsPart; + const hundreds = Math.floor((number % 1000) / 100); + const hundredsPart = formatDigit(hundreds, "C", "D", "M"); + const tens = Math.floor((number % 100) / 10); + const tensPart = formatDigit(tens, "X", "L", "C"); + const units = number % 10; + const unitsPart = formatDigit(units, "I", "V", "X"); + const formatted = thousandsPart + hundredsPart + tensPart + unitsPart; romanLiteralsCache[number] = formatted; return formatted; } /** * Returns the appropriate logo sprite path */ -export function getLogoSprite(): any { +export function getLogoSprite() { if (G_IS_STANDALONE || WEB_STEAM_SSO_AUTHENTICATED) { return "logo.png"; } @@ -618,10 +618,10 @@ export function getLogoSprite(): any { /** * Rejects a promise after X ms */ -export function timeoutPromise(promise: Promise, timeout: any = 30000): any { +export function timeoutPromise(promise: Promise, timeout = 30000) { return Promise.race([ - new Promise((resolve: any, reject: any): any => { - setTimeout((): any => reject("timeout of " + timeout + " ms exceeded"), timeout); + new Promise((resolve, reject) => { + setTimeout(() => reject("timeout of " + timeout + " ms exceeded"), timeout); }), promise, ]); diff --git a/src/ts/core/vector.ts b/src/ts/core/vector.ts index 9a709c2a..935e0cd5 100644 --- a/src/ts/core/vector.ts +++ b/src/ts/core/vector.ts @@ -1,11 +1,11 @@ import { globalConfig } from "./config"; import { safeModulo } from "./utils"; -const tileSize: any = globalConfig.tileSize; -const halfTileSize: any = globalConfig.halfTileSize; +const tileSize = globalConfig.tileSize; +const halfTileSize = globalConfig.halfTileSize; /** * @enum {string} */ -export const enumDirection: any = { +export const enumDirection = { top: "top", right: "right", bottom: "bottom", @@ -14,7 +14,7 @@ export const enumDirection: any = { /** * @enum {string} */ -export const enumInvertedDirections: any = { +export const enumInvertedDirections = { [enumDirection.top]: enumDirection.bottom, [enumDirection.right]: enumDirection.left, [enumDirection.bottom]: enumDirection.top, @@ -23,7 +23,7 @@ export const enumInvertedDirections: any = { /** * @enum {number} */ -export const enumDirectionToAngle: any = { +export const enumDirectionToAngle = { [enumDirection.top]: 0, [enumDirection.right]: 90, [enumDirection.bottom]: 180, @@ -32,7 +32,7 @@ export const enumDirectionToAngle: any = { /** * @enum {enumDirection} */ -export const enumAngleToDirection: any = { +export const enumAngleToDirection = { 0: enumDirection.top, 90: enumDirection.right, 180: enumDirection.bottom, @@ -224,8 +224,8 @@ export class Vector { * {} */ distanceSquare(v: Vector): number { - const dx: any = this.x - v.x; - const dy: any = this.y - v.y; + const dx = this.x - v.x; + const dy = this.y - v.y; return dx * dx + dy * dy; } /** @@ -240,8 +240,8 @@ export class Vector { * {} */ centerPoint(v: Vector): Vector { - const cx: any = this.x + v.x; - const cy: any = this.y + v.y; + const cx = this.x + v.x; + const cy = this.y + v.y; return new Vector(cx / 2, cy / 2); } /** @@ -305,7 +305,7 @@ export class Vector { * {} */ normalize(): Vector { - const len: any = Math.max(1e-5, Math.hypot(this.x, this.y)); + const len = Math.max(1e-5, Math.hypot(this.x, this.y)); return new Vector(this.x / len, this.y / len); } /** @@ -313,7 +313,7 @@ export class Vector { * {} */ normalizeIfGreaterOne(): Vector { - const len: any = Math.max(1, Math.hypot(this.x, this.y)); + const len = Math.max(1, Math.hypot(this.x, this.y)); return new Vector(this.x / len, this.y / len); } /** @@ -321,9 +321,9 @@ export class Vector { * {} */ normalizedDirection(v: Vector): Vector { - const dx: any = v.x - this.x; - const dy: any = v.y - this.y; - const len: any = Math.max(1e-5, Math.hypot(dx, dy)); + const dx = v.x - this.x; + const dy = v.y - this.y; + const len = Math.max(1e-5, Math.hypot(dx, dy)); return new Vector(dx / len, dy / len); } /** @@ -359,8 +359,8 @@ export class Vector { * {} new vector */ rotated(angle: number): Vector { - const sin: any = Math.sin(angle); - const cos: any = Math.cos(angle); + const sin = Math.sin(angle); + const cos = Math.cos(angle); return new Vector(this.x * cos - this.y * sin, this.x * sin + this.y * cos); } /** @@ -380,7 +380,7 @@ export class Vector { case 90: { // sin = 1; // cos = 0; - const x: any = this.x; + const x = this.x; this.x = -this.y; this.y = x; return this; @@ -395,7 +395,7 @@ export class Vector { case 270: { // sin = -1 // cos = 0 - const x: any = this.x; + const x = this.x; this.x = this.y; this.y = -x; return this; @@ -504,7 +504,7 @@ export class Vector { * Compares both vectors for epsilon equality * {} */ - equalsEpsilon(v: Vector, epsilon: any = 1e-5): Boolean { + equalsEpsilon(v: Vector, epsilon = 1e-5): Boolean { return Math.abs(this.x - v.x) < 1e-5 && Math.abs(this.y - v.y) < epsilon; } /** @@ -524,7 +524,7 @@ export class Vector { /** * Creates a simple representation of the vector */ - serializeSimple(): any { + serializeSimple() { return { x: this.x, y: this.y }; } /** @@ -538,8 +538,8 @@ export class Vector { * {} */ static deserializeTileFromInt(i: number): Vector { - const x: any = i % 256; - const y: any = Math.floor(i / 256); + const x = i % 256; + const y = Math.floor(i / 256); return new Vector(x, y); } /** @@ -562,14 +562,14 @@ export class Vector { /** * Interpolates two vectors, for a = 0, returns v1 and for a = 1 return v2, otherwise interpolate */ -export function mixVector(v1: Vector, v2: Vector, a: number): any { +export function mixVector(v1: Vector, v2: Vector, a: number) { return new Vector(v1.x * (1 - a) + v2.x * a, v1.y * (1 - a) + v2.y * a); } /** * Mapping from string direction to actual vector * @enum {Vector} */ -export const enumDirectionToVector: any = { +export const enumDirectionToVector = { top: new Vector(0, -1), right: new Vector(1, 0), bottom: new Vector(0, 1), diff --git a/src/ts/game/achievement_proxy.ts b/src/ts/game/achievement_proxy.ts index 2aea9f01..57b0a0aa 100644 --- a/src/ts/game/achievement_proxy.ts +++ b/src/ts/game/achievement_proxy.ts @@ -6,9 +6,9 @@ import { globalConfig } from "../core/config"; import { createLogger } from "../core/logging"; import { ACHIEVEMENTS } from "../platform/achievement_provider"; import { getBuildingDataFromCode } from "./building_codes"; -const logger: any = createLogger("achievement_proxy"); -const ROTATER: any = "rotater"; -const DEFAULT: any = "default"; +const logger = createLogger("achievement_proxy"); +const ROTATER = "rotater"; +const DEFAULT = "default"; export class AchievementProxy { public root = root; public provider = this.root.app.achievementProvider; @@ -24,7 +24,7 @@ export class AchievementProxy { } this.root.signals.postLoadHook.add(this.onLoad, this); } - onLoad(): any { + onLoad() { if (!this.root.gameMode.hasAchievements()) { logger.log("Disabling achievements because game mode does not have achievements"); this.disabled = true; @@ -32,17 +32,17 @@ export class AchievementProxy { } this.provider .onLoad(this.root) - .then((): any => { + .then(() => { this.disabled = false; logger.log("Recieving achievement signals"); this.initialize(); }) - .catch((err: any): any => { + .catch(err => { this.disabled = true; logger.error("Ignoring achievement signals", err); }); } - initialize(): any { + initialize() { this.root.signals.achievementCheck.dispatch(ACHIEVEMENTS.darkMode, null); if (this.has(ACHIEVEMENTS.mam)) { this.root.signals.entityAdded.add(this.onMamFailure, this); @@ -54,11 +54,11 @@ export class AchievementProxy { } this.startSlice(); } - startSlice(): any { + startSlice() { this.sliceTime = this.root.time.now(); this.root.signals.bulkAchievementCheck.dispatch(ACHIEVEMENTS.storeShape, this.sliceTime, ACHIEVEMENTS.throughputBp25, this.sliceTime, ACHIEVEMENTS.throughputBp50, this.sliceTime, ACHIEVEMENTS.throughputLogo25, this.sliceTime, ACHIEVEMENTS.throughputLogo50, this.sliceTime, ACHIEVEMENTS.throughputRocket10, this.sliceTime, ACHIEVEMENTS.throughputRocket20, this.sliceTime, ACHIEVEMENTS.play1h, this.sliceTime, ACHIEVEMENTS.play10h, this.sliceTime, ACHIEVEMENTS.play20h, this.sliceTime); } - update(): any { + update() { if (this.disabled) { return; } @@ -75,11 +75,11 @@ export class AchievementProxy { } return this.provider.collection.map.has(key); } - onEntityAdded(entity: Entity): any { + onEntityAdded(entity: Entity) { if (!entity.components.StaticMapEntity) { return; } - const building: any = getBuildingDataFromCode(entity.components.StaticMapEntity.code); + const building = getBuildingDataFromCode(entity.components.StaticMapEntity.code); if (building.metaInstance.id !== ROTATER) { return; } @@ -89,7 +89,7 @@ export class AchievementProxy { this.root.savegame.currentData.stats.usedInverseRotater = true; this.root.signals.entityAdded.remove(this.onEntityAdded); } - onStoryGoalCompleted(level: number): any { + onStoryGoalCompleted(level: number) { if (level > 26) { this.root.signals.entityAdded.add(this.onMamFailure, this); this.root.signals.entityDestroyed.add(this.onMamFailure, this); @@ -98,7 +98,7 @@ export class AchievementProxy { // reset on every level this.root.savegame.currentData.stats.failedMam = false; } - onMamFailure(): any { + onMamFailure() { this.root.savegame.currentData.stats.failedMam = true; } } diff --git a/src/ts/game/automatic_save.ts b/src/ts/game/automatic_save.ts index e3d1a275..c86d8bfe 100644 --- a/src/ts/game/automatic_save.ts +++ b/src/ts/game/automatic_save.ts @@ -5,11 +5,11 @@ import { GameRoot } from "./root"; /** * @enum {number} */ -export const enumSavePriority: any = { +export const enumSavePriority = { regular: 2, asap: 100, }; -const logger: any = createLogger("autosave"); +const logger = createLogger("autosave"); export class AutomaticSave { public root: GameRoot = root; public saveImportance = enumSavePriority.regular; @@ -17,30 +17,30 @@ export class AutomaticSave { constructor(root) { } - setSaveImportance(importance: any): any { + setSaveImportance(importance) { this.saveImportance = Math.max(this.saveImportance, importance); } - doSave(): any { + doSave() { if (G_IS_DEV && globalConfig.debug.disableSavegameWrite) { return; } this.root.gameState.doSave(); this.saveImportance = enumSavePriority.regular; } - update(): any { + update() { if (!this.root.gameInitialized) { // Bad idea return; } - const saveInterval: any = this.root.app.settings.getAutosaveIntervalSeconds(); + const saveInterval = this.root.app.settings.getAutosaveIntervalSeconds(); if (!saveInterval) { // Disabled return; } // Check when the last save was, but make sure that if it fails, we don't spam - const lastSaveTime: any = Math.max(this.lastSaveAttempt, this.root.savegame.getRealLastUpdate()); - const secondsSinceLastSave: any = (Date.now() - lastSaveTime) / 1000.0; - let shouldSave: any = false; + const lastSaveTime = Math.max(this.lastSaveAttempt, this.root.savegame.getRealLastUpdate()); + const secondsSinceLastSave = (Date.now() - lastSaveTime) / 1000.0; + let shouldSave = false; switch (this.saveImportance) { case enumSavePriority.asap: // High always should save diff --git a/src/ts/game/base_item.ts b/src/ts/game/base_item.ts index eec733d1..71fb6501 100644 --- a/src/ts/game/base_item.ts +++ b/src/ts/game/base_item.ts @@ -10,7 +10,7 @@ export class BaseItem extends BasicSerializableObject { constructor() { super(); } - static getId(): any { + static getId() { return "base_item"; } /** {} */ @@ -54,13 +54,13 @@ export class BaseItem extends BasicSerializableObject { * Draws the item to a canvas * @abstract */ - drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number): any { + drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number) { abstract; } /** * Draws the item at the given position */ - drawItemCenteredClipped(x: number, y: number, parameters: DrawParameters, diameter: number= = globalConfig.defaultItemDiameter): any { + drawItemCenteredClipped(x: number, y: number, parameters: DrawParameters, diameter: number= = globalConfig.defaultItemDiameter) { if (parameters.visibleRect.containsCircle(x, y, diameter / 2)) { this.drawItemCenteredImpl(x, y, parameters, diameter); } @@ -69,10 +69,10 @@ export class BaseItem extends BasicSerializableObject { * INTERNAL * @abstract */ - drawItemCenteredImpl(x: number, y: number, parameters: DrawParameters, diameter: number= = globalConfig.defaultItemDiameter): any { + drawItemCenteredImpl(x: number, y: number, parameters: DrawParameters, diameter: number= = globalConfig.defaultItemDiameter) { abstract; } - getBackgroundColorAsResource(): any { + getBackgroundColorAsResource() { abstract; return ""; } diff --git a/src/ts/game/belt_path.ts b/src/ts/game/belt_path.ts index a63dcbfd..959491de 100644 --- a/src/ts/game/belt_path.ts +++ b/src/ts/game/belt_path.ts @@ -11,17 +11,17 @@ import { BaseItem } from "./base_item"; import { Entity } from "./entity"; import { typeItemSingleton } from "./item_resolver"; import { GameRoot } from "./root"; -const logger: any = createLogger("belt_path"); +const logger = createLogger("belt_path"); // Helpers for more semantic access into interleaved arrays -const DEBUG: any = G_IS_DEV && false; +const DEBUG = G_IS_DEV && false; /** * Stores a path of belts, used for optimizing performance */ export class BeltPath extends BasicSerializableObject { - static getId(): any { + static getId() { return "BeltPath"; } - static getSchema(): any { + static getSchema() { return { entityPath: types.array(types.entity), items: types.array(types.pair(types.ufloat, typeItemSingleton)), @@ -35,10 +35,10 @@ export class BeltPath extends BasicSerializableObject { static fromSerialized(root: GameRoot, data: Object): BeltPath | string { // Create fake object which looks like a belt path but skips the constructor - const fakeObject: any = (Object.create(BeltPath.prototype) as BeltPath); + const fakeObject = Object.create(BeltPath.prototype) as BeltPath); fakeObject.root = root; // Deserialize the data - const errorCodeDeserialize: any = fakeObject.deserialize(data); + const errorCodeDeserialize = fakeObject.deserialize(data); if (errorCodeDeserialize) { return errorCodeDeserialize; } @@ -68,7 +68,7 @@ export class BeltPath extends BasicSerializableObject { /** * Initializes the path by computing the properties which are not saved */ - init(computeSpacing: boolean = true): any { + init(computeSpacing: boolean = true) { this.onPathChanged(); this.totalLength = this.computeTotalLength(); if (computeSpacing) { @@ -79,14 +79,14 @@ export class BeltPath extends BasicSerializableObject { */ this.worldBounds = this.computeBounds(); // Connect the belts - for (let i: any = 0; i < this.entityPath.length; ++i) { + for (let i = 0; i < this.entityPath.length; ++i) { this.entityPath[i].components.Belt.assignedPath = this; } } /** * Clears all items */ - clearAllItems(): any { + clearAllItems() { this.items = []; this.spacingToFirstItem = this.totalLength; this.numCompressedItemsAfterFirstItem = 0; @@ -101,15 +101,15 @@ export class BeltPath extends BasicSerializableObject { /** * Tries to accept the item */ - tryAcceptItem(item: BaseItem): any { + tryAcceptItem(item: BaseItem) { if (this.spacingToFirstItem >= globalConfig.itemSpacingOnBelts) { // So, since we already need one tick to accept this item we will add this directly. - const beltProgressPerTick: any = this.root.hubGoals.getBeltBaseSpeed() * + const beltProgressPerTick = this.root.hubGoals.getBeltBaseSpeed() * this.root.dynamicTickrate.deltaSeconds * globalConfig.itemSpacingOnBelts; // First, compute how much progress we can make *at max* - const maxProgress: any = Math.max(0, this.spacingToFirstItem - globalConfig.itemSpacingOnBelts); - const initialProgress: any = Math.min(maxProgress, beltProgressPerTick); + const maxProgress = Math.max(0, this.spacingToFirstItem - globalConfig.itemSpacingOnBelts); + const initialProgress = Math.min(maxProgress, beltProgressPerTick); this.items.unshift([this.spacingToFirstItem - initialProgress, item]); this.spacingToFirstItem = initialProgress; if (G_IS_DEV && globalConfig.debug.checkBeltPaths) { @@ -132,10 +132,10 @@ export class BeltPath extends BasicSerializableObject { * {} */ computeBounds(): Rectangle { - let bounds: any = this.entityPath[0].components.StaticMapEntity.getTileSpaceBounds(); - for (let i: any = 1; i < this.entityPath.length; ++i) { - const staticComp: any = this.entityPath[i].components.StaticMapEntity; - const otherBounds: any = staticComp.getTileSpaceBounds(); + let bounds = this.entityPath[0].components.StaticMapEntity.getTileSpaceBounds(); + for (let i = 1; i < this.entityPath.length; ++i) { + const staticComp = this.entityPath[i].components.StaticMapEntity; + const otherBounds = staticComp.getTileSpaceBounds(); bounds = bounds.getUnion(otherBounds); } return bounds.allScaled(globalConfig.tileSize); @@ -143,7 +143,7 @@ export class BeltPath extends BasicSerializableObject { /** * Recomputes cache variables once the path was changed */ - onPathChanged(): any { + onPathChanged() { this.boundAcceptor = this.computeAcceptingEntityAndSlot().acceptor; /** * How many items past the first item are compressed @@ -153,7 +153,7 @@ export class BeltPath extends BasicSerializableObject { /** * Called by the belt system when the surroundings changed */ - onSurroundingsChanged(): any { + onSurroundingsChanged() { this.onPathChanged(); } /** @@ -165,34 +165,34 @@ export class BeltPath extends BasicSerializableObject { entity?: Entity; } { DEBUG && !debug_Silent && logger.log("Recomputing acceptor target"); - const lastEntity: any = this.entityPath[this.entityPath.length - 1]; - const lastStatic: any = lastEntity.components.StaticMapEntity; - const lastBeltComp: any = lastEntity.components.Belt; + const lastEntity = this.entityPath[this.entityPath.length - 1]; + const lastStatic = lastEntity.components.StaticMapEntity; + const lastBeltComp = lastEntity.components.Belt; // Figure out where and into which direction we eject items - const ejectSlotWsTile: any = lastStatic.localTileToWorld(new Vector(0, 0)); - const ejectSlotWsDirection: any = lastStatic.localDirectionToWorld(lastBeltComp.direction); - const ejectSlotWsDirectionVector: any = enumDirectionToVector[ejectSlotWsDirection]; - const ejectSlotTargetWsTile: any = ejectSlotWsTile.add(ejectSlotWsDirectionVector); + const ejectSlotWsTile = lastStatic.localTileToWorld(new Vector(0, 0)); + const ejectSlotWsDirection = lastStatic.localDirectionToWorld(lastBeltComp.direction); + const ejectSlotWsDirectionVector = enumDirectionToVector[ejectSlotWsDirection]; + const ejectSlotTargetWsTile = ejectSlotWsTile.add(ejectSlotWsDirectionVector); // Try to find the given acceptor component to take the item - const targetEntity: any = this.root.map.getLayerContentXY(ejectSlotTargetWsTile.x, ejectSlotTargetWsTile.y, "regular"); + const targetEntity = this.root.map.getLayerContentXY(ejectSlotTargetWsTile.x, ejectSlotTargetWsTile.y, "regular"); if (!targetEntity) { return {}; } - const noSimplifiedBelts: any = !this.root.app.settings.getAllSettings().simplifiedBelts; + const noSimplifiedBelts = !this.root.app.settings.getAllSettings().simplifiedBelts; DEBUG && !debug_Silent && logger.log(" Found target entity", targetEntity.uid); - const targetStaticComp: any = targetEntity.components.StaticMapEntity; - const targetBeltComp: any = targetEntity.components.Belt; + const targetStaticComp = targetEntity.components.StaticMapEntity; + const targetBeltComp = targetEntity.components.Belt; // Check for belts (special case) if (targetBeltComp) { - const beltAcceptingDirection: any = targetStaticComp.localDirectionToWorld(enumDirection.top); + const beltAcceptingDirection = targetStaticComp.localDirectionToWorld(enumDirection.top); DEBUG && !debug_Silent && logger.log(" Entity is accepting items from", ejectSlotWsDirection, "vs", beltAcceptingDirection, "Rotation:", targetStaticComp.rotation); if (ejectSlotWsDirection === beltAcceptingDirection) { return { entity: targetEntity, - acceptor: (item: any): any => { - const path: any = targetBeltComp.assignedPath; + acceptor: item => { + const path = targetBeltComp.assignedPath; assert(path, "belt has no path"); return path.tryAcceptItem(item); }, @@ -200,27 +200,27 @@ export class BeltPath extends BasicSerializableObject { } } // Check for item acceptors - const targetAcceptorComp: any = targetEntity.components.ItemAcceptor; + const targetAcceptorComp = targetEntity.components.ItemAcceptor; if (!targetAcceptorComp) { // Entity doesn't accept items return {}; } - const ejectingDirection: any = targetStaticComp.worldDirectionToLocal(ejectSlotWsDirection); - const matchingSlot: any = targetAcceptorComp.findMatchingSlot(targetStaticComp.worldToLocalTile(ejectSlotTargetWsTile), ejectingDirection); + const ejectingDirection = targetStaticComp.worldDirectionToLocal(ejectSlotWsDirection); + const matchingSlot = targetAcceptorComp.findMatchingSlot(targetStaticComp.worldToLocalTile(ejectSlotTargetWsTile), ejectingDirection); if (!matchingSlot) { // No matching slot found return {}; } - const matchingSlotIndex: any = matchingSlot.index; - const passOver: any = this.computePassOverFunctionWithoutBelts(targetEntity, matchingSlotIndex); + const matchingSlotIndex = matchingSlot.index; + const passOver = this.computePassOverFunctionWithoutBelts(targetEntity, matchingSlotIndex); if (!passOver) { return {}; } - const matchingDirection: any = enumInvertedDirections[ejectingDirection]; - const filter: any = matchingSlot.slot.filter; + const matchingDirection = enumInvertedDirections[ejectingDirection]; + const filter = matchingSlot.slot.filter; return { entity: targetEntity, - acceptor: function (item: any, remainingProgress: any = 0.0): any { + acceptor: function (item, remainingProgress = 0.0) { // Check if the acceptor has a filter if (filter && item._type !== filter) { return false; @@ -242,13 +242,13 @@ export class BeltPath extends BasicSerializableObject { * {} */ computePassOverFunctionWithoutBelts(entity: Entity, matchingSlotIndex: number): (item: BaseItem, slotIndex: number) => boolean | void { - const systems: any = this.root.systemMgr.systems; - const hubGoals: any = this.root.hubGoals; + const systems = this.root.systemMgr.systems; + const hubGoals = this.root.hubGoals; // NOTICE: THIS IS COPIED FROM THE ITEM EJECTOR SYSTEM FOR PEROFMANCE REASONS - const itemProcessorComp: any = entity.components.ItemProcessor; + const itemProcessorComp = entity.components.ItemProcessor; if (itemProcessorComp) { // Its an item processor .. - return function (item: any): any { + return function (item) { // Check for potential filters if (!systems.itemProcessor.checkRequirements(entity, item, matchingSlotIndex)) { return; @@ -256,28 +256,28 @@ export class BeltPath extends BasicSerializableObject { return itemProcessorComp.tryTakeItem(item, matchingSlotIndex); }; } - const undergroundBeltComp: any = entity.components.UndergroundBelt; + const undergroundBeltComp = entity.components.UndergroundBelt; if (undergroundBeltComp) { // Its an underground belt. yay. - return function (item: any): any { + return function (item) { return undergroundBeltComp.tryAcceptExternalItem(item, hubGoals.getUndergroundBeltBaseSpeed()); }; } - const storageComp: any = entity.components.Storage; + const storageComp = entity.components.Storage; if (storageComp) { // It's a storage - return function (item: any): any { + return function (item) { if (storageComp.canAcceptItem(item)) { storageComp.takeItem(item); return true; } }; } - const filterComp: any = entity.components.Filter; + const filterComp = entity.components.Filter; if (filterComp) { // It's a filter! Unfortunately the filter has to know a lot about it's // surrounding state and components, so it can't be within the component itself. - return function (item: any): any { + return function (item) { if (systems.filter.tryAcceptItem(entity, matchingSlotIndex, item)) { return true; } @@ -289,30 +289,30 @@ export class BeltPath extends BasicSerializableObject { /** * Helper to throw an error on mismatch */ - debug_failIntegrity(change: string, ...reason: Array): any { - throw new Error("belt path invalid (" + change + "): " + reason.map((i: any): any => "" + i).join(" ")); + debug_failIntegrity(change: string, ...reason: Array) { + throw new Error("belt path invalid (" + change + "): " + reason.map(i => "" + i).join(" ")); } /** * Checks if this path is valid */ - debug_checkIntegrity(currentChange: any = "change"): any { - const fail: any = (...args: any): any => this.debug_failIntegrity(currentChange, ...args); + debug_checkIntegrity(currentChange = "change") { + const fail = (...args) => this.debug_failIntegrity(currentChange, ...args); // Check for empty path if (this.entityPath.length === 0) { return fail("Belt path is empty"); } // Check for mismatching length - const totalLength: any = this.computeTotalLength(); + const totalLength = this.computeTotalLength(); if (!epsilonCompare(this.totalLength, totalLength, 0.01)) { return this.debug_failIntegrity(currentChange, "Total length mismatch, stored =", this.totalLength, "but correct is", totalLength); } // Check for misconnected entities - for (let i: any = 0; i < this.entityPath.length - 1; ++i) { - const entity: any = this.entityPath[i]; + for (let i = 0; i < this.entityPath.length - 1; ++i) { + const entity = this.entityPath[i]; if (entity.destroyed) { return fail("Reference to destroyed entity " + entity.uid); } - const followUp: any = this.root.systemMgr.systems.belt.findFollowUpEntity(entity); + const followUp = this.root.systemMgr.systems.belt.findFollowUpEntity(entity); if (!followUp) { return fail("Follow up entity for the", i, "-th entity (total length", this.entityPath.length, ") was null!"); } @@ -332,9 +332,9 @@ export class BeltPath extends BasicSerializableObject { return fail(currentChange, "Path is empty but spacing to first item (", this.spacingToFirstItem, ") does not equal total length (", this.totalLength, ")"); } // Check items etc - let currentPos: any = this.spacingToFirstItem; - for (let i: any = 0; i < this.items.length; ++i) { - const item: any = this.items[i]; + let currentPos = this.spacingToFirstItem; + for (let i = 0; i < this.items.length; ++i) { + const item = this.items[i]; if (item[0 /* nextDistance */] < 0 || item[0 /* nextDistance */] > this.totalLength + 0.02) { return fail("Item has invalid offset to next item: ", item[0 /* nextDistance */], "(total length:", this.totalLength, ")"); } @@ -342,21 +342,21 @@ export class BeltPath extends BasicSerializableObject { } // Check the total sum matches if (!epsilonCompare(currentPos, this.totalLength, 0.01)) { - return fail("total sum (", currentPos, ") of first item spacing (", this.spacingToFirstItem, ") and items does not match total length (", this.totalLength, ") -> items: " + this.items.map((i: any): any => i[0 /* nextDistance */]).join("|")); + return fail("total sum (", currentPos, ") of first item spacing (", this.spacingToFirstItem, ") and items does not match total length (", this.totalLength, ") -> items: " + this.items.map(i => i[0 /* nextDistance */]).join("|")); } // Check bounds - const actualBounds: any = this.computeBounds(); + const actualBounds = this.computeBounds(); if (!actualBounds.equalsEpsilon(this.worldBounds, 0.01)) { return fail("Bounds are stale"); } // Check acceptor - const acceptor: any = this.computeAcceptingEntityAndSlot(true).acceptor; + const acceptor = this.computeAcceptingEntityAndSlot(true).acceptor; if (!!acceptor !== !!this.boundAcceptor) { return fail("Acceptor target mismatch, acceptor", !!acceptor, "vs stored", !!this.boundAcceptor); } // Check first nonzero offset - let firstNonzero: any = 0; - for (let i: any = this.items.length - 2; i >= 0; --i) { + let firstNonzero = 0; + for (let i = this.items.length - 2; i >= 0; --i) { if (this.items[i][0 /* nextDistance */] < globalConfig.itemSpacingOnBelts + 1e-5) { ++firstNonzero; } @@ -378,14 +378,14 @@ export class BeltPath extends BasicSerializableObject { /** * Extends the belt path by the given belt */ - extendOnEnd(entity: Entity): any { + extendOnEnd(entity: Entity) { DEBUG && logger.log("Extending belt path by entity at", entity.components.StaticMapEntity.origin); - const beltComp: any = entity.components.Belt; + const beltComp = entity.components.Belt; // Append the entity this.entityPath.push(entity); this.onPathChanged(); // Extend the path length - const additionalLength: any = beltComp.getEffectiveLengthTiles(); + const additionalLength = beltComp.getEffectiveLengthTiles(); this.totalLength += additionalLength; DEBUG && logger.log(" Extended total length by", additionalLength, "to", this.totalLength); // If we have no item, just update the distance to the first item @@ -395,7 +395,7 @@ export class BeltPath extends BasicSerializableObject { } else { // Otherwise, update the next-distance of the last item - const lastItem: any = this.items[this.items.length - 1]; + const lastItem = this.items[this.items.length - 1]; DEBUG && logger.log(" Extended spacing of last item from", lastItem[0 /* nextDistance */], "to", lastItem[0 /* nextDistance */] + additionalLength); lastItem[0 /* nextDistance */] += additionalLength; @@ -411,11 +411,11 @@ export class BeltPath extends BasicSerializableObject { /** * Extends the path with the given entity on the beginning */ - extendOnBeginning(entity: Entity): any { - const beltComp: any = entity.components.Belt; + extendOnBeginning(entity: Entity) { + const beltComp = entity.components.Belt; DEBUG && logger.log("Extending the path on the beginning"); // All items on that belt are simply lost (for now) - const length: any = beltComp.getEffectiveLengthTiles(); + const length = beltComp.getEffectiveLengthTiles(); // Extend the length of this path this.totalLength += length; // Simply adjust the first item spacing cuz we have no items contained @@ -452,17 +452,17 @@ export class BeltPath extends BasicSerializableObject { deleteEntityOnPathSplitIntoTwo(entity: Entity): BeltPath { DEBUG && logger.log("Splitting path at entity", entity.components.StaticMapEntity.origin); // First, find where the current path ends - const beltComp: any = entity.components.Belt; + const beltComp = entity.components.Belt; beltComp.assignedPath = null; - const entityLength: any = beltComp.getEffectiveLengthTiles(); + const entityLength = beltComp.getEffectiveLengthTiles(); assert(this.entityPath.indexOf(entity) >= 0, "Entity not contained for split"); assert(this.entityPath.indexOf(entity) !== 0, "Entity is first"); assert(this.entityPath.indexOf(entity) !== this.entityPath.length - 1, "Entity is last"); - let firstPathEntityCount: any = 0; - let firstPathLength: any = 0; - let firstPathEndEntity: any = null; - for (let i: any = 0; i < this.entityPath.length; ++i) { - const otherEntity: any = this.entityPath[i]; + let firstPathEntityCount = 0; + let firstPathLength = 0; + let firstPathEndEntity = null; + for (let i = 0; i < this.entityPath.length; ++i) { + const otherEntity = this.entityPath[i]; if (otherEntity === entity) { DEBUG && logger.log("Found entity at", i, "of length", firstPathLength); break; @@ -474,23 +474,23 @@ export class BeltPath extends BasicSerializableObject { DEBUG && logger.log("First path ends at", firstPathLength, "and entity", firstPathEndEntity.components.StaticMapEntity.origin, "and has", firstPathEntityCount, "entities"); // Compute length of second path - const secondPathLength: any = this.totalLength - firstPathLength - entityLength; - const secondPathStart: any = firstPathLength + entityLength; - const secondEntities: any = this.entityPath.splice(firstPathEntityCount + 1); + const secondPathLength = this.totalLength - firstPathLength - entityLength; + const secondPathStart = firstPathLength + entityLength; + const secondEntities = this.entityPath.splice(firstPathEntityCount + 1); DEBUG && logger.log("Second path starts at", secondPathStart, "and has a length of ", secondPathLength, "with", secondEntities.length, "entities"); // Remove the last item this.entityPath.pop(); DEBUG && logger.log("Splitting", this.items.length, "items"); DEBUG && - logger.log("Old items are", this.items.map((i: any): any => i[0 /* nextDistance */])); + logger.log("Old items are", this.items.map(i => i[0 /* nextDistance */])); // Create second path - const secondPath: any = new BeltPath(this.root, secondEntities); + const secondPath = new BeltPath(this.root, secondEntities); // Remove all items which are no longer relevant and transfer them to the second path - let itemPos: any = this.spacingToFirstItem; - for (let i: any = 0; i < this.items.length; ++i) { - const item: any = this.items[i]; - const distanceToNext: any = item[0 /* nextDistance */]; + let itemPos = this.spacingToFirstItem; + for (let i = 0; i < this.items.length; ++i) { + const item = this.items[i]; + const distanceToNext = item[0 /* nextDistance */]; DEBUG && logger.log(" Checking item at", itemPos, "with distance of", distanceToNext, "to next"); // Check if this item is past the first path if (itemPos >= firstPathLength) { @@ -518,7 +518,7 @@ export class BeltPath extends BasicSerializableObject { else { // Seems this item is on the first path (so all good), so just make sure it doesn't // have a nextDistance which is bigger than the total path length - const clampedDistanceToNext: any = Math.min(itemPos + distanceToNext, firstPathLength) - itemPos; + const clampedDistanceToNext = Math.min(itemPos + distanceToNext, firstPathLength) - itemPos; if (clampedDistanceToNext < distanceToNext) { DEBUG && logger.log("Correcting next distance (first path) from", distanceToNext, "to", clampedDistanceToNext); @@ -529,9 +529,9 @@ export class BeltPath extends BasicSerializableObject { itemPos += distanceToNext; } DEBUG && - logger.log("New items are", this.items.map((i: any): any => i[0 /* nextDistance */])); + logger.log("New items are", this.items.map(i => i[0 /* nextDistance */])); DEBUG && - logger.log("And second path items are", secondPath.items.map((i: any): any => i[0 /* nextDistance */])); + logger.log("And second path items are", secondPath.items.map(i => i[0 /* nextDistance */])); // Adjust our total length this.totalLength = firstPathLength; // Make sure that if we are empty, we set our first distance properly @@ -551,11 +551,11 @@ export class BeltPath extends BasicSerializableObject { /** * Deletes the last entity */ - deleteEntityOnEnd(entity: Entity): any { + deleteEntityOnEnd(entity: Entity) { assert(this.entityPath[this.entityPath.length - 1] === entity, "Not actually the last entity (instead " + this.entityPath.indexOf(entity) + ")"); // Ok, first remove the entity - const beltComp: any = entity.components.Belt; - const beltLength: any = beltComp.getEffectiveLengthTiles(); + const beltComp = entity.components.Belt; + const beltLength = beltComp.getEffectiveLengthTiles(); DEBUG && logger.log("Deleting last entity on path with length", this.entityPath.length, "(reducing", this.totalLength, " by", beltLength, ")"); this.totalLength -= beltLength; @@ -572,11 +572,11 @@ export class BeltPath extends BasicSerializableObject { } else { // Ok, make sure we simply drop all items which are no longer contained - let itemOffset: any = this.spacingToFirstItem; - let lastItemOffset: any = itemOffset; + let itemOffset = this.spacingToFirstItem; + let lastItemOffset = itemOffset; DEBUG && logger.log(" Adjusting", this.items.length, "items"); - for (let i: any = 0; i < this.items.length; ++i) { - const item: any = this.items[i]; + for (let i = 0; i < this.items.length; ++i) { + const item = this.items[i]; // Get rid of items past this path if (itemOffset >= this.totalLength) { DEBUG && logger.log("Dropping item (current index=", i, ")"); @@ -592,7 +592,7 @@ export class BeltPath extends BasicSerializableObject { // If we still have an item, make sure the last item matches if (this.items.length > 0) { // We can easily compute the next distance since we know where the last item is now - const lastDistance: any = this.totalLength - lastItemOffset; + const lastDistance = this.totalLength - lastItemOffset; assert(lastDistance >= 0.0, "Last item distance mismatch: " + lastDistance + " -> Total length was " + @@ -619,11 +619,11 @@ export class BeltPath extends BasicSerializableObject { * Deletes the entity of the start of the path * @see deleteEntityOnEnd */ - deleteEntityOnStart(entity: Entity): any { + deleteEntityOnStart(entity: Entity) { assert(entity === this.entityPath[0], "Not actually the start entity (instead " + this.entityPath.indexOf(entity) + ")"); // Ok, first remove the entity - const beltComp: any = entity.components.Belt; - const beltLength: any = beltComp.getEffectiveLengthTiles(); + const beltComp = entity.components.Belt; + const beltLength = beltComp.getEffectiveLengthTiles(); DEBUG && logger.log("Deleting first entity on path with length", this.entityPath.length, "(reducing", this.totalLength, " by", beltLength, ")"); this.totalLength -= beltLength; @@ -651,11 +651,11 @@ export class BeltPath extends BasicSerializableObject { DEBUG && logger.log(" We have at least one item in the beginning, drop those and adjust spacing (first item @", this.spacingToFirstItem, ") since we removed", beltLength, "length from path"); DEBUG && - logger.log(" Items:", this.items.map((i: any): any => i[0 /* nextDistance */])); + logger.log(" Items:", this.items.map(i => i[0 /* nextDistance */])); // Find offset to first item - let itemOffset: any = this.spacingToFirstItem; - for (let i: any = 0; i < this.items.length; ++i) { - const item: any = this.items[i]; + let itemOffset = this.spacingToFirstItem; + for (let i = 0; i < this.items.length; ++i) { + const item = this.items[i]; if (itemOffset <= beltLength) { DEBUG && logger.log(" -> Dropping item with index", i, "at", itemOffset, "since it was on the removed belt"); @@ -692,28 +692,28 @@ export class BeltPath extends BasicSerializableObject { /** * Extends the path by the given other path */ - extendByPath(otherPath: BeltPath): any { + extendByPath(otherPath: BeltPath) { assert(otherPath !== this, "Circular path dependency"); - const entities: any = otherPath.entityPath; + const entities = otherPath.entityPath; DEBUG && logger.log("Extending path by other path, starting to add entities"); - const oldLength: any = this.totalLength; + const oldLength = this.totalLength; DEBUG && logger.log(" Adding", entities.length, "new entities, current length =", this.totalLength); // First, append entities - for (let i: any = 0; i < entities.length; ++i) { - const entity: any = entities[i]; - const beltComp: any = entity.components.Belt; + for (let i = 0; i < entities.length; ++i) { + const entity = entities[i]; + const beltComp = entity.components.Belt; // Add to path and update references this.entityPath.push(entity); beltComp.assignedPath = this; // Update our length - const additionalLength: any = beltComp.getEffectiveLengthTiles(); + const additionalLength = beltComp.getEffectiveLengthTiles(); this.totalLength += additionalLength; } DEBUG && logger.log(" Path is now", this.entityPath.length, "entities and has a length of", this.totalLength); // Now, update the distance of our last item if (this.items.length !== 0) { - const lastItem: any = this.items[this.items.length - 1]; + const lastItem = this.items[this.items.length - 1]; lastItem[0 /* nextDistance */] += otherPath.spacingToFirstItem; DEBUG && logger.log(" Add distance to last item, effectively being", lastItem[0 /* nextDistance */], "now"); @@ -726,8 +726,8 @@ export class BeltPath extends BasicSerializableObject { } DEBUG && logger.log(" Pushing", otherPath.items.length, "items from other path"); // Aaand push the other paths items - for (let i: any = 0; i < otherPath.items.length; ++i) { - const item: any = otherPath.items[i]; + for (let i = 0; i < otherPath.items.length; ++i) { + const item = otherPath.items[i]; this.items.push([item[0 /* nextDistance */], item[1 /* item */]]); } // Update bounds @@ -742,9 +742,9 @@ export class BeltPath extends BasicSerializableObject { * {} */ computeTotalLength(): number { - let length: any = 0; - for (let i: any = 0; i < this.entityPath.length; ++i) { - const entity: any = this.entityPath[i]; + let length = 0; + for (let i = 0; i < this.entityPath.length; ++i) { + const entity = this.entityPath[i]; length += entity.components.Belt.getEffectiveLengthTiles(); } return length; @@ -752,7 +752,7 @@ export class BeltPath extends BasicSerializableObject { /** * Performs one tick */ - update(): any { + update() { if (G_IS_DEV && globalConfig.debug.checkBeltPaths) { this.debug_checkIntegrity("pre-update"); } @@ -761,7 +761,7 @@ export class BeltPath extends BasicSerializableObject { return; } // Divide by item spacing on belts since we use throughput and not speed - let beltSpeed: any = this.root.hubGoals.getBeltBaseSpeed() * + let beltSpeed = this.root.hubGoals.getBeltBaseSpeed() * this.root.dynamicTickrate.deltaSeconds * globalConfig.itemSpacingOnBelts; if (G_IS_DEV && globalConfig.debug.instantBelts) { @@ -769,17 +769,17 @@ export class BeltPath extends BasicSerializableObject { } // Store whether this is the first item we processed, so premature // item ejection is available - let isFirstItemProcessed: any = true; + let isFirstItemProcessed = true; // Store how much velocity (strictly its distance, not velocity) we have to distribute over all items - let remainingVelocity: any = beltSpeed; + let remainingVelocity = beltSpeed; // Store the last item we processed, so we can skip clashed ones - let lastItemProcessed: any; + let lastItemProcessed; for (lastItemProcessed = this.items.length - 1; lastItemProcessed >= 0; --lastItemProcessed) { - const nextDistanceAndItem: any = this.items[lastItemProcessed]; + const nextDistanceAndItem = this.items[lastItemProcessed]; // Compute how much spacing we need at least - const minimumSpacing: any = lastItemProcessed === this.items.length - 1 ? 0 : globalConfig.itemSpacingOnBelts; + const minimumSpacing = lastItemProcessed === this.items.length - 1 ? 0 : globalConfig.itemSpacingOnBelts; // Compute how much we can advance - let clampedProgress: any = nextDistanceAndItem[0 /* nextDistance */] - minimumSpacing; + let clampedProgress = nextDistanceAndItem[0 /* nextDistance */] - minimumSpacing; // Make sure we don't advance more than the remaining velocity has stored if (remainingVelocity < clampedProgress) { clampedProgress = remainingVelocity; @@ -800,18 +800,18 @@ export class BeltPath extends BasicSerializableObject { // Store how much velocity we "lost" because we bumped the item to the end of the // belt but couldn't move it any farther. We need this to tell the item acceptor // animation to start a tad later, so everything matches up. Yes I'm a perfectionist. - const excessVelocity: any = beltSpeed - clampedProgress; + const excessVelocity = beltSpeed - clampedProgress; // Try to directly get rid of the item if (this.boundAcceptor && this.boundAcceptor(nextDistanceAndItem[1 /* item */], excessVelocity)) { this.items.pop(); - const itemBehind: any = this.items[lastItemProcessed - 1]; + const itemBehind = this.items[lastItemProcessed - 1]; if (itemBehind && this.numCompressedItemsAfterFirstItem > 0) { // So, with the next tick we will skip this item, but it actually has the potential // to process farther -> If we don't advance here, we loose a tiny bit of progress // every tick which causes the belt to be slower than it actually is. // Also see #999 - const fixupProgress: any = Math.max(0, Math.min(remainingVelocity, itemBehind[0 /* nextDistance */])); + const fixupProgress = Math.max(0, Math.min(remainingVelocity, itemBehind[0 /* nextDistance */])); // See above itemBehind[0 /* nextDistance */] -= fixupProgress; remainingVelocity -= fixupProgress; @@ -833,7 +833,7 @@ export class BeltPath extends BasicSerializableObject { // Compute compressed item count this.numCompressedItemsAfterFirstItem = Math.max(0, this.numCompressedItemsAfterFirstItem, this.items.length - 2 - lastItemProcessed); // Check if we have an item which is ready to be emitted - const lastItem: any = this.items[this.items.length - 1]; + const lastItem = this.items[this.items.length - 1]; if (lastItem && lastItem[0 /* nextDistance */] === 0) { if (this.boundAcceptor && this.boundAcceptor(lastItem[1 /* item */])) { this.items.pop(); @@ -849,34 +849,34 @@ export class BeltPath extends BasicSerializableObject { * {} */ computePositionFromProgress(progress: number): Vector { - let currentLength: any = 0; + let currentLength = 0; // floating point issues .. assert(progress <= this.totalLength + 0.02, "Progress too big: " + progress); - for (let i: any = 0; i < this.entityPath.length; ++i) { - const beltComp: any = this.entityPath[i].components.Belt; - const localLength: any = beltComp.getEffectiveLengthTiles(); + for (let i = 0; i < this.entityPath.length; ++i) { + const beltComp = this.entityPath[i].components.Belt; + const localLength = beltComp.getEffectiveLengthTiles(); if (currentLength + localLength >= progress || i === this.entityPath.length - 1) { // Min required here due to floating point issues - const localProgress: any = Math.min(1.0, progress - currentLength); + const localProgress = Math.min(1.0, progress - currentLength); assert(localProgress >= 0.0, "Invalid local progress: " + localProgress); - const localSpace: any = beltComp.transformBeltToLocalSpace(localProgress); + const localSpace = beltComp.transformBeltToLocalSpace(localProgress); return this.entityPath[i].components.StaticMapEntity.localTileToWorld(localSpace); } currentLength += localLength; } assert(false, "invalid progress: " + progress + " (max: " + this.totalLength + ")"); } - drawDebug(parameters: DrawParameters): any { + drawDebug(parameters: DrawParameters) { if (!parameters.visibleRect.containsRect(this.worldBounds)) { return; } parameters.context.fillStyle = "#d79a25"; parameters.context.strokeStyle = "#d79a25"; parameters.context.beginPath(); - for (let i: any = 0; i < this.entityPath.length; ++i) { - const entity: any = this.entityPath[i]; - const pos: any = entity.components.StaticMapEntity; - const worldPos: any = pos.origin.toWorldSpaceCenterOfTile(); + for (let i = 0; i < this.entityPath.length; ++i) { + const entity = this.entityPath[i]; + const pos = entity.components.StaticMapEntity; + const worldPos = pos.origin.toWorldSpaceCenterOfTile(); if (i === 0) { parameters.context.moveTo(worldPos.x, worldPos.y); } @@ -886,10 +886,10 @@ export class BeltPath extends BasicSerializableObject { } parameters.context.stroke(); // Items - let progress: any = this.spacingToFirstItem; - for (let i: any = 0; i < this.items.length; ++i) { - const nextDistanceAndItem: any = this.items[i]; - const worldPos: any = this.computePositionFromProgress(progress).toWorldSpaceCenterOfTile(); + let progress = this.spacingToFirstItem; + for (let i = 0; i < this.items.length; ++i) { + const nextDistanceAndItem = this.items[i]; + const worldPos = this.computePositionFromProgress(progress).toWorldSpaceCenterOfTile(); parameters.context.fillStyle = "#268e4d"; parameters.context.beginRoundedRect(worldPos.x - 5, worldPos.y - 5, 10, 10, 3); parameters.context.fill(); @@ -902,28 +902,28 @@ export class BeltPath extends BasicSerializableObject { parameters.context.fillRect(worldPos.x + 5, worldPos.y, 20, 3); } } - for (let i: any = 0; i < this.entityPath.length; ++i) { - const entity: any = this.entityPath[i]; + for (let i = 0; i < this.entityPath.length; ++i) { + const entity = this.entityPath[i]; parameters.context.fillStyle = "#d79a25"; - const pos: any = entity.components.StaticMapEntity; - const worldPos: any = pos.origin.toWorldSpaceCenterOfTile(); + const pos = entity.components.StaticMapEntity; + const worldPos = pos.origin.toWorldSpaceCenterOfTile(); parameters.context.beginCircle(worldPos.x, worldPos.y, i === 0 ? 5 : 3); parameters.context.fill(); } - for (let progress: any = 0; progress <= this.totalLength + 0.01; progress += 0.2) { - const worldPos: any = this.computePositionFromProgress(progress).toWorldSpaceCenterOfTile(); + for (let progress = 0; progress <= this.totalLength + 0.01; progress += 0.2) { + const worldPos = this.computePositionFromProgress(progress).toWorldSpaceCenterOfTile(); parameters.context.fillStyle = "red"; parameters.context.beginCircle(worldPos.x, worldPos.y, 1); parameters.context.fill(); } - const firstItemIndicator: any = this.computePositionFromProgress(this.spacingToFirstItem).toWorldSpaceCenterOfTile(); + const firstItemIndicator = this.computePositionFromProgress(this.spacingToFirstItem).toWorldSpaceCenterOfTile(); parameters.context.fillStyle = "purple"; parameters.context.fillRect(firstItemIndicator.x - 3, firstItemIndicator.y - 1, 6, 2); } /** * Checks if this belt path should render simplified */ - checkIsPotatoMode(): any { + checkIsPotatoMode() { // POTATO Mode: Only show items when belt is hovered if (!this.root.app.settings.getAllSettings().simplifiedBelts) { return false; @@ -932,13 +932,13 @@ export class BeltPath extends BasicSerializableObject { // Not in regular layer return true; } - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (!mousePos) { // Mouse not registered return true; } - const tile: any = this.root.camera.screenToWorld(mousePos).toTileSpace(); - const contents: any = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); + const tile = this.root.camera.screenToWorld(mousePos).toTileSpace(); + const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); if (!contents || !contents.components.Belt) { // Nothing below return true; @@ -952,7 +952,7 @@ export class BeltPath extends BasicSerializableObject { /** * Draws the path */ - draw(parameters: DrawParameters): any { + draw(parameters: DrawParameters) { if (!parameters.visibleRect.containsRect(this.worldBounds)) { return; } @@ -961,43 +961,43 @@ export class BeltPath extends BasicSerializableObject { return; } if (this.checkIsPotatoMode()) { - const firstItem: any = this.items[0]; + const firstItem = this.items[0]; if (this.entityPath.length > 1 && firstItem) { - const medianBeltIndex: any = clamp(Math.round(this.entityPath.length / 2 - 1), 0, this.entityPath.length - 1); - const medianBelt: any = this.entityPath[medianBeltIndex]; - const beltComp: any = medianBelt.components.Belt; - const staticComp: any = medianBelt.components.StaticMapEntity; - const centerPosLocal: any = beltComp.transformBeltToLocalSpace(this.entityPath.length % 2 === 0 ? beltComp.getEffectiveLengthTiles() : 0.5); - const centerPos: any = staticComp.localTileToWorld(centerPosLocal).toWorldSpaceCenterOfTile(); + const medianBeltIndex = clamp(Math.round(this.entityPath.length / 2 - 1), 0, this.entityPath.length - 1); + const medianBelt = this.entityPath[medianBeltIndex]; + const beltComp = medianBelt.components.Belt; + const staticComp = medianBelt.components.StaticMapEntity; + const centerPosLocal = beltComp.transformBeltToLocalSpace(this.entityPath.length % 2 === 0 ? beltComp.getEffectiveLengthTiles() : 0.5); + const centerPos = staticComp.localTileToWorld(centerPosLocal).toWorldSpaceCenterOfTile(); parameters.context.globalAlpha = 0.5; firstItem[1 /* item */].drawItemCenteredClipped(centerPos.x, centerPos.y, parameters); parameters.context.globalAlpha = 1; } return; } - let currentItemPos: any = this.spacingToFirstItem; - let currentItemIndex: any = 0; - let trackPos: any = 0.0; + let currentItemPos = this.spacingToFirstItem; + let currentItemIndex = 0; + let trackPos = 0.0; let drawStack: Array<[ Vector, BaseItem ]> = []; - let drawStackProp: any = ""; + let drawStackProp = ""; // Iterate whole track and check items - for (let i: any = 0; i < this.entityPath.length; ++i) { - const entity: any = this.entityPath[i]; - const beltComp: any = entity.components.Belt; - const beltLength: any = beltComp.getEffectiveLengthTiles(); + for (let i = 0; i < this.entityPath.length; ++i) { + const entity = this.entityPath[i]; + const beltComp = entity.components.Belt; + const beltLength = beltComp.getEffectiveLengthTiles(); // Check if the current items are on the belt while (trackPos + beltLength >= currentItemPos - 1e-5) { // It's on the belt, render it now - const staticComp: any = entity.components.StaticMapEntity; + const staticComp = entity.components.StaticMapEntity; assert(currentItemPos - trackPos >= 0, "invalid track pos: " + currentItemPos + " vs " + trackPos + " (l =" + beltLength + ")"); - const localPos: any = beltComp.transformBeltToLocalSpace(currentItemPos - trackPos); - const worldPos: any = staticComp.localTileToWorld(localPos).toWorldSpaceCenterOfTile(); - const distanceAndItem: any = this.items[currentItemIndex]; - const item: any = distanceAndItem[1 /* item */]; - const nextItemDistance: any = distanceAndItem[0 /* nextDistance */]; + const localPos = beltComp.transformBeltToLocalSpace(currentItemPos - trackPos); + const worldPos = staticComp.localTileToWorld(localPos).toWorldSpaceCenterOfTile(); + const distanceAndItem = this.items[currentItemIndex]; + const item = distanceAndItem[1 /* item */]; + const nextItemDistance = distanceAndItem[0 /* nextDistance */]; if (!parameters.visibleRect.containsCircle(worldPos.x, worldPos.y, globalConfig.defaultItemDiameter)) { // this one isn't visible, do not append it // Start a new stack @@ -1008,7 +1008,7 @@ export class BeltPath extends BasicSerializableObject { else { if (drawStack.length > 1) { // Check if we can append to the stack, since its already a stack of two same items - const referenceItem: any = drawStack[0]; + const referenceItem = drawStack[0]; if (referenceItem[1].equals(item) && Math.abs(referenceItem[0][drawStackProp] - worldPos[drawStackProp]) < 0.001) { // Will continue stack @@ -1021,11 +1021,11 @@ export class BeltPath extends BasicSerializableObject { } } else if (drawStack.length === 1) { - const firstItem: any = drawStack[0]; + const firstItem = drawStack[0]; // Check if we can make it a stack if (firstItem[1 /* item */].equals(item)) { // Same item, check if it is either horizontal or vertical - const startPos: any = firstItem[0 /* pos */]; + const startPos = firstItem[0 /* pos */]; if (Math.abs(startPos.x - worldPos.x) < 0.001) { drawStackProp = "x"; } @@ -1079,23 +1079,23 @@ export class BeltPath extends BasicSerializableObject { ]>; root: GameRoot; zoomLevel: number; - }): any { + }) { context.scale(dpi, dpi); if (G_IS_DEV && globalConfig.debug.showShapeGrouping) { context.fillStyle = "rgba(0, 0, 255, 0.5)"; context.fillRect(0, 0, w, h); } - const parameters: any = new DrawParameters({ + const parameters = new DrawParameters({ context, desiredAtlasScale: ORIGINAL_SPRITE_SCALE, root, visibleRect: new Rectangle(-1000, -1000, 2000, 2000), zoomLevel, }); - const itemSize: any = globalConfig.itemSpacingOnBelts * globalConfig.tileSize; - const item: any = stack[0]; - const pos: any = new Vector(itemSize / 2, itemSize / 2); - for (let i: any = 0; i < stack.length; i++) { + const itemSize = globalConfig.itemSpacingOnBelts * globalConfig.tileSize; + const item = stack[0]; + const pos = new Vector(itemSize / 2, itemSize / 2); + for (let i = 0; i < stack.length; i++) { item[1].drawItemCenteredClipped(pos.x, pos.y, parameters, globalConfig.defaultItemDiameter); pos[direction] += globalConfig.itemSpacingOnBelts * globalConfig.tileSize; } @@ -1103,23 +1103,23 @@ export class BeltPath extends BasicSerializableObject { drawDrawStack(stack: Array<[ Vector, BaseItem - ]>, parameters: DrawParameters, directionProp: any): any { + ]>, parameters: DrawParameters, directionProp) { if (stack.length === 0) { return; } - const firstItem: any = stack[0]; - const firstItemPos: any = firstItem[0]; + const firstItem = stack[0]; + const firstItemPos = firstItem[0]; if (stack.length === 1) { firstItem[1].drawItemCenteredClipped(firstItemPos.x, firstItemPos.y, parameters, globalConfig.defaultItemDiameter); return; } - const itemSize: any = globalConfig.itemSpacingOnBelts * globalConfig.tileSize; - const inverseDirection: any = directionProp === "x" ? "y" : "x"; - const dimensions: any = new Vector(itemSize, itemSize); + const itemSize = globalConfig.itemSpacingOnBelts * globalConfig.tileSize; + const inverseDirection = directionProp === "x" ? "y" : "x"; + const dimensions = new Vector(itemSize, itemSize); dimensions[inverseDirection] *= stack.length; - const directionVector: any = firstItemPos.copy().sub(stack[1][0]); - const dpi: any = smoothenDpi(globalConfig.shapesSharpness * parameters.zoomLevel); - const sprite: any = this.root.buffers.getForKey({ + const directionVector = firstItemPos.copy().sub(stack[1][0]); + const dpi = smoothenDpi(globalConfig.shapesSharpness * parameters.zoomLevel); + const sprite = this.root.buffers.getForKey({ key: "beltpaths", subKey: "stack-" + directionProp + @@ -1142,7 +1142,7 @@ export class BeltPath extends BasicSerializableObject { zoomLevel: parameters.zoomLevel, }, }); - const anchor: any = directionVector[inverseDirection] < 0 ? firstItem : stack[stack.length - 1]; + const anchor = directionVector[inverseDirection] < 0 ? firstItem : stack[stack.length - 1]; parameters.context.drawImage(sprite, anchor[0].x - itemSize / 2, anchor[0].y - itemSize / 2, dimensions.x, dimensions.y); } } diff --git a/src/ts/game/blueprint.ts b/src/ts/game/blueprint.ts index 13e32017..a34517dd 100644 --- a/src/ts/game/blueprint.ts +++ b/src/ts/game/blueprint.ts @@ -23,21 +23,21 @@ export class Blueprint { /** * Creates a new blueprint from the given entity uids */ - static fromUids(root: GameRoot, uids: Array): any { - const newEntities: any = []; - let averagePosition: any = new Vector(); + static fromUids(root: GameRoot, uids: Array) { + const newEntities = []; + let averagePosition = new Vector(); // First, create a copy - for (let i: any = 0; i < uids.length; ++i) { - const entity: any = root.entityMgr.findByUid(uids[i]); + for (let i = 0; i < uids.length; ++i) { + const entity = root.entityMgr.findByUid(uids[i]); assert(entity, "Entity for blueprint not found:" + uids[i]); - const clone: any = entity.clone(); + const clone = entity.clone(); newEntities.push(clone); - const pos: any = entity.components.StaticMapEntity.getTileSpaceBounds().getCenter(); + const pos = entity.components.StaticMapEntity.getTileSpaceBounds().getCenter(); averagePosition.addInplace(pos); } averagePosition.divideScalarInplace(uids.length); - const blueprintOrigin: any = averagePosition.subScalars(0.5, 0.5).floor(); - for (let i: any = 0; i < uids.length; ++i) { + const blueprintOrigin = averagePosition.subScalars(0.5, 0.5).floor(); + for (let i = 0; i < uids.length; ++i) { newEntities[i].components.StaticMapEntity.origin.subInplace(blueprintOrigin); } // Now, make sure the origin is 0,0 @@ -46,7 +46,7 @@ export class Blueprint { /** * Returns the cost of this blueprint in shapes */ - getCost(): any { + getCost() { if (G_IS_DEV && globalConfig.debug.blueprintsNoCost) { return 0; } @@ -55,13 +55,13 @@ export class Blueprint { /** * Draws the blueprint at the given origin */ - draw(parameters: DrawParameters, tile: any): any { + draw(parameters: DrawParameters, tile) { parameters.context.globalAlpha = 0.8; - for (let i: any = 0; i < this.entities.length; ++i) { - const entity: any = this.entities[i]; - const staticComp: any = entity.components.StaticMapEntity; - const newPos: any = staticComp.origin.add(tile); - const rect: any = staticComp.getTileSpaceBounds(); + for (let i = 0; i < this.entities.length; ++i) { + const entity = this.entities[i]; + const staticComp = entity.components.StaticMapEntity; + const newPos = staticComp.origin.add(tile); + const rect = staticComp.getTileSpaceBounds(); rect.moveBy(tile.x, tile.y); if (!parameters.root.logic.checkCanPlaceEntity(entity, { offset: tile })) { parameters.context.globalAlpha = 0.3; @@ -76,10 +76,10 @@ export class Blueprint { /** * Rotates the blueprint clockwise */ - rotateCw(): any { - for (let i: any = 0; i < this.entities.length; ++i) { - const entity: any = this.entities[i]; - const staticComp: any = entity.components.StaticMapEntity; + rotateCw() { + for (let i = 0; i < this.entities.length; ++i) { + const entity = this.entities[i]; + const staticComp = entity.components.StaticMapEntity; // Actually keeping this in as an easter egg to rotate the trash can // if (staticComp.getMetaBuilding().getIsRotateable()) { staticComp.rotation = (staticComp.rotation + 90) % 360; @@ -91,26 +91,26 @@ export class Blueprint { /** * Rotates the blueprint counter clock wise */ - rotateCcw(): any { + rotateCcw() { // Well ... - for (let i: any = 0; i < 3; ++i) { + for (let i = 0; i < 3; ++i) { this.rotateCw(); } } /** * Checks if the blueprint can be placed at the given tile */ - canPlace(root: GameRoot, tile: Vector): any { - let anyPlaceable: any = false; - for (let i: any = 0; i < this.entities.length; ++i) { - const entity: any = this.entities[i]; + canPlace(root: GameRoot, tile: Vector) { + let anyPlaceable = false; + for (let i = 0; i < this.entities.length; ++i) { + const entity = this.entities[i]; if (root.logic.checkCanPlaceEntity(entity, { offset: tile })) { anyPlaceable = true; } } return anyPlaceable; } - canAfford(root: GameRoot): any { + canAfford(root: GameRoot) { if (root.gameMode.getHasFreeCopyPaste()) { return true; } @@ -119,16 +119,16 @@ export class Blueprint { /** * Attempts to place the blueprint at the given tile */ - tryPlace(root: GameRoot, tile: Vector): any { - return root.logic.performBulkOperation((): any => { - return root.logic.performImmutableOperation((): any => { - let count: any = 0; - for (let i: any = 0; i < this.entities.length; ++i) { - const entity: any = this.entities[i]; + tryPlace(root: GameRoot, tile: Vector) { + return root.logic.performBulkOperation(() => { + return root.logic.performImmutableOperation(() => { + let count = 0; + for (let i = 0; i < this.entities.length; ++i) { + const entity = this.entities[i]; if (!root.logic.checkCanPlaceEntity(entity, { offset: tile })) { continue; } - const clone: any = entity.clone(); + const clone = entity.clone(); clone.components.StaticMapEntity.origin.addInplace(tile); root.logic.freeEntityAreaBeforeBuild(clone); root.map.placeStaticEntity(clone); diff --git a/src/ts/game/building_codes.ts b/src/ts/game/building_codes.ts index 3d182707..2d3f9290 100644 --- a/src/ts/game/building_codes.ts +++ b/src/ts/game/building_codes.ts @@ -30,7 +30,7 @@ const variantsCache: Map = new Map(); /** * Registers a new variant */ -export function registerBuildingVariant(code: number | string, meta: typeof MetaBuilding, variant: string = "default" /* @TODO: Circular dependency, actually its defaultBuildingVariant */, rotationVariant: number = 0): any { +export function registerBuildingVariant(code: number | string, meta: typeof MetaBuilding, variant: string = "default" /* @TODO: Circular dependency, actually its defaultBuildingVariant */, rotationVariant: number = 0) { assert(!gBuildingVariants[code], "Duplicate id: " + code); gBuildingVariants[code] = { metaClass: meta, @@ -166,7 +166,7 @@ functiorateBuildingHash(build string, variant: strin * @param {number} rotationVariant * @returns */ -function generateBuildingHash(buildingId: string, variant: string, rotationVariant: number): any { +function generateBuildingHash(buildingId: string, variant: string, rotationVariant: number) { return buildingId + "/" + variant + "/" + rotationVariant; } /** @@ -180,10 +180,10 @@ export function getBuildingDataFromCode(code: string | number): BuildingVariantI /** * Builds the cache for the codes */ -export function buildBuildingCodeCache(): any { - for (const code: any in gBuildingVariants) { - const data: any = gBuildingVariants[code]; - const hash: any = generateBuildingHash(data.metaInstance.getId(), data.variant, data.rotationVariant); +export function buildBuildingCodeCache() { + for (const code in gBuildingVariants) { + const data = gBuildingVariants[code]; + const hash = generateBuildingHash(data.metaInstance.getId(), data.variant, data.rotationVariant); variantsCache.set(hash, isNaN(+code) ? code : +code); } } @@ -192,8 +192,8 @@ export function buildBuildingCodeCache(): any { * {} */ export function getCodeFromBuildingData(metaBuilding: MetaBuilding, variant: string, rotationVariant: number): number | string { - const hash: any = generateBuildingHash(metaBuilding.getId(), variant, rotationVariant); - const result: any = variantsCache.get(hash); + const hash = generateBuildingHash(metaBuilding.getId(), variant, rotationVariant); + const result = variantsCache.get(hash); if (G_IS_DEV) { if (!result) { console.warn("Known hashes:", Array.from(variantsCache.keys())); diff --git a/src/ts/game/buildings/analyzer.ts b/src/ts/game/buildings/analyzer.ts index 34ebf1b9..68aa9cb0 100644 --- a/src/ts/game/buildings/analyzer.ts +++ b/src/ts/game/buildings/analyzer.ts @@ -6,13 +6,13 @@ import { Entity } from "../entity"; import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; -const overlayMatrix: any = generateMatrixRotations([1, 1, 0, 1, 1, 1, 0, 1, 0]); +const overlayMatrix = generateMatrixRotations([1, 1, 0, 1, 1, 1, 0, 1, 0]); export class MetaAnalyzerBuilding extends MetaBuilding { constructor() { super("analyzer"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 43, @@ -20,30 +20,30 @@ export class MetaAnalyzerBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#3a52bc"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_virtual_processing); } /** {} **/ getLayer(): "wires" { return "wires"; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getRenderPins(): any { + getRenderPins() { // We already have it included return false; } - getSpecialOverlayRenderMatrix(rotation: any, rotationVariant: any, variant: any): any { + getSpecialOverlayRenderMatrix(rotation, rotationVariant, variant) { return overlayMatrix[rotation]; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/balancer.ts b/src/ts/game/buildings/balancer.ts index b3858891..2f16ac42 100644 --- a/src/ts/game/buildings/balancer.ts +++ b/src/ts/game/buildings/balancer.ts @@ -10,13 +10,13 @@ import { T } from "../../translations"; import { formatItemsPerSecond, generateMatrixRotations } from "../../core/utils"; import { BeltUnderlaysComponent } from "../components/belt_underlays"; /** @enum {string} */ -export const enumBalancerVariants: any = { +export const enumBalancerVariants = { merger: "merger", mergerInverse: "merger-inverse", splitter: "splitter", splitterInverse: "splitter-inverse", }; -const overlayMatrices: any = { +const overlayMatrices = { [defaultBuildingVariant]: null, [enumBalancerVariants.merger]: generateMatrixRotations([0, 1, 0, 0, 1, 1, 0, 1, 0]), [enumBalancerVariants.mergerInverse]: generateMatrixRotations([0, 1, 0, 1, 1, 0, 0, 1, 0]), @@ -28,7 +28,7 @@ export class MetaBalancerBuilding extends MetaBuilding { constructor() { super("balancer"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 4, @@ -52,7 +52,7 @@ export class MetaBalancerBuilding extends MetaBuilding { }, ]; } - getDimensions(variant: any): any { + getDimensions(variant) { switch (variant) { case defaultBuildingVariant: return new Vector(2, 1); @@ -69,7 +69,7 @@ export class MetaBalancerBuilding extends MetaBuilding { * {} */ getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity): Array | null { - const matrix: any = overlayMatrices[variant]; + const matrix = overlayMatrices[variant]; if (matrix) { return matrix[rotation]; } @@ -85,7 +85,7 @@ export class MetaBalancerBuilding extends MetaBuilding { if (root.gameMode.throughputDoesNotMatter()) { return []; } - let speedMultiplier: any = 2; + let speedMultiplier = 2; switch (variant) { case enumBalancerVariants.merger: case enumBalancerVariants.mergerInverse: @@ -93,15 +93,15 @@ export class MetaBalancerBuilding extends MetaBuilding { case enumBalancerVariants.splitterInverse: speedMultiplier = 1; } - const speed: any = (root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.balancer) / 2) * speedMultiplier; + const speed = (root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.balancer) / 2) * speedMultiplier; return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#555759"; } - getAvailableVariants(root: GameRoot): any { - const deterministic: any = root.gameMode.getIsDeterministic(); - let available: any = deterministic ? [] : [defaultBuildingVariant]; + getAvailableVariants(root: GameRoot) { + const deterministic = root.gameMode.getIsDeterministic(); + let available = deterministic ? [] : [defaultBuildingVariant]; if (!deterministic && root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_merger)) { available.push(enumBalancerVariants.merger, enumBalancerVariants.mergerInverse); } @@ -110,13 +110,13 @@ export class MetaBalancerBuilding extends MetaBuilding { } return available; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_balancer); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemAcceptorComponent({ slots: [], // set later })); @@ -130,7 +130,7 @@ export class MetaBalancerBuilding extends MetaBuilding { })); entity.addComponent(new BeltUnderlaysComponent({ underlays: [] })); } - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { + updateVariants(entity: Entity, rotationVariant: number, variant: string) { switch (variant) { case defaultBuildingVariant: { entity.components.ItemAcceptor.setSlots([ diff --git a/src/ts/game/buildings/belt.ts b/src/ts/game/buildings/belt.ts index 6180859c..1d5aedcb 100644 --- a/src/ts/game/buildings/belt.ts +++ b/src/ts/game/buildings/belt.ts @@ -8,8 +8,8 @@ import { Entity } from "../entity"; import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { THEME } from "../theme"; -export const arrayBeltVariantToRotation: any = [enumDirection.top, enumDirection.left, enumDirection.right]; -export const beltOverlayMatrices: any = { +export const arrayBeltVariantToRotation = [enumDirection.top, enumDirection.left, enumDirection.right]; +export const beltOverlayMatrices = { [enumDirection.top]: generateMatrixRotations([0, 1, 0, 0, 1, 0, 0, 1, 0]), [enumDirection.left]: generateMatrixRotations([0, 0, 0, 1, 1, 0, 0, 1, 0]), [enumDirection.right]: generateMatrixRotations([0, 0, 0, 0, 1, 1, 0, 1, 0]), @@ -19,7 +19,7 @@ export class MetaBeltBuilding extends MetaBuilding { constructor() { super("belt"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 1, @@ -38,25 +38,25 @@ export class MetaBeltBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return THEME.map.chunkOverview.beltColor; } - getPlacementSound(): any { + getPlacementSound() { return SOUNDS.placeBelt; } - getHasDirectionLockAvailable(): any { + getHasDirectionLockAvailable() { return true; } - getStayInPlacementMode(): any { + getStayInPlacementMode() { return true; } - getRotateAutomaticallyWhilePlacing(): any { + getRotateAutomaticallyWhilePlacing() { return true; } - getSprite(): any { + getSprite() { return null; } - getIsReplaceable(): any { + getIsReplaceable() { return true; } /** @@ -69,10 +69,10 @@ export class MetaBeltBuilding extends MetaBuilding { if (root.gameMode.throughputDoesNotMatter()) { return []; } - const beltSpeed: any = root.hubGoals.getBeltBaseSpeed(); + const beltSpeed = root.hubGoals.getBeltBaseSpeed(); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(beltSpeed)]]; } - getPreviewSprite(rotationVariant: any): any { + getPreviewSprite(rotationVariant) { switch (arrayBeltVariantToRotation[rotationVariant]) { case enumDirection.top: { return Loader.getSprite("sprites/buildings/belt_top.png"); @@ -88,7 +88,7 @@ export class MetaBeltBuilding extends MetaBuilding { } } } - getBlueprintSprite(rotationVariant: any): any { + getBlueprintSprite(rotationVariant) { switch (arrayBeltVariantToRotation[rotationVariant]) { case enumDirection.top: { return Loader.getSprite("sprites/blueprints/belt_top.png"); @@ -104,18 +104,18 @@ export class MetaBeltBuilding extends MetaBuilding { } } } - getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity): any { + getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity) { return beltOverlayMatrices[entity.components.Belt.direction][rotation]; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new BeltComponent({ direction: enumDirection.top, // updated later })); } - updateVariants(entity: Entity, rotationVariant: number): any { + updateVariants(entity: Entity, rotationVariant: number) { entity.components.Belt.direction = arrayBeltVariantToRotation[rotationVariant]; } /** @@ -133,20 +133,20 @@ export class MetaBeltBuilding extends MetaBuilding { rotationVariant: number; connectedEntities?: Array; } { - const topDirection: any = enumAngleToDirection[rotation]; - const rightDirection: any = enumAngleToDirection[(rotation + 90) % 360]; - const bottomDirection: any = enumAngleToDirection[(rotation + 180) % 360]; - const leftDirection: any = enumAngleToDirection[(rotation + 270) % 360]; - const { ejectors, acceptors }: any = root.logic.getEjectorsAndAcceptorsAtTile(tile); - let hasBottomEjector: any = false; - let hasRightEjector: any = false; - let hasLeftEjector: any = false; - let hasTopAcceptor: any = false; - let hasLeftAcceptor: any = false; - let hasRightAcceptor: any = false; + const topDirection = enumAngleToDirection[rotation]; + const rightDirection = enumAngleToDirection[(rotation + 90) % 360]; + const bottomDirection = enumAngleToDirection[(rotation + 180) % 360]; + const leftDirection = enumAngleToDirection[(rotation + 270) % 360]; + const { ejectors, acceptors } = root.logic.getEjectorsAndAcceptorsAtTile(tile); + let hasBottomEjector = false; + let hasRightEjector = false; + let hasLeftEjector = false; + let hasTopAcceptor = false; + let hasLeftAcceptor = false; + let hasRightAcceptor = false; // Check all ejectors - for (let i: any = 0; i < ejectors.length; ++i) { - const ejector: any = ejectors[i]; + for (let i = 0; i < ejectors.length; ++i) { + const ejector = ejectors[i]; if (ejector.toDirection === topDirection) { hasBottomEjector = true; } @@ -158,8 +158,8 @@ export class MetaBeltBuilding extends MetaBuilding { } } // Check all acceptors - for (let i: any = 0; i < acceptors.length; ++i) { - const acceptor: any = acceptors[i]; + for (let i = 0; i < acceptors.length; ++i) { + const acceptor = acceptors[i]; if (acceptor.fromDirection === bottomDirection) { hasTopAcceptor = true; } diff --git a/src/ts/game/buildings/block.ts b/src/ts/game/buildings/block.ts index 77bbd227..243764c8 100644 --- a/src/ts/game/buildings/block.ts +++ b/src/ts/game/buildings/block.ts @@ -7,7 +7,7 @@ export class MetaBlockBuilding extends MetaBuilding { constructor() { super("block"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 64, @@ -15,7 +15,7 @@ export class MetaBlockBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#333"; } /** @@ -138,11 +138,11 @@ export class MetaBlockBuilding extends MetaBuilding { * @param {import("../../savegame/savegame_serializer").GameRoot} root * @returns */ - getIsRemovable(root: import("../../savegame/savegame_serializer").GameRoot): any { + getIsRemovable(root: import("../../savegame/savegame_serializer").GameRoot) { return root.gameMode.getIsEditor(); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { } + setupEntityComponents(entity: Entity) { } } diff --git a/src/ts/game/buildings/comparator.ts b/src/ts/game/buildings/comparator.ts index 70759282..5a95f865 100644 --- a/src/ts/game/buildings/comparator.ts +++ b/src/ts/game/buildings/comparator.ts @@ -10,7 +10,7 @@ export class MetaComparatorBuilding extends MetaBuilding { constructor() { super("comparator"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 46, @@ -18,27 +18,27 @@ export class MetaComparatorBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#823cab"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_virtual_processing); } /** {} **/ getLayer(): "wires" { return "wires"; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getRenderPins(): any { + getRenderPins() { // We already have it included return false; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/constant_producer.ts b/src/ts/game/buildings/constant_producer.ts index 858b14ea..c6d07e27 100644 --- a/src/ts/game/buildings/constant_producer.ts +++ b/src/ts/game/buildings/constant_producer.ts @@ -11,7 +11,7 @@ export class MetaConstantProducerBuilding extends MetaBuilding { constructor() { super("constant_producer"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 62, @@ -19,7 +19,7 @@ export class MetaConstantProducerBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#bfd630"; } /** @@ -142,13 +142,13 @@ export class MetaConstantProducerBuilding extends MetaBuilding { * @param {import("../../savegame/savegame_serializer").GameRoot} root * @returns */ - getIsRemovable(root: import("../../savegame/savegame_serializer").GameRoot): any { + getIsRemovable(root: import("../../savegame/savegame_serializer").GameRoot) { return root.gameMode.getIsEditor(); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemEjectorComponent({ slots: [{ pos: new Vector(0, 0), direction: enumDirection.top }], })); diff --git a/src/ts/game/buildings/constant_signal.ts b/src/ts/game/buildings/constant_signal.ts index 2141967e..df915e66 100644 --- a/src/ts/game/buildings/constant_signal.ts +++ b/src/ts/game/buildings/constant_signal.ts @@ -6,13 +6,13 @@ import { GameRoot } from "../root"; import { ConstantSignalComponent } from "../components/constant_signal"; import { generateMatrixRotations } from "../../core/utils"; import { enumHubGoalRewards } from "../tutorial_goals"; -const overlayMatrix: any = generateMatrixRotations([0, 1, 0, 1, 1, 1, 1, 1, 1]); +const overlayMatrix = generateMatrixRotations([0, 1, 0, 1, 1, 1, 1, 1, 1]); export class MetaConstantSignalBuilding extends MetaBuilding { constructor() { super("constant_signal"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 31, @@ -20,29 +20,29 @@ export class MetaConstantSignalBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#2b84fd"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_constant_signal); } /** {} **/ getLayer(): "wires" { return "wires"; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getRenderPins(): any { + getRenderPins() { return false; } - getSpecialOverlayRenderMatrix(rotation: any): any { + getSpecialOverlayRenderMatrix(rotation) { return overlayMatrix[rotation]; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/cutter.ts b/src/ts/game/buildings/cutter.ts index 0d36455c..52306fbc 100644 --- a/src/ts/game/buildings/cutter.ts +++ b/src/ts/game/buildings/cutter.ts @@ -9,13 +9,13 @@ import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; /** @enum {string} */ -export const enumCutterVariants: any = { quad: "quad" }; +export const enumCutterVariants = { quad: "quad" }; export class MetaCutterBuilding extends MetaBuilding { constructor() { super("cutter"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 9, @@ -27,10 +27,10 @@ export class MetaCutterBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#7dcda2"; } - getDimensions(variant: any): any { + getDimensions(variant) { switch (variant) { case defaultBuildingVariant: return new Vector(2, 1); @@ -50,24 +50,24 @@ export class MetaCutterBuilding extends MetaBuilding { if (root.gameMode.throughputDoesNotMatter()) { return []; } - const speed: any = root.hubGoals.getProcessorBaseSpeed(variant === enumCutterVariants.quad + const speed = root.hubGoals.getProcessorBaseSpeed(variant === enumCutterVariants.quad ? enumItemProcessorTypes.cutterQuad : enumItemProcessorTypes.cutter); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } - getAvailableVariants(root: GameRoot): any { + getAvailableVariants(root: GameRoot) { if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_cutter_quad)) { return [defaultBuildingVariant, enumCutterVariants.quad]; } return super.getAvailableVariants(root); } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_cutter_and_trash); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemProcessorComponent({ inputsPerCharge: 1, processorType: enumItemProcessorTypes.cutter, @@ -83,7 +83,7 @@ export class MetaCutterBuilding extends MetaBuilding { ], })); } - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { + updateVariants(entity: Entity, rotationVariant: number, variant: string) { switch (variant) { case defaultBuildingVariant: { entity.components.ItemEjector.setSlots([ diff --git a/src/ts/game/buildings/display.ts b/src/ts/game/buildings/display.ts index 3dd3d2b8..42a66fc7 100644 --- a/src/ts/game/buildings/display.ts +++ b/src/ts/game/buildings/display.ts @@ -10,7 +10,7 @@ export class MetaDisplayBuilding extends MetaBuilding { constructor() { super("display"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 40, @@ -18,22 +18,22 @@ export class MetaDisplayBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#aaaaaa"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_display); } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getShowWiresLayerPreview(): any { + getShowWiresLayerPreview() { return true; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/filter.ts b/src/ts/game/buildings/filter.ts index 8ecbdab4..4ef78fa9 100644 --- a/src/ts/game/buildings/filter.ts +++ b/src/ts/game/buildings/filter.ts @@ -14,7 +14,7 @@ export class MetaFilterBuilding extends MetaBuilding { constructor() { super("filter"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 37, @@ -22,16 +22,16 @@ export class MetaFilterBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#c45c2e"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_filter); } - getDimensions(): any { + getDimensions() { return new Vector(2, 1); } - getShowWiresLayerPreview(): any { + getShowWiresLayerPreview() { return true; } /** @@ -44,13 +44,13 @@ export class MetaFilterBuilding extends MetaBuilding { if (root.gameMode.throughputDoesNotMatter()) { return []; } - const beltSpeed: any = root.hubGoals.getBeltBaseSpeed(); + const beltSpeed = root.hubGoals.getBeltBaseSpeed(); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(beltSpeed)]]; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/goal_acceptor.ts b/src/ts/game/buildings/goal_acceptor.ts index 3ce6fbc9..7ad1a3c9 100644 --- a/src/ts/game/buildings/goal_acceptor.ts +++ b/src/ts/game/buildings/goal_acceptor.ts @@ -11,7 +11,7 @@ export class MetaGoalAcceptorBuilding extends MetaBuilding { constructor() { super("goal_acceptor"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 63, @@ -19,7 +19,7 @@ export class MetaGoalAcceptorBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#ce418a"; } /** @@ -142,13 +142,13 @@ export class MetaGoalAcceptorBuilding extends MetaBuilding { * @param {import("../../savegame/savegame_serializer").GameRoot} root * @returns */ - getIsRemovable(root: import("../../savegame/savegame_serializer").GameRoot): any { + getIsRemovable(root: import("../../savegame/savegame_serializer").GameRoot) { return root.gameMode.getIsEditor(); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemAcceptorComponent({ slots: [ { diff --git a/src/ts/game/buildings/hub.ts b/src/ts/game/buildings/hub.ts index d7b0df4e..004f9f5f 100644 --- a/src/ts/game/buildings/hub.ts +++ b/src/ts/game/buildings/hub.ts @@ -10,7 +10,7 @@ export class MetaHubBuilding extends MetaBuilding { constructor() { super("hub"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 26, @@ -18,29 +18,29 @@ export class MetaHubBuilding extends MetaBuilding { }, ]; } - getDimensions(): any { + getDimensions() { return new Vector(4, 4); } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#eb5555"; } - getIsRotateable(): any { + getIsRotateable() { return false; } - getBlueprintSprite(): any { + getBlueprintSprite() { return null; } - getSprite(): any { + getSprite() { // We render it ourself return null; } - getIsRemovable(): any { + getIsRemovable() { return false; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new HubComponent()); entity.addComponent(new ItemProcessorComponent({ inputsPerCharge: 1, @@ -56,7 +56,7 @@ export class MetaHubBuilding extends MetaBuilding { ], })); const slots: Array = []; - for (let i: any = 0; i < 4; ++i) { + for (let i = 0; i < 4; ++i) { slots.push({ pos: new Vector(i, 0), direction: enumDirection.top, filter: "shape" }, { pos: new Vector(i, 3), direction: enumDirection.bottom, filter: "shape" }, { pos: new Vector(0, i), direction: enumDirection.left, filter: "shape" }, { pos: new Vector(3, i), direction: enumDirection.right, filter: "shape" }); } entity.addComponent(new ItemAcceptorComponent({ diff --git a/src/ts/game/buildings/item_producer.ts b/src/ts/game/buildings/item_producer.ts index e3e0373a..322bc617 100644 --- a/src/ts/game/buildings/item_producer.ts +++ b/src/ts/game/buildings/item_producer.ts @@ -9,7 +9,7 @@ export class MetaItemProducerBuilding extends MetaBuilding { constructor() { super("item_producer"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 61, @@ -17,16 +17,16 @@ export class MetaItemProducerBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#b37dcd"; } - getShowWiresLayerPreview(): any { + getShowWiresLayerPreview() { return true; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemEjectorComponent({ slots: [{ pos: new Vector(0, 0), direction: enumDirection.top }], })); diff --git a/src/ts/game/buildings/lever.ts b/src/ts/game/buildings/lever.ts index 878ec215..535d94e3 100644 --- a/src/ts/game/buildings/lever.ts +++ b/src/ts/game/buildings/lever.ts @@ -10,7 +10,7 @@ export class MetaLeverBuilding extends MetaBuilding { constructor() { super("lever"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 33, @@ -18,26 +18,26 @@ export class MetaLeverBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { // @todo: Render differently based on if its activated or not return "#1a678b"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_wires_painter_and_levers); } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getSprite(): any { + getSprite() { return null; } - getShowWiresLayerPreview(): any { + getShowWiresLayerPreview() { return true; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/logic_gate.ts b/src/ts/game/buildings/logic_gate.ts index 525bd2fb..6f6d0677 100644 --- a/src/ts/game/buildings/logic_gate.ts +++ b/src/ts/game/buildings/logic_gate.ts @@ -7,25 +7,25 @@ import { enumLogicGateType, LogicGateComponent } from "../components/logic_gate" import { generateMatrixRotations } from "../../core/utils"; import { enumHubGoalRewards } from "../tutorial_goals"; /** @enum {string} */ -export const enumLogicGateVariants: any = { +export const enumLogicGateVariants = { not: "not", xor: "xor", or: "or", }; /** @enum {string} */ -const enumVariantToGate: any = { +const enumVariantToGate = { [defaultBuildingVariant]: enumLogicGateType.and, [enumLogicGateVariants.not]: enumLogicGateType.not, [enumLogicGateVariants.xor]: enumLogicGateType.xor, [enumLogicGateVariants.or]: enumLogicGateType.or, }; -const overlayMatrices: any = { +const overlayMatrices = { [defaultBuildingVariant]: generateMatrixRotations([0, 1, 0, 1, 1, 1, 0, 1, 1]), [enumLogicGateVariants.xor]: generateMatrixRotations([0, 1, 0, 1, 1, 1, 0, 1, 1]), [enumLogicGateVariants.or]: generateMatrixRotations([0, 1, 0, 1, 1, 1, 0, 1, 1]), [enumLogicGateVariants.not]: generateMatrixRotations([0, 1, 0, 0, 1, 0, 0, 1, 0]), }; -const colors: any = { +const colors = { [defaultBuildingVariant]: "#f48d41", [enumLogicGateVariants.xor]: "#f4a241", [enumLogicGateVariants.or]: "#f4d041", @@ -36,7 +36,7 @@ export class MetaLogicGateBuilding extends MetaBuilding { constructor() { super("logic_gate"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 32, @@ -56,23 +56,23 @@ export class MetaLogicGateBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(variant: any): any { + getSilhouetteColor(variant) { return colors[variant]; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_logic_gates); } /** {} **/ getLayer(): "wires" { return "wires"; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getSpecialOverlayRenderMatrix(rotation: any, rotationVariant: any, variant: any): any { + getSpecialOverlayRenderMatrix(rotation, rotationVariant, variant) { return overlayMatrices[variant][rotation]; } - getAvailableVariants(): any { + getAvailableVariants() { return [ defaultBuildingVariant, enumLogicGateVariants.or, @@ -80,14 +80,14 @@ export class MetaLogicGateBuilding extends MetaBuilding { enumLogicGateVariants.xor, ]; } - getRenderPins(): any { + getRenderPins() { // We already have it included return false; } - updateVariants(entity: Entity, rotationVariant: number, variant: any): any { - const gateType: any = enumVariantToGate[variant]; + updateVariants(entity: Entity, rotationVariant: number, variant) { + const gateType = enumVariantToGate[variant]; entity.components.LogicGate.type = gateType; - const pinComp: any = entity.components.WiredPins; + const pinComp = entity.components.WiredPins; switch (gateType) { case enumLogicGateType.and: case enumLogicGateType.xor: @@ -133,7 +133,7 @@ export class MetaLogicGateBuilding extends MetaBuilding { /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [], })); diff --git a/src/ts/game/buildings/miner.ts b/src/ts/game/buildings/miner.ts index 10566789..b296f7ba 100644 --- a/src/ts/game/buildings/miner.ts +++ b/src/ts/game/buildings/miner.ts @@ -8,8 +8,8 @@ import { enumHubGoalRewards } from "../tutorial_goals"; import { T } from "../../translations"; import { formatItemsPerSecond, generateMatrixRotations } from "../../core/utils"; /** @enum {string} */ -export const enumMinerVariants: any = { chainable: "chainable" }; -const overlayMatrix: any = { +export const enumMinerVariants = { chainable: "chainable" }; +const overlayMatrix = { [defaultBuildingVariant]: generateMatrixRotations([1, 1, 1, 1, 0, 1, 1, 1, 1]), [enumMinerVariants.chainable]: generateMatrixRotations([0, 1, 0, 1, 1, 1, 1, 1, 1]), }; @@ -18,7 +18,7 @@ export class MetaMinerBuilding extends MetaBuilding { constructor() { super("miner"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 7, @@ -30,7 +30,7 @@ export class MetaMinerBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#b37dcd"; } /** @@ -43,28 +43,28 @@ export class MetaMinerBuilding extends MetaBuilding { if (root.gameMode.throughputDoesNotMatter()) { return []; } - const speed: any = root.hubGoals.getMinerBaseSpeed(); + const speed = root.hubGoals.getMinerBaseSpeed(); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } - getAvailableVariants(root: GameRoot): any { + getAvailableVariants(root: GameRoot) { if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_miner_chainable)) { return [enumMinerVariants.chainable]; } return super.getAvailableVariants(root); } - getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity): any { + getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity) { return overlayMatrix[variant][rotation]; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new MinerComponent({})); entity.addComponent(new ItemEjectorComponent({ slots: [{ pos: new Vector(0, 0), direction: enumDirection.top }], })); } - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { + updateVariants(entity: Entity, rotationVariant: number, variant: string) { entity.components.Miner.chainable = variant === enumMinerVariants.chainable; } } diff --git a/src/ts/game/buildings/mixer.ts b/src/ts/game/buildings/mixer.ts index 081e358c..b27ac015 100644 --- a/src/ts/game/buildings/mixer.ts +++ b/src/ts/game/buildings/mixer.ts @@ -13,7 +13,7 @@ export class MetaMixerBuilding extends MetaBuilding { constructor() { super("mixer"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 15, @@ -21,13 +21,13 @@ export class MetaMixerBuilding extends MetaBuilding { }, ]; } - getDimensions(): any { + getDimensions() { return new Vector(2, 1); } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#cdbb7d"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_mixer); } /** @@ -40,13 +40,13 @@ export class MetaMixerBuilding extends MetaBuilding { if (root.gameMode.throughputDoesNotMatter()) { return []; } - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.mixer); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.mixer); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemProcessorComponent({ inputsPerCharge: 2, processorType: enumItemProcessorTypes.mixer, diff --git a/src/ts/game/buildings/painter.ts b/src/ts/game/buildings/painter.ts index c3a9d31c..378e5475 100644 --- a/src/ts/game/buildings/painter.ts +++ b/src/ts/game/buildings/painter.ts @@ -10,13 +10,13 @@ import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; import { WiredPinsComponent, enumPinSlotType } from "../components/wired_pins"; /** @enum {string} */ -export const enumPainterVariants: any = { mirrored: "mirrored", double: "double", quad: "quad" }; +export const enumPainterVariants = { mirrored: "mirrored", double: "double", quad: "quad" }; export class MetaPainterBuilding extends MetaBuilding { constructor() { super("painter"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 16, @@ -36,7 +36,7 @@ export class MetaPainterBuilding extends MetaBuilding { }, ]; } - getDimensions(variant: any): any { + getDimensions(variant) { switch (variant) { case defaultBuildingVariant: case enumPainterVariants.mirrored: @@ -49,7 +49,7 @@ export class MetaPainterBuilding extends MetaBuilding { assertAlways(false, "Unknown painter variant: " + variant); } } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#cd9b7d"; } /** @@ -65,21 +65,21 @@ export class MetaPainterBuilding extends MetaBuilding { switch (variant) { case defaultBuildingVariant: case enumPainterVariants.mirrored: { - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.painter); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.painter); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } case enumPainterVariants.double: { - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.painterDouble); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.painterDouble); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed, true)]]; } case enumPainterVariants.quad: { - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.painterQuad); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.painterQuad); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } } } - getAvailableVariants(root: GameRoot): any { - let variants: any = [defaultBuildingVariant, enumPainterVariants.mirrored]; + getAvailableVariants(root: GameRoot) { + let variants = [defaultBuildingVariant, enumPainterVariants.mirrored]; if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_painter_double)) { variants.push(enumPainterVariants.double); } @@ -89,13 +89,13 @@ export class MetaPainterBuilding extends MetaBuilding { } return variants; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_painter); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemProcessorComponent({})); entity.addComponent(new ItemEjectorComponent({ slots: [{ pos: new Vector(1, 0), direction: enumDirection.right }], @@ -115,7 +115,7 @@ export class MetaPainterBuilding extends MetaBuilding { ], })); } - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { + updateVariants(entity: Entity, rotationVariant: number, variant: string) { switch (variant) { case defaultBuildingVariant: case enumPainterVariants.mirrored: { diff --git a/src/ts/game/buildings/reader.ts b/src/ts/game/buildings/reader.ts index c41bad0f..b8e0511a 100644 --- a/src/ts/game/buildings/reader.ts +++ b/src/ts/game/buildings/reader.ts @@ -10,13 +10,13 @@ import { BeltUnderlaysComponent } from "../components/belt_underlays"; import { BeltReaderComponent } from "../components/belt_reader"; import { enumHubGoalRewards } from "../tutorial_goals"; import { generateMatrixRotations } from "../../core/utils"; -const overlayMatrix: any = generateMatrixRotations([0, 1, 0, 0, 1, 0, 0, 1, 0]); +const overlayMatrix = generateMatrixRotations([0, 1, 0, 0, 1, 0, 0, 1, 0]); export class MetaReaderBuilding extends MetaBuilding { constructor() { super("reader"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 49, @@ -24,16 +24,16 @@ export class MetaReaderBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#25fff2"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_belt_reader); } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getShowWiresLayerPreview(): any { + getShowWiresLayerPreview() { return true; } /** @@ -45,7 +45,7 @@ export class MetaReaderBuilding extends MetaBuilding { /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/rotater.ts b/src/ts/game/buildings/rotater.ts index 254f9af8..d93484e5 100644 --- a/src/ts/game/buildings/rotater.ts +++ b/src/ts/game/buildings/rotater.ts @@ -9,8 +9,8 @@ import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; /** @enum {string} */ -export const enumRotaterVariants: any = { ccw: "ccw", rotate180: "rotate180" }; -const overlayMatrices: any = { +export const enumRotaterVariants = { ccw: "ccw", rotate180: "rotate180" }; +const overlayMatrices = { [defaultBuildingVariant]: generateMatrixRotations([0, 1, 1, 1, 1, 0, 0, 1, 1]), [enumRotaterVariants.ccw]: generateMatrixRotations([1, 1, 0, 0, 1, 1, 1, 1, 0]), [enumRotaterVariants.rotate180]: generateMatrixRotations([1, 1, 0, 1, 1, 1, 0, 1, 1]), @@ -20,7 +20,7 @@ export class MetaRotaterBuilding extends MetaBuilding { constructor() { super("rotater"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 11, @@ -36,14 +36,14 @@ export class MetaRotaterBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#7dc6cd"; } /** * {} */ getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity): Array | null { - const matrix: any = overlayMatrices[variant]; + const matrix = overlayMatrices[variant]; if (matrix) { return matrix[rotation]; } @@ -61,21 +61,21 @@ export class MetaRotaterBuilding extends MetaBuilding { } switch (variant) { case defaultBuildingVariant: { - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.rotater); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.rotater); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } case enumRotaterVariants.ccw: { - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.rotaterCCW); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.rotaterCCW); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } case enumRotaterVariants.rotate180: { - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.rotater180); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.rotater180); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } } } - getAvailableVariants(root: GameRoot): any { - let variants: any = [defaultBuildingVariant]; + getAvailableVariants(root: GameRoot) { + let variants = [defaultBuildingVariant]; if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_rotater_ccw)) { variants.push(enumRotaterVariants.ccw); } @@ -84,13 +84,13 @@ export class MetaRotaterBuilding extends MetaBuilding { } return variants; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_rotater); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemProcessorComponent({ inputsPerCharge: 1, processorType: enumItemProcessorTypes.rotater, @@ -108,7 +108,7 @@ export class MetaRotaterBuilding extends MetaBuilding { ], })); } - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { + updateVariants(entity: Entity, rotationVariant: number, variant: string) { switch (variant) { case defaultBuildingVariant: { entity.components.ItemProcessor.type = enumItemProcessorTypes.rotater; diff --git a/src/ts/game/buildings/stacker.ts b/src/ts/game/buildings/stacker.ts index 4fa6c052..dadfcc36 100644 --- a/src/ts/game/buildings/stacker.ts +++ b/src/ts/game/buildings/stacker.ts @@ -13,7 +13,7 @@ export class MetaStackerBuilding extends MetaBuilding { constructor() { super("stacker"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 14, @@ -21,10 +21,10 @@ export class MetaStackerBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#9fcd7d"; } - getDimensions(): any { + getDimensions() { return new Vector(2, 1); } /** @@ -37,16 +37,16 @@ export class MetaStackerBuilding extends MetaBuilding { if (root.gameMode.throughputDoesNotMatter()) { return []; } - const speed: any = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.stacker); + const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.stacker); return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]]; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_stacker); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemProcessorComponent({ inputsPerCharge: 2, processorType: enumItemProcessorTypes.stacker, diff --git a/src/ts/game/buildings/storage.ts b/src/ts/game/buildings/storage.ts index e6030779..5554ccdc 100644 --- a/src/ts/game/buildings/storage.ts +++ b/src/ts/game/buildings/storage.ts @@ -9,13 +9,13 @@ import { Entity } from "../entity"; import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; -const storageSize: any = 5000; +const storageSize = 5000; export class MetaStorageBuilding extends MetaBuilding { constructor() { super("storage"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 21, @@ -23,28 +23,28 @@ export class MetaStorageBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#bbdf6d"; } /** * {} */ - getAdditionalStatistics(root: any, variant: any): Array<[ + getAdditionalStatistics(root, variant): Array<[ string, string ]> { return [[T.ingame.buildingPlacement.infoTexts.storage, formatBigNumber(storageSize)]]; } - getDimensions(): any { + getDimensions() { return new Vector(2, 2); } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_storage); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { // Required, since the item processor needs this. entity.addComponent(new ItemEjectorComponent({ slots: [ diff --git a/src/ts/game/buildings/transistor.ts b/src/ts/game/buildings/transistor.ts index 66221f7d..e94ea71a 100644 --- a/src/ts/game/buildings/transistor.ts +++ b/src/ts/game/buildings/transistor.ts @@ -7,10 +7,10 @@ import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; /** @enum {string} */ -export const enumTransistorVariants: any = { +export const enumTransistorVariants = { mirrored: "mirrored", }; -const overlayMatrices: any = { +const overlayMatrices = { [defaultBuildingVariant]: generateMatrixRotations([0, 1, 0, 1, 1, 0, 0, 1, 0]), [enumTransistorVariants.mirrored]: generateMatrixRotations([0, 1, 0, 0, 1, 1, 0, 1, 0]), }; @@ -19,7 +19,7 @@ export class MetaTransistorBuilding extends MetaBuilding { constructor() { super("transistor"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 38, @@ -31,37 +31,37 @@ export class MetaTransistorBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#bc3a61"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_logic_gates); } /** {} **/ getLayer(): "wires" { return "wires"; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getAvailableVariants(): any { + getAvailableVariants() { return [defaultBuildingVariant, enumTransistorVariants.mirrored]; } - getSpecialOverlayRenderMatrix(rotation: any, rotationVariant: any, variant: any): any { + getSpecialOverlayRenderMatrix(rotation, rotationVariant, variant) { return overlayMatrices[variant][rotation]; } - getRenderPins(): any { + getRenderPins() { // We already have it included return false; } - updateVariants(entity: Entity, rotationVariant: number, variant: any): any { + updateVariants(entity: Entity, rotationVariant: number, variant) { entity.components.WiredPins.slots[1].direction = variant === enumTransistorVariants.mirrored ? enumDirection.right : enumDirection.left; } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [ { diff --git a/src/ts/game/buildings/trash.ts b/src/ts/game/buildings/trash.ts index 7ada1429..c37712c3 100644 --- a/src/ts/game/buildings/trash.ts +++ b/src/ts/game/buildings/trash.ts @@ -7,13 +7,13 @@ import { Entity } from "../entity"; import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; -const overlayMatrix: any = generateMatrixRotations([1, 1, 0, 1, 1, 1, 0, 1, 1]); +const overlayMatrix = generateMatrixRotations([1, 1, 0, 1, 1, 1, 0, 1, 1]); export class MetaTrashBuilding extends MetaBuilding { constructor() { super("trash"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 20, @@ -21,29 +21,29 @@ export class MetaTrashBuilding extends MetaBuilding { }, ]; } - getIsRotateable(): any { + getIsRotateable() { return false; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#ed1d5d"; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getSpecialOverlayRenderMatrix(rotation: any): any { + getSpecialOverlayRenderMatrix(rotation) { return overlayMatrix[rotation]; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_cutter_and_trash); } - addAchievementReceiver(entity: any): any { + addAchievementReceiver(entity) { if (!entity.root) { return; } - const itemProcessor: any = entity.components.ItemProcessor; - const tryTakeItem: any = itemProcessor.tryTakeItem.bind(itemProcessor); - itemProcessor.tryTakeItem = (): any => { - const taken: any = tryTakeItem(...arguments); + const itemProcessor = entity.components.ItemProcessor; + const tryTakeItem = itemProcessor.tryTakeItem.bind(itemProcessor); + itemProcessor.tryTakeItem = () => { + const taken = tryTakeItem(...arguments); if (taken) { entity.root.signals.achievementCheck.dispatch(ACHIEVEMENTS.trash1000, 1); } @@ -53,7 +53,7 @@ export class MetaTrashBuilding extends MetaBuilding { /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new ItemAcceptorComponent({ slots: [ { diff --git a/src/ts/game/buildings/underground_belt.ts b/src/ts/game/buildings/underground_belt.ts index ebc633bf..07d12e9b 100644 --- a/src/ts/game/buildings/underground_belt.ts +++ b/src/ts/game/buildings/underground_belt.ts @@ -11,18 +11,18 @@ import { enumHubGoalRewards } from "../tutorial_goals"; import { formatItemsPerSecond, generateMatrixRotations } from "../../core/utils"; import { T } from "../../translations"; /** @enum {string} */ -export const arrayUndergroundRotationVariantToMode: any = [ +export const arrayUndergroundRotationVariantToMode = [ enumUndergroundBeltMode.sender, enumUndergroundBeltMode.receiver, ]; /** @enum {string} */ -export const enumUndergroundBeltVariants: any = { tier2: "tier2" }; -export const enumUndergroundBeltVariantToTier: any = { +export const enumUndergroundBeltVariants = { tier2: "tier2" }; +export const enumUndergroundBeltVariantToTier = { [defaultBuildingVariant]: 0, [enumUndergroundBeltVariants.tier2]: 1, }; -const colorsByRotationVariant: any = ["#6d9dff", "#71ff9c"]; -const overlayMatrices: any = [ +const colorsByRotationVariant = ["#6d9dff", "#71ff9c"]; +const overlayMatrices = [ // Sender generateMatrixRotations([1, 1, 1, 0, 1, 0, 0, 1, 0]), // Receiver @@ -33,7 +33,7 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { constructor() { super("underground_belt"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 22, @@ -57,16 +57,16 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(variant: any, rotationVariant: any): any { + getSilhouetteColor(variant, rotationVariant) { return colorsByRotationVariant[rotationVariant]; } - getFlipOrientationAfterPlacement(): any { + getFlipOrientationAfterPlacement() { return true; } - getStayInPlacementMode(): any { + getStayInPlacementMode() { return true; } - getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity): any { + getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity) { return overlayMatrices[rotationVariant][rotation]; } /** @@ -76,8 +76,8 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { string, string ]> { - const rangeTiles: any = globalConfig.undergroundBeltMaxTilesByTier[enumUndergroundBeltVariantToTier[variant]]; - const beltSpeed: any = root.hubGoals.getUndergroundBeltBaseSpeed(); + const rangeTiles = globalConfig.undergroundBeltMaxTilesByTier[enumUndergroundBeltVariantToTier[variant]]; + const beltSpeed = root.hubGoals.getUndergroundBeltBaseSpeed(); const stats: Array<[ string, string @@ -93,14 +93,14 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { stats.push([T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(beltSpeed)]); return stats; } - getAvailableVariants(root: GameRoot): any { + getAvailableVariants(root: GameRoot) { if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_underground_belt_tier_2)) { return [defaultBuildingVariant, enumUndergroundBeltVariants.tier2]; } return super.getAvailableVariants(root); } - getPreviewSprite(rotationVariant: number, variant: string): any { - let suffix: any = ""; + getPreviewSprite(rotationVariant: number, variant: string) { + let suffix = ""; if (variant !== defaultBuildingVariant) { suffix = "-" + variant; } @@ -113,8 +113,8 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { assertAlways(false, "Invalid rotation variant"); } } - getBlueprintSprite(rotationVariant: number, variant: string): any { - let suffix: any = ""; + getBlueprintSprite(rotationVariant: number, variant: string) { + let suffix = ""; if (variant !== defaultBuildingVariant) { suffix = "-" + variant; } @@ -127,16 +127,16 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { assertAlways(false, "Invalid rotation variant"); } } - getSprite(rotationVariant: number, variant: string): any { + getSprite(rotationVariant: number, variant: string) { return this.getPreviewSprite(rotationVariant, variant); } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_tunnel); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { // Required, since the item processor needs this. entity.addComponent(new ItemEjectorComponent({ slots: [], @@ -161,18 +161,18 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { rotationVariant: number; connectedEntities?: Array; } { - const searchDirection: any = enumAngleToDirection[rotation]; - const searchVector: any = enumDirectionToVector[searchDirection]; - const tier: any = enumUndergroundBeltVariantToTier[variant]; - const targetRotation: any = (rotation + 180) % 360; - const targetSenderRotation: any = rotation; - for (let searchOffset: any = 1; searchOffset <= globalConfig.undergroundBeltMaxTilesByTier[tier]; ++searchOffset) { + const searchDirection = enumAngleToDirection[rotation]; + const searchVector = enumDirectionToVector[searchDirection]; + const tier = enumUndergroundBeltVariantToTier[variant]; + const targetRotation = (rotation + 180) % 360; + const targetSenderRotation = rotation; + for (let searchOffset = 1; searchOffset <= globalConfig.undergroundBeltMaxTilesByTier[tier]; ++searchOffset) { tile = tile.addScalars(searchVector.x, searchVector.y); - const contents: any = root.map.getTileContent(tile, "regular"); + const contents = root.map.getTileContent(tile, "regular"); if (contents) { - const undergroundComp: any = contents.components.UndergroundBelt; + const undergroundComp = contents.components.UndergroundBelt; if (undergroundComp && undergroundComp.tier === tier) { - const staticComp: any = contents.components.StaticMapEntity; + const staticComp = contents.components.StaticMapEntity; if (staticComp.rotation === targetRotation) { if (undergroundComp.mode !== enumUndergroundBeltMode.sender) { // If we encounter an underground receiver on our way which is also faced in our direction, we don't accept that @@ -205,7 +205,7 @@ export class MetaUndergroundBeltBuilding extends MetaBuilding { rotationVariant: 0, }; } - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { + updateVariants(entity: Entity, rotationVariant: number, variant: string) { entity.components.UndergroundBelt.tier = enumUndergroundBeltVariantToTier[variant]; switch (arrayUndergroundRotationVariantToMode[rotationVariant]) { case enumUndergroundBeltMode.sender: { diff --git a/src/ts/game/buildings/virtual_processor.ts b/src/ts/game/buildings/virtual_processor.ts index dfacebfb..be6e2092 100644 --- a/src/ts/game/buildings/virtual_processor.ts +++ b/src/ts/game/buildings/virtual_processor.ts @@ -10,21 +10,21 @@ import { MetaPainterBuilding } from "./painter"; import { MetaRotaterBuilding } from "./rotater"; import { MetaStackerBuilding } from "./stacker"; /** @enum {string} */ -export const enumVirtualProcessorVariants: any = { +export const enumVirtualProcessorVariants = { rotater: "rotater", unstacker: "unstacker", stacker: "stacker", painter: "painter", }; /** @enum {string} */ -const enumVariantToGate: any = { +const enumVariantToGate = { [defaultBuildingVariant]: enumLogicGateType.cutter, [enumVirtualProcessorVariants.rotater]: enumLogicGateType.rotater, [enumVirtualProcessorVariants.unstacker]: enumLogicGateType.unstacker, [enumVirtualProcessorVariants.stacker]: enumLogicGateType.stacker, [enumVirtualProcessorVariants.painter]: enumLogicGateType.painter, }; -const colors: any = { +const colors = { [defaultBuildingVariant]: new MetaCutterBuilding().getSilhouetteColor(), [enumVirtualProcessorVariants.rotater]: new MetaRotaterBuilding().getSilhouetteColor(), [enumVirtualProcessorVariants.unstacker]: new MetaStackerBuilding().getSilhouetteColor(), @@ -36,7 +36,7 @@ export class MetaVirtualProcessorBuilding extends MetaBuilding { constructor() { super("virtual_processor"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 42, @@ -60,20 +60,20 @@ export class MetaVirtualProcessorBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(variant: any): any { + getSilhouetteColor(variant) { return colors[variant]; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_virtual_processing); } /** {} **/ getLayer(): "wires" { return "wires"; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getAvailableVariants(): any { + getAvailableVariants() { return [ defaultBuildingVariant, enumVirtualProcessorVariants.rotater, @@ -82,14 +82,14 @@ export class MetaVirtualProcessorBuilding extends MetaBuilding { enumVirtualProcessorVariants.unstacker, ]; } - getRenderPins(): any { + getRenderPins() { // We already have it included return false; } - updateVariants(entity: Entity, rotationVariant: number, variant: any): any { - const gateType: any = enumVariantToGate[variant]; + updateVariants(entity: Entity, rotationVariant: number, variant) { + const gateType = enumVariantToGate[variant]; entity.components.LogicGate.type = gateType; - const pinComp: any = entity.components.WiredPins; + const pinComp = entity.components.WiredPins; switch (gateType) { case enumLogicGateType.cutter: case enumLogicGateType.unstacker: { @@ -155,7 +155,7 @@ export class MetaVirtualProcessorBuilding extends MetaBuilding { /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WiredPinsComponent({ slots: [], })); diff --git a/src/ts/game/buildings/wire.ts b/src/ts/game/buildings/wire.ts index 68285856..399e870b 100644 --- a/src/ts/game/buildings/wire.ts +++ b/src/ts/game/buildings/wire.ts @@ -7,23 +7,23 @@ import { Entity } from "../entity"; import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; -export const arrayWireRotationVariantToType: any = [ +export const arrayWireRotationVariantToType = [ enumWireType.forward, enumWireType.turn, enumWireType.split, enumWireType.cross, ]; -export const wireOverlayMatrices: any = { +export const wireOverlayMatrices = { [enumWireType.forward]: generateMatrixRotations([0, 1, 0, 0, 1, 0, 0, 1, 0]), [enumWireType.split]: generateMatrixRotations([0, 0, 0, 1, 1, 1, 0, 1, 0]), [enumWireType.turn]: generateMatrixRotations([0, 0, 0, 0, 1, 1, 0, 1, 0]), [enumWireType.cross]: generateMatrixRotations([0, 1, 0, 1, 1, 1, 0, 1, 0]), }; /** @enum {string} */ -export const wireVariants: any = { +export const wireVariants = { second: "second", }; -const enumWireVariantToVariant: any = { +const enumWireVariantToVariant = { [defaultBuildingVariant]: enumWireVariant.first, [wireVariants.second]: enumWireVariant.second, }; @@ -32,7 +32,7 @@ export class MetaWireBuilding extends MetaBuilding { constructor() { super("wire"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 27, @@ -76,51 +76,51 @@ export class MetaWireBuilding extends MetaBuilding { }, ]; } - getHasDirectionLockAvailable(): any { + getHasDirectionLockAvailable() { return true; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#61ef6f"; } - getAvailableVariants(): any { + getAvailableVariants() { return [defaultBuildingVariant, wireVariants.second]; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } - getStayInPlacementMode(): any { + getStayInPlacementMode() { return true; } - getPlacementSound(): any { + getPlacementSound() { return SOUNDS.placeBelt; } - getRotateAutomaticallyWhilePlacing(): any { + getRotateAutomaticallyWhilePlacing() { return true; } /** {} **/ getLayer(): "wires" { return "wires"; } - getSprite(): any { + getSprite() { return null; } - getIsReplaceable(): any { + getIsReplaceable() { return true; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_wires_painter_and_levers); } /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WireComponent({})); } - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { + updateVariants(entity: Entity, rotationVariant: number, variant: string) { entity.components.Wire.type = arrayWireRotationVariantToType[rotationVariant]; entity.components.Wire.variant = enumWireVariantToVariant[variant]; } - getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity): any { + getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity) { return wireOverlayMatrices[entity.components.Wire.type][rotation]; } /** @@ -128,7 +128,7 @@ export class MetaWireBuilding extends MetaBuilding { * {} */ getPreviewSprite(rotationVariant: number, variant: string): import("../../core/draw_utils").AtlasSprite { - const wireVariant: any = enumWireVariantToVariant[variant]; + const wireVariant = enumWireVariantToVariant[variant]; switch (arrayWireRotationVariantToType[rotationVariant]) { case enumWireType.forward: { return Loader.getSprite("sprites/wires/sets/" + wireVariant + "_forward.png"); @@ -147,7 +147,7 @@ export class MetaWireBuilding extends MetaBuilding { } } } - getBlueprintSprite(rotationVariant: any, variant: any): any { + getBlueprintSprite(rotationVariant, variant) { return this.getPreviewSprite(rotationVariant, variant); } /** @@ -165,19 +165,19 @@ export class MetaWireBuilding extends MetaBuilding { rotationVariant: number; connectedEntities?: Array; } { - const wireVariant: any = enumWireVariantToVariant[variant]; - const connections: any = { + const wireVariant = enumWireVariantToVariant[variant]; + const connections = { top: root.logic.computeWireEdgeStatus({ tile, wireVariant, edge: enumDirection.top }), right: root.logic.computeWireEdgeStatus({ tile, wireVariant, edge: enumDirection.right }), bottom: root.logic.computeWireEdgeStatus({ tile, wireVariant, edge: enumDirection.bottom }), left: root.logic.computeWireEdgeStatus({ tile, wireVariant, edge: enumDirection.left }), }; - let flag: any = 0; + let flag = 0; flag |= connections.top ? 0x1000 : 0; flag |= connections.right ? 0x100 : 0; flag |= connections.bottom ? 0x10 : 0; flag |= connections.left ? 0x1 : 0; - let targetType: any = enumWireType.forward; + let targetType = enumWireType.forward; // First, reset rotation rotation = 0; switch (flag) { diff --git a/src/ts/game/buildings/wire_tunnel.ts b/src/ts/game/buildings/wire_tunnel.ts index 214de3bf..07e90953 100644 --- a/src/ts/game/buildings/wire_tunnel.ts +++ b/src/ts/game/buildings/wire_tunnel.ts @@ -5,13 +5,13 @@ import { Entity } from "../entity"; import { defaultBuildingVariant, MetaBuilding } from "../meta_building"; import { GameRoot } from "../root"; import { enumHubGoalRewards } from "../tutorial_goals"; -const wireTunnelOverlayMatrix: any = generateMatrixRotations([0, 1, 0, 1, 1, 1, 0, 1, 0]); +const wireTunnelOverlayMatrix = generateMatrixRotations([0, 1, 0, 1, 1, 1, 0, 1, 0]); export class MetaWireTunnelBuilding extends MetaBuilding { constructor() { super("wire_tunnel"); } - static getAllVariantCombinations(): any { + static getAllVariantCombinations() { return [ { internalId: 39, @@ -19,19 +19,19 @@ export class MetaWireTunnelBuilding extends MetaBuilding { }, ]; } - getSilhouetteColor(): any { + getSilhouetteColor() { return "#777a86"; } - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_wires_painter_and_levers); } - getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity): any { + getSpecialOverlayRenderMatrix(rotation: number, rotationVariant: number, variant: string, entity: Entity) { return wireTunnelOverlayMatrix[rotation]; } - getIsRotateable(): any { + getIsRotateable() { return false; } - getDimensions(): any { + getDimensions() { return new Vector(1, 1); } /** {} **/ @@ -41,7 +41,7 @@ export class MetaWireTunnelBuilding extends MetaBuilding { /** * Creates the entity at the given location */ - setupEntityComponents(entity: Entity): any { + setupEntityComponents(entity: Entity) { entity.addComponent(new WireTunnelComponent()); } } diff --git a/src/ts/game/camera.ts b/src/ts/game/camera.ts index 409f015e..c3e67ab0 100644 --- a/src/ts/game/camera.ts +++ b/src/ts/game/camera.ts @@ -8,19 +8,19 @@ import { mixVector, Vector } from "../core/vector"; import { BasicSerializableObject, types } from "../savegame/serialization"; import { KEYMAPPINGS } from "./key_action_mapper"; import { GameRoot } from "./root"; -const logger: any = createLogger("camera"); -export const USER_INTERACT_MOVE: any = "move"; -export const USER_INTERACT_ZOOM: any = "zoom"; -export const USER_INTERACT_TOUCHEND: any = "touchend"; -const velocitySmoothing: any = 0.5; -const velocityFade: any = 0.98; -const velocityStrength: any = 0.4; -const velocityMax: any = 20; -const ticksBeforeErasingVelocity: any = 10; +const logger = createLogger("camera"); +export const USER_INTERACT_MOVE = "move"; +export const USER_INTERACT_ZOOM = "zoom"; +export const USER_INTERACT_TOUCHEND = "touchend"; +const velocitySmoothing = 0.5; +const velocityFade = 0.98; +const velocityStrength = 0.4; +const velocityMax = 20; +const ticksBeforeErasingVelocity = 10; /** * @enum {string} */ -export const enumMouseButton: any = { +export const enumMouseButton = { left: "left", middle: "middle", right: "right", @@ -63,7 +63,7 @@ export class Camera extends BasicSerializableObject { this.clampZoomLevel(); this.bindKeys(); if (G_IS_DEV) { - window.addEventListener("keydown", (ev: any): any => { + window.addEventListener("keydown", ev => { if (ev.key === "i") { this.zoomLevel = 3; } @@ -71,17 +71,17 @@ export class Camera extends BasicSerializableObject { } } // Serialization - static getId(): any { + static getId() { return "Camera"; } - static getSchema(): any { + static getSchema() { return { zoomLevel: types.float, center: types.vector, }; } - deserialize(data: any): any { - const errorCode: any = super.deserialize(data); + deserialize(data) { + const errorCode = super.deserialize(data); if (errorCode) { return errorCode; } @@ -89,55 +89,55 @@ export class Camera extends BasicSerializableObject { this.clampZoomLevel(); } // Simple getters & setters - addScreenShake(amount: any): any { - const currentShakeAmount: any = this.currentShake.length(); - const scale: any = 1 / (1 + 3 * currentShakeAmount); + addScreenShake(amount) { + const currentShakeAmount = this.currentShake.length(); + const scale = 1 / (1 + 3 * currentShakeAmount); this.currentShake.x = this.currentShake.x + 2 * (Math.random() - 0.5) * scale * amount; this.currentShake.y = this.currentShake.y + 2 * (Math.random() - 0.5) * scale * amount; } /** * Sets a point in world space to focus on */ - setDesiredCenter(center: Vector): any { + setDesiredCenter(center: Vector) { this.desiredCenter = center.copy(); this.currentlyMoving = false; } /** * Sets a desired zoom level */ - setDesiredZoom(zoom: number): any { + setDesiredZoom(zoom: number) { this.desiredZoom = zoom; } /** * Returns if this camera is currently moving by a non-user interaction */ - isCurrentlyMovingToDesiredCenter(): any { + isCurrentlyMovingToDesiredCenter() { return this.desiredCenter !== null; } /** * Sets the camera pan, every frame the camera will move by this amount */ - setPan(pan: Vector): any { + setPan(pan: Vector) { this.desiredPan = pan.copy(); } /** * Finds a good initial zoom level */ - findInitialZoom(): any { - let desiredWorldSpaceWidth: any = 18 * globalConfig.tileSize; + findInitialZoom() { + let desiredWorldSpaceWidth = 18 * globalConfig.tileSize; if (window.innerWidth < 1000) { desiredWorldSpaceWidth = 12 * globalConfig.tileSize; } - const zoomLevelX: any = this.root.gameWidth / desiredWorldSpaceWidth; - const zoomLevelY: any = this.root.gameHeight / desiredWorldSpaceWidth; - const finalLevel: any = Math.min(zoomLevelX, zoomLevelY); + const zoomLevelX = this.root.gameWidth / desiredWorldSpaceWidth; + const zoomLevelY = this.root.gameHeight / desiredWorldSpaceWidth; + const finalLevel = Math.min(zoomLevelX, zoomLevelY); assert(Number.isFinite(finalLevel) && finalLevel > 0, "Invalid zoom level computed for initial zoom: " + finalLevel); return finalLevel; } /** * Clears all animations */ - clearAnimations(): any { + clearAnimations() { this.touchPostMoveVelocity.x = 0; this.touchPostMoveVelocity.y = 0; this.desiredCenter = null; @@ -178,7 +178,7 @@ export class Camera extends BasicSerializableObject { /** * Cancels all interactions, that is user interaction and non user interaction */ - cancelAllInteractions(): any { + cancelAllInteractions() { this.touchPostMoveVelocity = new Vector(0, 0); this.desiredCenter = null; this.currentlyMoving = false; @@ -188,37 +188,37 @@ export class Camera extends BasicSerializableObject { /** * Returns effective viewport width */ - getViewportWidth(): any { + getViewportWidth() { return this.root.gameWidth / this.zoomLevel; } /** * Returns effective viewport height */ - getViewportHeight(): any { + getViewportHeight() { return this.root.gameHeight / this.zoomLevel; } /** * Returns effective world space viewport left */ - getViewportLeft(): any { + getViewportLeft() { return this.center.x - this.getViewportWidth() / 2 + (this.currentShake.x * 10) / this.zoomLevel; } /** * Returns effective world space viewport right */ - getViewportRight(): any { + getViewportRight() { return this.center.x + this.getViewportWidth() / 2 + (this.currentShake.x * 10) / this.zoomLevel; } /** * Returns effective world space viewport top */ - getViewportTop(): any { + getViewportTop() { return this.center.y - this.getViewportHeight() / 2 + (this.currentShake.x * 10) / this.zoomLevel; } /** * Returns effective world space viewport bottom */ - getViewportBottom(): any { + getViewportBottom() { return this.center.y + this.getViewportHeight() / 2 + (this.currentShake.x * 10) / this.zoomLevel; } /** @@ -228,13 +228,13 @@ export class Camera extends BasicSerializableObject { getVisibleRect(): Rectangle { return Rectangle.fromTRBL(Math.floor(this.getViewportTop()), Math.ceil(this.getViewportRight()), Math.ceil(this.getViewportBottom()), Math.floor(this.getViewportLeft())); } - getIsMapOverlayActive(): any { + getIsMapOverlayActive() { return this.zoomLevel < globalConfig.mapChunkOverviewMinZoom; } /** * Attaches all event listeners */ - internalInitEvents(): any { + internalInitEvents() { this.eventListenerTouchStart = this.onTouchStart.bind(this); this.eventListenerTouchEnd = this.onTouchEnd.bind(this); this.eventListenerTouchMove = this.onTouchMove.bind(this); @@ -257,7 +257,7 @@ export class Camera extends BasicSerializableObject { /** * Cleans up all event listeners */ - cleanup(): any { + cleanup() { if (SUPPORT_TOUCH) { this.root.canvas.removeEventListener("touchstart", this.eventListenerTouchStart); this.root.canvas.removeEventListener("touchend", this.eventListenerTouchEnd); @@ -273,21 +273,21 @@ export class Camera extends BasicSerializableObject { /** * Binds the arrow keys */ - bindKeys(): any { - const mapper: any = this.root.keyMapper; - mapper.getBinding(KEYMAPPINGS.navigation.mapMoveUp).add((): any => (this.keyboardForce.y = -1)); - mapper.getBinding(KEYMAPPINGS.navigation.mapMoveDown).add((): any => (this.keyboardForce.y = 1)); - mapper.getBinding(KEYMAPPINGS.navigation.mapMoveRight).add((): any => (this.keyboardForce.x = 1)); - mapper.getBinding(KEYMAPPINGS.navigation.mapMoveLeft).add((): any => (this.keyboardForce.x = -1)); + bindKeys() { + const mapper = this.root.keyMapper; + mapper.getBinding(KEYMAPPINGS.navigation.mapMoveUp).add(() => (this.keyboardForce.y = -1)); + mapper.getBinding(KEYMAPPINGS.navigation.mapMoveDown).add(() => (this.keyboardForce.y = 1)); + mapper.getBinding(KEYMAPPINGS.navigation.mapMoveRight).add(() => (this.keyboardForce.x = 1)); + mapper.getBinding(KEYMAPPINGS.navigation.mapMoveLeft).add(() => (this.keyboardForce.x = -1)); mapper .getBinding(KEYMAPPINGS.navigation.mapZoomIn) - .add((): any => (this.desiredZoom = this.zoomLevel * 1.2)); + .add(() => (this.desiredZoom = this.zoomLevel * 1.2)); mapper .getBinding(KEYMAPPINGS.navigation.mapZoomOut) - .add((): any => (this.desiredZoom = this.zoomLevel / 1.2)); - mapper.getBinding(KEYMAPPINGS.navigation.centerMap).add((): any => this.centerOnMap()); + .add(() => (this.desiredZoom = this.zoomLevel / 1.2)); + mapper.getBinding(KEYMAPPINGS.navigation.centerMap).add(() => this.centerOnMap()); } - centerOnMap(): any { + centerOnMap() { this.desiredCenter = new Vector(0, 0); } /** @@ -295,7 +295,7 @@ export class Camera extends BasicSerializableObject { * {} world space */ screenToWorld(screen: Vector): Vector { - const centerSpace: any = screen.subScalars(this.root.gameWidth / 2, this.root.gameHeight / 2); + const centerSpace = screen.subScalars(this.root.gameWidth / 2, this.root.gameHeight / 2); return centerSpace.divideScalar(this.zoomLevel).add(this.center); } /** @@ -303,7 +303,7 @@ export class Camera extends BasicSerializableObject { * {} screen space */ worldToScreen(world: Vector): Vector { - const screenSpace: any = world.sub(this.center).multiplyScalar(this.zoomLevel); + const screenSpace = world.sub(this.center).multiplyScalar(this.zoomLevel); return screenSpace.addScalars(this.root.gameWidth / 2, this.root.gameHeight / 2); } /** @@ -311,13 +311,13 @@ export class Camera extends BasicSerializableObject { * {} true if its on screen */ isWorldPointOnScreen(point: Vector): boolean { - const rect: any = this.getVisibleRect(); + const rect = this.getVisibleRect(); return rect.containsPoint(point.x, point.y); } - getMaximumZoom(): any { + getMaximumZoom() { return this.root.gameMode.getMaximumZoom(); } - getMinimumZoom(): any { + getMinimumZoom() { return this.root.gameMode.getMinimumZoom(); } /** @@ -339,7 +339,7 @@ export class Camera extends BasicSerializableObject { * Checks if the mouse event is too close after a touch event and thus * should get ignored */ - checkPreventDoubleMouse(): any { + checkPreventDoubleMouse() { if (performance.now() - clickDetectorGlobals.lastTouchTime < 1000.0) { return false; } @@ -348,7 +348,7 @@ export class Camera extends BasicSerializableObject { /** * Mousedown handler */ - onMouseDown(event: MouseEvent): any { + onMouseDown(event: MouseEvent) { if (event.cancelable) { event.preventDefault(); // event.stopPropagation(); @@ -371,7 +371,7 @@ export class Camera extends BasicSerializableObject { /** * Mousemove handler */ - onMouseMove(event: MouseEvent): any { + onMouseMove(event: MouseEvent) { if (event.cancelable) { event.preventDefault(); // event.stopPropagation(); @@ -390,7 +390,7 @@ export class Camera extends BasicSerializableObject { /** * Mouseup handler */ - onMouseUp(event: MouseEvent=): any { + onMouseUp(event: MouseEvent=) { if (event) { if (event.cancelable) { event.preventDefault(); @@ -406,27 +406,27 @@ export class Camera extends BasicSerializableObject { /** * Mousewheel event */ - onMouseWheel(event: WheelEvent): any { + onMouseWheel(event: WheelEvent) { if (event.cancelable) { event.preventDefault(); // event.stopPropagation(); } - const prevZoom: any = this.zoomLevel; - const scale: any = 1 + 0.15 * this.root.app.settings.getScrollWheelSensitivity(); + const prevZoom = this.zoomLevel; + const scale = 1 + 0.15 * this.root.app.settings.getScrollWheelSensitivity(); assert(Number.isFinite(scale), "Got invalid scale in mouse wheel event: " + event.deltaY); assert(Number.isFinite(this.zoomLevel), "Got invalid zoom level *before* wheel: " + this.zoomLevel); this.zoomLevel *= event.deltaY < 0 ? scale : 1 / scale; assert(Number.isFinite(this.zoomLevel), "Got invalid zoom level *after* wheel: " + this.zoomLevel); this.clampZoomLevel(); this.desiredZoom = null; - let mousePosition: any = this.root.app.mousePosition; + let mousePosition = this.root.app.mousePosition; if (!this.root.app.settings.getAllSettings().zoomToCursor) { mousePosition = new Vector(this.root.gameWidth / 2, this.root.gameHeight / 2); } if (mousePosition) { - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const worldDelta: any = worldPos.sub(this.center); - const actualDelta: any = this.zoomLevel / prevZoom - 1; + const worldPos = this.root.camera.screenToWorld(mousePosition); + const worldDelta = worldPos.sub(this.center); + const actualDelta = this.zoomLevel / prevZoom - 1; this.center = this.center.add(worldDelta.multiplyScalar(actualDelta)); this.desiredCenter = null; } @@ -435,7 +435,7 @@ export class Camera extends BasicSerializableObject { /** * Touch start handler */ - onTouchStart(event: TouchEvent): any { + onTouchStart(event: TouchEvent) { if (event.cancelable) { event.preventDefault(); // event.stopPropagation(); @@ -443,7 +443,7 @@ export class Camera extends BasicSerializableObject { clickDetectorGlobals.lastTouchTime = performance.now(); this.touchPostMoveVelocity = new Vector(0, 0); if (event.touches.length === 1) { - const touch: any = event.touches[0]; + const touch = event.touches[0]; this.combinedSingleTouchStartHandler(touch.clientX, touch.clientY); } else if (event.touches.length === 2) { @@ -451,8 +451,8 @@ export class Camera extends BasicSerializableObject { // // Something prevented pinching // return false; // } - const touch1: any = event.touches[0]; - const touch2: any = event.touches[1]; + const touch1 = event.touches[0]; + const touch2 = event.touches[1]; this.currentlyMoving = false; this.currentlyPinching = true; this.lastPinchPositions = [ @@ -465,35 +465,35 @@ export class Camera extends BasicSerializableObject { /** * Touch move handler */ - onTouchMove(event: TouchEvent): any { + onTouchMove(event: TouchEvent) { if (event.cancelable) { event.preventDefault(); // event.stopPropagation(); } clickDetectorGlobals.lastTouchTime = performance.now(); if (event.touches.length === 1) { - const touch: any = event.touches[0]; + const touch = event.touches[0]; this.combinedSingleTouchMoveHandler(touch.clientX, touch.clientY); } else if (event.touches.length === 2) { if (this.currentlyPinching) { - const touch1: any = event.touches[0]; - const touch2: any = event.touches[1]; - const newPinchPositions: any = [ + const touch1 = event.touches[0]; + const touch2 = event.touches[1]; + const newPinchPositions = [ new Vector(touch1.clientX, touch1.clientY), new Vector(touch2.clientX, touch2.clientY), ]; // Get distance of taps last time and now - const lastDistance: any = this.lastPinchPositions[0].distance(this.lastPinchPositions[1]); - const thisDistance: any = newPinchPositions[0].distance(newPinchPositions[1]); + const lastDistance = this.lastPinchPositions[0].distance(this.lastPinchPositions[1]); + const thisDistance = newPinchPositions[0].distance(newPinchPositions[1]); // IMPORTANT to do math max here to avoid NaN and causing an invalid zoom level - const difference: any = thisDistance / Math.max(0.001, lastDistance); + const difference = thisDistance / Math.max(0.001, lastDistance); // Find old center of zoom - let oldCenter: any = this.lastPinchPositions[0].centerPoint(this.lastPinchPositions[1]); + let oldCenter = this.lastPinchPositions[0].centerPoint(this.lastPinchPositions[1]); // Find new center of zoom - let center: any = newPinchPositions[0].centerPoint(newPinchPositions[1]); + let center = newPinchPositions[0].centerPoint(newPinchPositions[1]); // Compute movement - let movement: any = oldCenter.sub(center); + let movement = oldCenter.sub(center); this.center.x += movement.x / this.zoomLevel; this.center.y += movement.y / this.zoomLevel; // Compute zoom @@ -508,7 +508,7 @@ export class Camera extends BasicSerializableObject { ")"); this.zoomLevel *= difference; // Stick to pivot point - const correcture: any = center.multiplyScalar(difference - 1).divideScalar(this.zoomLevel); + const correcture = center.multiplyScalar(difference - 1).divideScalar(this.zoomLevel); this.center = this.center.add(correcture); this.lastPinchPositions = newPinchPositions; this.userInteraction.dispatch(USER_INTERACT_MOVE); @@ -525,7 +525,7 @@ export class Camera extends BasicSerializableObject { /** * Touch end and cancel handler */ - onTouchEnd(event: TouchEvent=): any { + onTouchEnd(event: TouchEvent=) { if (event) { if (event.cancelable) { event.preventDefault(); @@ -536,15 +536,15 @@ export class Camera extends BasicSerializableObject { if (event.changedTouches.length === 0) { logger.warn("Touch end without changed touches"); } - const touch: any = event.changedTouches[0]; + const touch = event.changedTouches[0]; this.combinedSingleTouchStopHandler(touch.clientX, touch.clientY); return false; } /** * Internal touch start handler */ - combinedSingleTouchStartHandler(x: number, y: number): any { - const pos: any = new Vector(x, y); + combinedSingleTouchStartHandler(x: number, y: number) { + const pos = new Vector(x, y); if (this.downPreHandler.dispatch(pos, enumMouseButton.left) === STOP_PROPAGATION) { // Somebody else captured it return; @@ -559,8 +559,8 @@ export class Camera extends BasicSerializableObject { /** * Internal touch move handler */ - combinedSingleTouchMoveHandler(x: number, y: number): any { - const pos: any = new Vector(x, y); + combinedSingleTouchMoveHandler(x: number, y: number) { + const pos = new Vector(x, y); if (this.movePreHandler.dispatch(pos) === STOP_PROPAGATION) { // Somebody else captured it return; @@ -568,7 +568,7 @@ export class Camera extends BasicSerializableObject { if (!this.currentlyMoving) { return false; } - let delta: any = this.lastMovingPosition.sub(pos).divideScalar(this.zoomLevel); + let delta = this.lastMovingPosition.sub(pos).divideScalar(this.zoomLevel); if (G_IS_DEV && globalConfig.debug.testCulling) { // When testing culling, we see everything from the same distance delta = delta.multiplyScalar(this.zoomLevel * -2); @@ -588,7 +588,7 @@ export class Camera extends BasicSerializableObject { /** * Internal touch stop handler */ - combinedSingleTouchStopHandler(x: any, y: any): any { + combinedSingleTouchStopHandler(x, y) { if (this.currentlyMoving || this.currentlyPinching) { this.currentlyMoving = false; this.currentlyPinching = false; @@ -604,7 +604,7 @@ export class Camera extends BasicSerializableObject { /** * Clamps the camera zoom level within the allowed range */ - clampZoomLevel(): any { + clampZoomLevel() { if (G_IS_DEV && globalConfig.debug.disableZoomLimits) { return; } @@ -618,25 +618,25 @@ export class Camera extends BasicSerializableObject { /** * Clamps the center within set boundaries */ - clampToBounds(): any { - const bounds: any = this.root.gameMode.getCameraBounds(); + clampToBounds() { + const bounds = this.root.gameMode.getCameraBounds(); if (!bounds) { return; } - const tileScaleBounds: any = this.root.gameMode.getCameraBounds().allScaled(globalConfig.tileSize); + const tileScaleBounds = this.root.gameMode.getCameraBounds().allScaled(globalConfig.tileSize); this.center.x = clamp(this.center.x, tileScaleBounds.x, tileScaleBounds.x + tileScaleBounds.w); this.center.y = clamp(this.center.y, tileScaleBounds.y, tileScaleBounds.y + tileScaleBounds.h); } /** * Updates the camera */ - update(dt: number): any { + update(dt: number) { dt = Math.min(dt, 33); this.cameraUpdateTimeBucket += dt; // Simulate movement of N FPS - const updatesPerFrame: any = 4; - const physicsStepSizeMs: any = 1000.0 / (60.0 * updatesPerFrame); - let now: any = this.root.time.systemNow() - 3 * physicsStepSizeMs; + const updatesPerFrame = 4; + const physicsStepSizeMs = 1000.0 / (60.0 * updatesPerFrame); + let now = this.root.time.systemNow() - 3 * physicsStepSizeMs; while (this.cameraUpdateTimeBucket > physicsStepSizeMs) { now += physicsStepSizeMs; this.cameraUpdateTimeBucket -= physicsStepSizeMs; @@ -652,13 +652,13 @@ export class Camera extends BasicSerializableObject { /** * Prepares a context to transform it */ - transform(context: CanvasRenderingContext2D): any { + transform(context: CanvasRenderingContext2D) { if (G_IS_DEV && globalConfig.debug.testCulling) { context.transform(1, 0, 0, 1, 100, 100); return; } this.clampZoomLevel(); - const zoom: any = this.zoomLevel; + const zoom = this.zoomLevel; context.transform( // Scale, skew, rotate zoom, 0, 0, zoom, @@ -668,14 +668,14 @@ export class Camera extends BasicSerializableObject { /** * Internal shake handler */ - internalUpdateShake(now: number, dt: number): any { + internalUpdateShake(now: number, dt: number) { this.currentShake = this.currentShake.multiplyScalar(0.92); } /** * Internal pan handler */ - internalUpdatePanning(now: number, dt: number): any { - const baseStrength: any = velocityStrength * this.root.app.platformWrapper.getTouchPanStrength(); + internalUpdatePanning(now: number, dt: number) { + const baseStrength = velocityStrength * this.root.app.platformWrapper.getTouchPanStrength(); this.touchPostMoveVelocity = this.touchPostMoveVelocity.multiplyScalar(velocityFade); // Check if the camera is being dragged but standing still: if not, zero out `touchPostMoveVelocity`. if (this.currentlyMoving && this.desiredCenter === null) { @@ -694,7 +694,7 @@ export class Camera extends BasicSerializableObject { } // Check influence of past points if (!this.currentlyMoving && !this.currentlyPinching) { - const len: any = this.touchPostMoveVelocity.length(); + const len = this.touchPostMoveVelocity.length(); if (len >= velocityMax) { this.touchPostMoveVelocity.x = (this.touchPostMoveVelocity.x * velocityMax) / len; this.touchPostMoveVelocity.y = (this.touchPostMoveVelocity.y * velocityMax) / len; @@ -709,7 +709,7 @@ export class Camera extends BasicSerializableObject { /** * Internal screen panning handler */ - internalUpdateMousePanning(now: number, dt: number): any { + internalUpdateMousePanning(now: number, dt: number) { if (!this.root.app.focused) { return; } @@ -717,7 +717,7 @@ export class Camera extends BasicSerializableObject { // Not enabled return; } - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (!mousePos) { return; } @@ -735,8 +735,8 @@ export class Camera extends BasicSerializableObject { // Out of screen return; } - const panAreaPixels: any = 2; - const panVelocity: any = new Vector(); + const panAreaPixels = 2; + const panVelocity = new Vector(); if (mousePos.x < panAreaPixels) { panVelocity.x -= 1; } @@ -755,11 +755,11 @@ export class Camera extends BasicSerializableObject { /** * Updates the non user interaction zooming */ - internalUpdateZooming(now: number, dt: number): any { + internalUpdateZooming(now: number, dt: number) { if (!this.currentlyPinching && this.desiredZoom !== null) { - const diff: any = this.zoomLevel - this.desiredZoom; + const diff = this.zoomLevel - this.desiredZoom; if (Math.abs(diff) > 0.0001) { - let fade: any = 0.94; + let fade = 0.94; if (diff > 0) { // Zoom out faster than in fade = 0.9; @@ -778,13 +778,13 @@ export class Camera extends BasicSerializableObject { /** * Updates the non user interaction centering */ - internalUpdateCentering(now: number, dt: number): any { + internalUpdateCentering(now: number, dt: number) { if (!this.currentlyMoving && this.desiredCenter !== null) { - const diff: any = this.center.direction(this.desiredCenter); - const length: any = diff.length(); - const tolerance: any = 1 / this.zoomLevel; + const diff = this.center.direction(this.desiredCenter); + const length = diff.length(); + const tolerance = 1 / this.zoomLevel; if (length > tolerance) { - const movement: any = diff.multiplyScalar(Math.min(1, dt * 0.008)); + const movement = diff.multiplyScalar(Math.min(1, dt * 0.008)); this.center.x += movement.x; this.center.y += movement.y; } @@ -796,13 +796,13 @@ export class Camera extends BasicSerializableObject { /** * Updates the keyboard forces */ - internalUpdateKeyboardForce(now: number, dt: number): any { + internalUpdateKeyboardForce(now: number, dt: number) { if (!this.currentlyMoving && this.desiredCenter == null) { - const limitingDimension: any = Math.min(this.root.gameWidth, this.root.gameHeight); - const moveAmount: any = ((limitingDimension / 2048) * dt) / this.zoomLevel; - let forceX: any = 0; - let forceY: any = 0; - const actionMapper: any = this.root.keyMapper; + const limitingDimension = Math.min(this.root.gameWidth, this.root.gameHeight); + const moveAmount = ((limitingDimension / 2048) * dt) / this.zoomLevel; + let forceX = 0; + let forceY = 0; + const actionMapper = this.root.keyMapper; if (actionMapper.getBinding(KEYMAPPINGS.navigation.mapMoveUp).pressed) { forceY -= 1; } @@ -815,7 +815,7 @@ export class Camera extends BasicSerializableObject { if (actionMapper.getBinding(KEYMAPPINGS.navigation.mapMoveRight).pressed) { forceX += 1; } - let movementSpeed: any = this.root.app.settings.getMovementSpeed() * + let movementSpeed = this.root.app.settings.getMovementSpeed() * (actionMapper.getBinding(KEYMAPPINGS.navigation.mapMoveFaster).pressed ? 4 : 1); this.center.x += moveAmount * forceX * movementSpeed; this.center.y += moveAmount * forceY * movementSpeed; diff --git a/src/ts/game/colors.ts b/src/ts/game/colors.ts index a52698ba..f6cc5c93 100644 --- a/src/ts/game/colors.ts +++ b/src/ts/game/colors.ts @@ -1,5 +1,5 @@ /** @enum {string} */ -export const enumColors: any = { +export const enumColors = { red: "red", green: "green", blue: "blue", @@ -9,9 +9,9 @@ export const enumColors: any = { white: "white", uncolored: "uncolored", }; -const c: any = enumColors; +const c = enumColors; /** @enum {string} */ -export const enumColorToShortcode: any = { +export const enumColorToShortcode = { [c.red]: "r", [c.green]: "g", [c.blue]: "b", @@ -22,12 +22,12 @@ export const enumColorToShortcode: any = { [c.uncolored]: "u", }; /** @enum {enumColors} */ -export const enumShortcodeToColor: any = {}; -for (const key: any in enumColorToShortcode) { +export const enumShortcodeToColor = {}; +for (const key in enumColorToShortcode) { enumShortcodeToColor[enumColorToShortcode[key]] = key; } /** @enum {string} */ -export const enumColorsToHexCode: any = { +export const enumColorsToHexCode = { [c.red]: "#ff666a", [c.green]: "#78ff66", [c.blue]: "#66a7ff", @@ -42,8 +42,8 @@ export const enumColorsToHexCode: any = { [c.uncolored]: "#aaaaaa", }; /** @enum {Object.} */ -export const enumColorMixingResults: any = {}; -const bitfieldToColor: any = [ +export const enumColorMixingResults = {}; +const bitfieldToColor = [ /* 000 */ c.uncolored, /* 001 */ c.red, /* 010 */ c.green, @@ -53,9 +53,9 @@ const bitfieldToColor: any = [ /* 110 */ c.cyan, /* 111 */ c.white, ]; -for (let i: any = 0; i < 1 << 3; ++i) { +for (let i = 0; i < 1 << 3; ++i) { enumColorMixingResults[bitfieldToColor[i]] = {}; - for (let j: any = 0; j < 1 << 3; ++j) { + for (let j = 0; j < 1 << 3; ++j) { enumColorMixingResults[bitfieldToColor[i]][bitfieldToColor[j]] = bitfieldToColor[i | j]; } } diff --git a/src/ts/game/component.ts b/src/ts/game/component.ts index c53f0529..4e62f5ee 100644 --- a/src/ts/game/component.ts +++ b/src/ts/game/component.ts @@ -12,17 +12,17 @@ export class Component extends BasicSerializableObject { /** * Should return the schema used for serialization */ - static getSchema(): any { + static getSchema() { return {}; } /** * Copy the current state to another component */ - copyAdditionalStateTo(otherComponent: Component): any { } + copyAdditionalStateTo(otherComponent: Component) { } /** * Clears all items and state */ - clear(): any { } + clear() { } /* dev:start */ /** * Fixes typeof DerivedComponent is not assignable to typeof Component, compiled out diff --git a/src/ts/game/component_registry.ts b/src/ts/game/component_registry.ts index c6ce29a6..e4756305 100644 --- a/src/ts/game/component_registry.ts +++ b/src/ts/game/component_registry.ts @@ -20,8 +20,8 @@ import { BeltReaderComponent } from "./components/belt_reader"; import { FilterComponent } from "./components/filter"; import { ItemProducerComponent } from "./components/item_producer"; import { GoalAcceptorComponent } from "./components/goal_acceptor"; -export function initComponentRegistry(): any { - const components: any = [ +export function initComponentRegistry() { + const components = [ StaticMapEntityComponent, BeltComponent, ItemEjectorComponent, @@ -44,7 +44,7 @@ export function initComponentRegistry(): any { ItemProducerComponent, GoalAcceptorComponent, ]; - components.forEach((component: any): any => gComponentRegistry.register(component)); + components.forEach(component => gComponentRegistry.register(component)); // IMPORTANT ^^^^^ UPDATE ENTITY COMPONENT STORAGE AFTERWARDS // Sanity check - If this is thrown, you forgot to add a new component here assert( diff --git a/src/ts/game/components/belt.ts b/src/ts/game/components/belt.ts index 02b82621..6fba8c91 100644 --- a/src/ts/game/components/belt.ts +++ b/src/ts/game/components/belt.ts @@ -2,7 +2,7 @@ import { enumDirection, Vector } from "../../core/vector"; import { types } from "../../savegame/serialization"; import { BeltPath } from "../belt_path"; import { Component } from "../component"; -export const curvedBeltLength: any = 0.78; +export const curvedBeltLength = /* Math.PI / 4 */ 0.78; export const FAKE_BELT_ACCEPTOR_SLOT: import("./item_acceptor").ItemAcceptorSlot = { pos: new Vector(0, 0), direction: enumDirection.bottom, @@ -30,7 +30,7 @@ export const FAKE_BELT_EJECTOR_SLOT_BY_DIRECTION: { }, }; export class BeltComponent extends Component { - static getId(): any { + static getId() { return "Belt"; } public direction = direction; @@ -39,7 +39,7 @@ export class BeltComponent extends Component { constructor({ direction = enumDirection.top }) { super(); } - clear(): any { + clear() { if (this.assignedPath) { this.assignedPath.clearAllItems(); } @@ -79,12 +79,12 @@ export class BeltComponent extends Component { return new Vector(0, 0.5 - progress); case enumDirection.right: { assert(progress <= curvedBeltLength + 0.02, "Invalid progress 2: " + progress); - const arcProgress: any = (progress / curvedBeltLength) * 0.5 * Math.PI; + const arcProgress = (progress / curvedBeltLength) * 0.5 * Math.PI; return new Vector(0.5 - 0.5 * Math.cos(arcProgress), 0.5 - 0.5 * Math.sin(arcProgress)); } case enumDirection.left: { assert(progress <= curvedBeltLength + 0.02, "Invalid progress 3: " + progress); - const arcProgress: any = (progress / curvedBeltLength) * 0.5 * Math.PI; + const arcProgress = (progress / curvedBeltLength) * 0.5 * Math.PI; return new Vector(-0.5 + 0.5 * Math.cos(arcProgress), 0.5 - 0.5 * Math.sin(arcProgress)); } default: diff --git a/src/ts/game/components/belt_reader.ts b/src/ts/game/components/belt_reader.ts index 00732fe3..d0336221 100644 --- a/src/ts/game/components/belt_reader.ts +++ b/src/ts/game/components/belt_reader.ts @@ -3,15 +3,15 @@ import { BaseItem } from "../base_item"; import { typeItemSingleton } from "../item_resolver"; import { types } from "../../savegame/serialization"; /** @enum {string} */ -export const enumBeltReaderType: any = { +export const enumBeltReaderType = { wired: "wired", wireless: "wireless", }; export class BeltReaderComponent extends Component { - static getId(): any { + static getId() { return "BeltReader"; } - static getSchema(): any { + static getSchema() { return { lastItem: types.nullable(typeItemSingleton), }; @@ -21,7 +21,7 @@ export class BeltReaderComponent extends Component { super(); this.clear(); } - clear(): any { + clear() { /** * Which items went through the reader, we only store the time */ diff --git a/src/ts/game/components/belt_underlays.ts b/src/ts/game/components/belt_underlays.ts index fd2356cf..a6e9d652 100644 --- a/src/ts/game/components/belt_underlays.ts +++ b/src/ts/game/components/belt_underlays.ts @@ -9,7 +9,7 @@ import { Component } from "../component"; * Top Only: * @enum {string} */ -export const enumClippedBeltUnderlayType: any = { +export const enumClippedBeltUnderlayType = { full: "full", bottomOnly: "bottomOnly", topOnly: "topOnly", @@ -22,7 +22,7 @@ export type BeltUnderlayTile = { }; export class BeltUnderlaysComponent extends Component { - static getId(): any { + static getId() { return "BeltUnderlays"; } public underlays = underlays; diff --git a/src/ts/game/components/constant_signal.ts b/src/ts/game/components/constant_signal.ts index 7f57d21d..7f07210e 100644 --- a/src/ts/game/components/constant_signal.ts +++ b/src/ts/game/components/constant_signal.ts @@ -3,10 +3,10 @@ import { BaseItem } from "../base_item"; import { Component } from "../component"; import { typeItemSingleton } from "../item_resolver"; export class ConstantSignalComponent extends Component { - static getId(): any { + static getId() { return "ConstantSignal"; } - static getSchema(): any { + static getSchema() { return { signal: types.nullable(typeItemSingleton), }; @@ -14,7 +14,7 @@ export class ConstantSignalComponent extends Component { /** * Copy the current state to another component */ - copyAdditionalStateTo(otherComponent: ConstantSignalComponent): any { + copyAdditionalStateTo(otherComponent: ConstantSignalComponent) { otherComponent.signal = this.signal; } public signal = signal; diff --git a/src/ts/game/components/display.ts b/src/ts/game/components/display.ts index 41077759..404c74cc 100644 --- a/src/ts/game/components/display.ts +++ b/src/ts/game/components/display.ts @@ -1,6 +1,6 @@ import { Component } from "../component"; export class DisplayComponent extends Component { - static getId(): any { + static getId() { return "Display"; } } diff --git a/src/ts/game/components/filter.ts b/src/ts/game/components/filter.ts index b78e0bfc..382924db 100644 --- a/src/ts/game/components/filter.ts +++ b/src/ts/game/components/filter.ts @@ -8,13 +8,13 @@ export type PendingFilterItem = { }; export class FilterComponent extends Component { - static getId(): any { + static getId() { return "Filter"; } - duplicateWithoutContents(): any { + duplicateWithoutContents() { return new FilterComponent(); } - static getSchema(): any { + static getSchema() { return { pendingItemsToLeaveThrough: types.array(types.structured({ item: typeItemSingleton, @@ -31,7 +31,7 @@ export class FilterComponent extends Component { super(); this.clear(); } - clear(): any { + clear() { /** * Items in queue to leave through */ diff --git a/src/ts/game/components/goal_acceptor.ts b/src/ts/game/components/goal_acceptor.ts index efca96ab..5cf65e77 100644 --- a/src/ts/game/components/goal_acceptor.ts +++ b/src/ts/game/components/goal_acceptor.ts @@ -3,10 +3,10 @@ import { BaseItem } from "../base_item"; import { Component } from "../component"; import { typeItemSingleton } from "../item_resolver"; export class GoalAcceptorComponent extends Component { - static getId(): any { + static getId() { return "GoalAcceptor"; } - static getSchema(): any { + static getSchema() { return { item: typeItemSingleton, }; @@ -17,7 +17,7 @@ export class GoalAcceptorComponent extends Component { super(); this.clear(); } - clear(): any { + clear() { /** * The last item we delivered */ @@ -30,18 +30,18 @@ export class GoalAcceptorComponent extends Component { /** * Clears items but doesn't instantly reset the progress bar */ - clearItems(): any { + clearItems() { this.lastDelivery = null; this.currentDeliveredItems = 0; } - getRequiredSecondsPerItem(): any { + getRequiredSecondsPerItem() { return (globalConfig.goalAcceptorsPerProducer / (globalConfig.puzzleModeSpeed * globalConfig.beltSpeedItemsPerSecond)); } /** * Copy the current state to another component */ - copyAdditionalStateTo(otherComponent: GoalAcceptorComponent): any { + copyAdditionalStateTo(otherComponent: GoalAcceptorComponent) { otherComponent.item = this.item; } } diff --git a/src/ts/game/components/hub.ts b/src/ts/game/components/hub.ts index 3287dbe7..11caab3a 100644 --- a/src/ts/game/components/hub.ts +++ b/src/ts/game/components/hub.ts @@ -1,6 +1,6 @@ import { Component } from "../component"; export class HubComponent extends Component { - static getId(): any { + static getId() { return "Hub"; } } diff --git a/src/ts/game/components/item_acceptor.ts b/src/ts/game/components/item_acceptor.ts index f0aafcb6..d9ceabdd 100644 --- a/src/ts/game/components/item_acceptor.ts +++ b/src/ts/game/components/item_acceptor.ts @@ -20,7 +20,7 @@ export type ItemAcceptorSlotConfig = { export class ItemAcceptorComponent extends Component { - static getId(): any { + static getId() { return "ItemAcceptor"; } @@ -29,16 +29,16 @@ export class ItemAcceptorComponent extends Component { this.setSlots(slots); this.clear(); } - clear(): any { + clear() { /** * Fixes belt animations */ this.itemConsumptionAnimations = []; } - setSlots(slots: Array): any { + setSlots(slots: Array) { this.slots = []; - for (let i: any = 0; i < slots.length; ++i) { - const slot: any = slots[i]; + for (let i = 0; i < slots.length; ++i) { + const slot = slots[i]; this.slots.push({ pos: slot.pos, direction: slot.direction, @@ -52,14 +52,14 @@ export class ItemAcceptorComponent extends Component { * * NOTICE: The belt path ignores this for performance reasons and does his own check */ - canAcceptItem(slotIndex: number, item: BaseItem=): any { - const slot: any = this.slots[slotIndex]; + canAcceptItem(slotIndex: number, item: BaseItem=) { + const slot = this.slots[slotIndex]; return !slot.filter || slot.filter === item.getItemType(); } /** * Called when an item has been accepted so that */ - onItemAccepted(slotIndex: number, direction: enumDirection, item: BaseItem, remainingProgress: number = 0.0): any { + onItemAccepted(slotIndex: number, direction: enumDirection, item: BaseItem, remainingProgress: number = 0.0) { this.itemConsumptionAnimations.push({ item, slotIndex, @@ -75,10 +75,10 @@ export class ItemAcceptorComponent extends Component { // We need to invert our direction since the acceptor specifies *from* which direction // it accepts items, but the ejector specifies *into* which direction it ejects items. // E.g.: Ejector ejects into "right" direction but acceptor accepts from "left" direction. - const desiredDirection: any = enumInvertedDirections[fromLocalDirection]; + const desiredDirection = enumInvertedDirections[fromLocalDirection]; // Go over all slots and try to find a target slot - for (let slotIndex: any = 0; slotIndex < this.slots.length; ++slotIndex) { - const slot: any = this.slots[slotIndex]; + for (let slotIndex = 0; slotIndex < this.slots.length; ++slotIndex) { + const slot = this.slots[slotIndex]; // Make sure the acceptor slot is on the right position if (!slot.pos.equals(targetLocalTile)) { continue; diff --git a/src/ts/game/components/item_ejector.ts b/src/ts/game/components/item_ejector.ts index 22c0f932..06f221c5 100644 --- a/src/ts/game/components/item_ejector.ts +++ b/src/ts/game/components/item_ejector.ts @@ -17,10 +17,10 @@ export type ItemEjectorSlot = { }; export class ItemEjectorComponent extends Component { - static getId(): any { + static getId() { return "ItemEjector"; } - static getSchema(): any { + static getSchema() { // The cachedDestSlot, cachedTargetEntity fields are not serialized. return { slots: types.fixedSizeArray(types.structured({ @@ -35,8 +35,8 @@ export class ItemEjectorComponent extends Component { super(); this.setSlots(slots); } - clear(): any { - for (const slot: any of this.slots) { + clear() { + for (const slot of this.slots) { slot.item = null; slot.lastItem = null; slot.progress = 0; @@ -45,10 +45,10 @@ export class ItemEjectorComponent extends Component { setSlots(slots: Array<{ pos: Vector; direction: enumDirection; - }>): any { + }>) { this.slots = []; - for (let i: any = 0; i < slots.length; ++i) { - const slot: any = slots[i]; + for (let i = 0; i < slots.length; ++i) { + const slot = slots[i]; this.slots.push({ pos: slot.pos, direction: slot.direction, @@ -65,14 +65,14 @@ export class ItemEjectorComponent extends Component { * {} */ getSlotTargetLocalTile(slot: ItemEjectorSlot): Vector { - const directionVector: any = enumDirectionToVector[slot.direction]; + const directionVector = enumDirectionToVector[slot.direction]; return slot.pos.add(directionVector); } /** * Returns whether any slot ejects to the given local tile */ - anySlotEjectsToLocalTile(tile: Vector): any { - for (let i: any = 0; i < this.slots.length; ++i) { + anySlotEjectsToLocalTile(tile: Vector) { + for (let i = 0; i < this.slots.length; ++i) { if (this.getSlotTargetLocalTile(this.slots[i]).equals(tile)) { return true; } @@ -92,7 +92,7 @@ export class ItemEjectorComponent extends Component { * {} */ getFirstFreeSlot(): ?number { - for (let i: any = 0; i < this.slots.length; ++i) { + for (let i = 0; i < this.slots.length; ++i) { if (this.canEjectOnSlot(i)) { return i; } @@ -117,8 +117,8 @@ export class ItemEjectorComponent extends Component { * {} */ takeSlotItem(slotIndex: number): BaseItem | null { - const slot: any = this.slots[slotIndex]; - const item: any = slot.item; + const slot = this.slots[slotIndex]; + const item = slot.item; slot.item = null; slot.progress = 0.0; return item; diff --git a/src/ts/game/components/item_processor.ts b/src/ts/game/components/item_processor.ts index 9d901443..45b7909b 100644 --- a/src/ts/game/components/item_processor.ts +++ b/src/ts/game/components/item_processor.ts @@ -2,7 +2,7 @@ import { types } from "../../savegame/serialization"; import { BaseItem } from "../base_item"; import { Component } from "../component"; /** @enum {string} */ -export const enumItemProcessorTypes: any = { +export const enumItemProcessorTypes = { balancer: "balancer", cutter: "cutter", cutterQuad: "cutterQuad", @@ -21,7 +21,7 @@ export const enumItemProcessorTypes: any = { goal: "goal", }; /** @enum {string} */ -export const enumItemProcessorRequirements: any = { +export const enumItemProcessorRequirements = { painterQuad: "painterQuad", }; export type EjectorItemToEject = { @@ -36,10 +36,10 @@ export type EjectorCharge = { export class ItemProcessorComponent extends Component { - static getId(): any { + static getId() { return "ItemProcessor"; } - static getSchema(): any { + static getSchema() { return { nextOutputSlot: types.uint, }; @@ -53,7 +53,7 @@ export class ItemProcessorComponent extends Component { super(); this.clear(); } - clear(): any { + clear() { // Which slot to emit next, this is only a preference and if it can't emit // it will take the other one. Some machines ignore this (e.g. the balancer) to make // sure the outputs always match @@ -78,7 +78,7 @@ export class ItemProcessorComponent extends Component { /** * Tries to take the item */ - tryTakeItem(item: BaseItem, sourceSlot: number): any { + tryTakeItem(item: BaseItem, sourceSlot: number) { if (this.type === enumItemProcessorTypes.hub || this.type === enumItemProcessorTypes.trash || this.type === enumItemProcessorTypes.goal) { diff --git a/src/ts/game/components/item_producer.ts b/src/ts/game/components/item_producer.ts index ac027a03..6fe26138 100644 --- a/src/ts/game/components/item_producer.ts +++ b/src/ts/game/components/item_producer.ts @@ -1,6 +1,6 @@ import { Component } from "../component"; export class ItemProducerComponent extends Component { - static getId(): any { + static getId() { return "ItemProducer"; } } diff --git a/src/ts/game/components/lever.ts b/src/ts/game/components/lever.ts index 0d081d3e..e5c4673d 100644 --- a/src/ts/game/components/lever.ts +++ b/src/ts/game/components/lever.ts @@ -1,10 +1,10 @@ import { Component } from "../component"; import { types } from "../../savegame/serialization"; export class LeverComponent extends Component { - static getId(): any { + static getId() { return "Lever"; } - static getSchema(): any { + static getSchema() { return { toggled: types.bool, }; @@ -12,7 +12,7 @@ export class LeverComponent extends Component { /** * Copy the current state to another component */ - copyAdditionalStateTo(otherComponent: LeverComponent): any { + copyAdditionalStateTo(otherComponent: LeverComponent) { otherComponent.toggled = this.toggled; } public toggled = toggled; diff --git a/src/ts/game/components/logic_gate.ts b/src/ts/game/components/logic_gate.ts index ac520586..b95eafee 100644 --- a/src/ts/game/components/logic_gate.ts +++ b/src/ts/game/components/logic_gate.ts @@ -1,6 +1,6 @@ import { Component } from "../component"; /** @enum {string} */ -export const enumLogicGateType: any = { +export const enumLogicGateType = { and: "and", not: "not", xor: "xor", @@ -15,7 +15,7 @@ export const enumLogicGateType: any = { painter: "painter", }; export class LogicGateComponent extends Component { - static getId(): any { + static getId() { return "LogicGate"; } public type = type; diff --git a/src/ts/game/components/miner.ts b/src/ts/game/components/miner.ts index 35a40844..6001c835 100644 --- a/src/ts/game/components/miner.ts +++ b/src/ts/game/components/miner.ts @@ -3,12 +3,12 @@ import { BaseItem } from "../base_item"; import { Component } from "../component"; import { Entity } from "../entity"; import { typeItemSingleton } from "../item_resolver"; -const chainBufferSize: any = 6; +const chainBufferSize = 6; export class MinerComponent extends Component { - static getId(): any { + static getId() { return "Miner"; } - static getSchema(): any { + static getSchema() { // cachedMinedItem is not serialized. return { lastMiningTime: types.ufloat, @@ -24,14 +24,14 @@ export class MinerComponent extends Component { super(); this.clear(); } - clear(): any { + clear() { /** * Stores items from other miners which were chained to this * miner. */ this.itemChainBuffer = []; } - tryAcceptChainedItem(item: BaseItem): any { + tryAcceptChainedItem(item: BaseItem) { if (this.itemChainBuffer.length > chainBufferSize) { // Well, this one is full return false; diff --git a/src/ts/game/components/static_map_entity.ts b/src/ts/game/components/static_map_entity.ts index 3d492881..2af471ac 100644 --- a/src/ts/game/components/static_map_entity.ts +++ b/src/ts/game/components/static_map_entity.ts @@ -7,10 +7,10 @@ import { types } from "../../savegame/serialization"; import { getBuildingDataFromCode } from "../building_codes"; import { Component } from "../component"; export class StaticMapEntityComponent extends Component { - static getId(): any { + static getId() { return "StaticMapEntity"; } - static getSchema(): any { + static getSchema() { return { origin: types.tileVector, rotation: types.float, @@ -71,7 +71,7 @@ export class StaticMapEntityComponent extends Component { /** * Copy the current state to another component */ - copyAdditionalStateTo(otherComponent: Component): any { + copyAdditionalStateTo(otherComponent: Component) { return new StaticMapEntityComponent({ origin: this.origin.copy(), rotation: this.rotation, @@ -93,7 +93,7 @@ export class StaticMapEntityComponent extends Component { * {} */ getTileSpaceBounds(): Rectangle { - const size: any = this.getTileSize(); + const size = this.getTileSize(); switch (this.rotation) { case 0: return new Rectangle(this.origin.x, this.origin.y, size.x, size.y); @@ -140,7 +140,7 @@ export class StaticMapEntityComponent extends Component { * {} */ localTileToWorld(localTile: Vector): Vector { - const result: any = localTile.rotateFastMultipleOf90(this.rotation); + const result = localTile.rotateFastMultipleOf90(this.rotation); result.x += this.origin.x; result.y += this.origin.y; return result; @@ -148,19 +148,19 @@ export class StaticMapEntityComponent extends Component { /** * Transforms from world space to local space */ - worldToLocalTile(worldTile: Vector): any { - const localUnrotated: any = worldTile.sub(this.origin); + worldToLocalTile(worldTile: Vector) { + const localUnrotated = worldTile.sub(this.origin); return this.unapplyRotationToVector(localUnrotated); } /** * Returns whether the entity should be drawn for the given parameters */ - shouldBeDrawn(parameters: DrawParameters): any { - let x: any = 0; - let y: any = 0; - let w: any = 0; - let h: any = 0; - const size: any = this.getTileSize(); + shouldBeDrawn(parameters: DrawParameters) { + let x = 0; + let y = 0; + let w = 0; + let h = 0; + const size = this.getTileSize(); switch (this.rotation) { case 0: { x = this.origin.x; @@ -198,13 +198,13 @@ export class StaticMapEntityComponent extends Component { /** * Draws a sprite over the whole space of the entity */ - drawSpriteOnBoundsClipped(parameters: DrawParameters, sprite: AtlasSprite, extrudePixels: number= = 0, overridePosition: Vector= = null): any { + drawSpriteOnBoundsClipped(parameters: DrawParameters, sprite: AtlasSprite, extrudePixels: number= = 0, overridePosition: Vector= = null) { if (!this.shouldBeDrawn(parameters) && !overridePosition) { return; } - const size: any = this.getTileSize(); - let worldX: any = this.origin.x * globalConfig.tileSize; - let worldY: any = this.origin.y * globalConfig.tileSize; + const size = this.getTileSize(); + let worldX = this.origin.x * globalConfig.tileSize; + let worldY = this.origin.y * globalConfig.tileSize; if (overridePosition) { worldX = overridePosition.x * globalConfig.tileSize; worldY = overridePosition.y * globalConfig.tileSize; @@ -214,8 +214,8 @@ export class StaticMapEntityComponent extends Component { sprite.drawCached(parameters, worldX - extrudePixels * size.x, worldY - extrudePixels * size.y, globalConfig.tileSize * size.x + 2 * extrudePixels * size.x, globalConfig.tileSize * size.y + 2 * extrudePixels * size.y); } else { - const rotationCenterX: any = worldX + globalConfig.halfTileSize; - const rotationCenterY: any = worldY + globalConfig.halfTileSize; + const rotationCenterX = worldX + globalConfig.halfTileSize; + const rotationCenterY = worldY + globalConfig.halfTileSize; parameters.context.translate(rotationCenterX, rotationCenterY); parameters.context.rotate(Math.radians(this.rotation)); sprite.drawCached(parameters, -globalConfig.halfTileSize - extrudePixels * size.x, -globalConfig.halfTileSize - extrudePixels * size.y, globalConfig.tileSize * size.x + 2 * extrudePixels * size.x, globalConfig.tileSize * size.y + 2 * extrudePixels * size.y, false // no clipping possible here diff --git a/src/ts/game/components/storage.ts b/src/ts/game/components/storage.ts index e95da5de..84c15f85 100644 --- a/src/ts/game/components/storage.ts +++ b/src/ts/game/components/storage.ts @@ -8,10 +8,10 @@ export const MODS_ADDITIONAL_STORAGE_ITEM_RESOLVER: { [x: string]: (item: BaseItem) => Boolean; } = {}; export class StorageComponent extends Component { - static getId(): any { + static getId() { return "Storage"; } - static getSchema(): any { + static getSchema() { return { storedCount: types.uint, storedItem: types.nullable(typeItemSingleton), @@ -28,14 +28,14 @@ export class StorageComponent extends Component { /** * Returns whether this storage can accept the item */ - canAcceptItem(item: BaseItem): any { + canAcceptItem(item: BaseItem) { if (this.storedCount >= this.maximumStorage) { return false; } if (!this.storedItem || this.storedCount === 0) { return true; } - const itemType: any = item.getItemType(); + const itemType = item.getItemType(); if (itemType !== this.storedItem.getItemType()) { // Check type matches return false; @@ -60,7 +60,7 @@ export class StorageComponent extends Component { getIsFull(): boolean { return this.storedCount >= this.maximumStorage; } - takeItem(item: BaseItem): any { + takeItem(item: BaseItem) { this.storedItem = item; this.storedCount++; } diff --git a/src/ts/game/components/underground_belt.ts b/src/ts/game/components/underground_belt.ts index e23674d4..2e46b571 100644 --- a/src/ts/game/components/underground_belt.ts +++ b/src/ts/game/components/underground_belt.ts @@ -5,7 +5,7 @@ import { Component } from "../component"; import { Entity } from "../entity"; import { typeItemSingleton } from "../item_resolver"; /** @enum {string} */ -export const enumUndergroundBeltMode: any = { +export const enumUndergroundBeltMode = { sender: "sender", receiver: "receiver", }; @@ -15,10 +15,10 @@ export type LinkedUndergroundBelt = { }; export class UndergroundBeltComponent extends Component { - static getId(): any { + static getId() { return "UndergroundBelt"; } - static getSchema(): any { + static getSchema() { return { pendingItems: types.array(types.pair(typeItemSingleton, types.float)), }; @@ -31,7 +31,7 @@ export class UndergroundBeltComponent extends Component { super(); this.clear(); } - clear(): any { + clear() { this.consumptionAnimations = []; /** * Used on both receiver and sender. @@ -44,7 +44,7 @@ export class UndergroundBeltComponent extends Component { /** * Tries to accept an item from an external source like a regular belt or building */ - tryAcceptExternalItem(item: BaseItem, beltSpeed: number): any { + tryAcceptExternalItem(item: BaseItem, beltSpeed: number) { if (this.mode !== enumUndergroundBeltMode.sender) { // Only senders accept external items return false; @@ -59,13 +59,13 @@ export class UndergroundBeltComponent extends Component { /** * Tries to accept a tunneled item */ - tryAcceptTunneledItem(item: BaseItem, travelDistance: number, beltSpeed: number, now: number): any { + tryAcceptTunneledItem(item: BaseItem, travelDistance: number, beltSpeed: number, now: number) { if (this.mode !== enumUndergroundBeltMode.receiver) { // Only receivers can accept tunneled items return false; } // Notice: We assume that for all items the travel distance is the same - const maxItemsInTunnel: any = (2 + travelDistance) / globalConfig.itemSpacingOnBelts; + const maxItemsInTunnel = (2 + travelDistance) / globalConfig.itemSpacingOnBelts; if (this.pendingItems.length >= maxItemsInTunnel) { // Simulate a real belt which gets full at some point return false; @@ -74,7 +74,7 @@ export class UndergroundBeltComponent extends Component { // This corresponds to the item ejector - it needs 0.5 additional tiles to eject the item. // So instead of adding 1 we add 0.5 only. // Additionally it takes 1 tile for the acceptor which we just add on top. - const travelDuration: any = (travelDistance + 1.5) / beltSpeed / globalConfig.itemSpacingOnBelts; + const travelDuration = (travelDistance + 1.5) / beltSpeed / globalConfig.itemSpacingOnBelts; this.pendingItems.push([item, now + travelDuration]); return true; } diff --git a/src/ts/game/components/wire.ts b/src/ts/game/components/wire.ts index df8a446c..b1bc6b75 100644 --- a/src/ts/game/components/wire.ts +++ b/src/ts/game/components/wire.ts @@ -1,18 +1,18 @@ import { Component } from "../component"; /** @enum {string} */ -export const enumWireType: any = { +export const enumWireType = { forward: "forward", turn: "turn", split: "split", cross: "cross", }; /** @enum {string} */ -export const enumWireVariant: any = { +export const enumWireVariant = { first: "first", second: "second", }; export class WireComponent extends Component { - static getId(): any { + static getId() { return "Wire"; } public type = type; diff --git a/src/ts/game/components/wire_tunnel.ts b/src/ts/game/components/wire_tunnel.ts index 11015240..0f6f2f5c 100644 --- a/src/ts/game/components/wire_tunnel.ts +++ b/src/ts/game/components/wire_tunnel.ts @@ -1,6 +1,6 @@ import { Component } from "../component"; export class WireTunnelComponent extends Component { - static getId(): any { + static getId() { return "WireTunnel"; } public linkedNetworks: Array = []; diff --git a/src/ts/game/components/wired_pins.ts b/src/ts/game/components/wired_pins.ts index baa2778c..74ec2e6d 100644 --- a/src/ts/game/components/wired_pins.ts +++ b/src/ts/game/components/wired_pins.ts @@ -4,7 +4,7 @@ import { Component } from "../component"; import { types } from "../../savegame/serialization"; import { typeItemSingleton } from "../item_resolver"; /** @enum {string} */ -export const enumPinSlotType: any = { +export const enumPinSlotType = { logicalEjector: "logicalEjector", logicalAcceptor: "logicalAcceptor", }; @@ -23,10 +23,10 @@ export type WirePinSlot = { export class WiredPinsComponent extends Component { - static getId(): any { + static getId() { return "WiredPins"; } - static getSchema(): any { + static getSchema() { return { slots: types.fixedSizeArray(types.structured({ value: types.nullable(typeItemSingleton), @@ -41,10 +41,10 @@ export class WiredPinsComponent extends Component { /** * Sets the slots of this building */ - setSlots(slots: Array): any { + setSlots(slots: Array) { this.slots = []; - for (let i: any = 0; i < slots.length; ++i) { - const slotData: any = slots[i]; + for (let i = 0; i < slots.length; ++i) { + const slotData = slots[i]; this.slots.push({ pos: slotData.pos, type: slotData.type, diff --git a/src/ts/game/core.ts b/src/ts/game/core.ts index cb0ac1df..4e7bf8f3 100644 --- a/src/ts/game/core.ts +++ b/src/ts/game/core.ts @@ -34,7 +34,7 @@ import { AchievementProxy } from "./achievement_proxy"; import { SoundProxy } from "./sound_proxy"; import { GameTime } from "./time/game_time"; import { MOD_SIGNALS } from "../mods/mod_signals"; -const logger: any = createLogger("ingame/core"); +const logger = createLogger("ingame/core"); // Store the canvas so we can reuse it later let lastCanvas: HTMLCanvasElement = null; let lastContext: CanvasRenderingContext2D = null; @@ -55,7 +55,7 @@ export class GameCore { * Initializes the root object which stores all game related data. The state * is required as a back reference (used sometimes) */ - initializeRoot(parentState: import("../states/ingame").InGameState, savegame: Savegame, gameModeId: any): any { + initializeRoot(parentState: import("../states/ingame").InGameState, savegame: Savegame, gameModeId) { logger.log("initializing root"); // Construct the root element, this is the data representation of the game this.root = new GameRoot(this.app); @@ -67,7 +67,7 @@ export class GameCore { // Initialize canvas element & context this.internalInitCanvas(); // Members - const root: any = this.root; + const root = this.root; // This isn't nice, but we need it right here root.keyMapper = new KeyActionMapper(root, this.root.gameState.inputReciever); // Init game mode @@ -102,7 +102,7 @@ export class GameCore { } // @todo Find better place if (G_IS_DEV && globalConfig.debug.manualTickOnly) { - this.root.gameState.inputReciever.keydown.add((key: any): any => { + this.root.gameState.inputReciever.keydown.add(key => { if (key.keyCode === 84) { // 'T' // Extract current real time @@ -123,7 +123,7 @@ export class GameCore { * Initializes a new game, this means creating a new map and centering on the * playerbase */ - initNewGame(): any { + initNewGame() { logger.log("Initializing new game"); this.root.gameIsFresh = true; this.root.map.seed = randomInt(0, 100000); @@ -131,7 +131,7 @@ export class GameCore { return; } // Place the hub - const hub: any = gMetaBuildingRegistry.findByClass(MetaHubBuilding).createEntity({ + const hub = gMetaBuildingRegistry.findByClass(MetaHubBuilding).createEntity({ root: this.root, origin: new Vector(-2, -2), rotation: 0, @@ -147,17 +147,17 @@ export class GameCore { * Inits an existing game by loading the raw savegame data and deserializing it. * Also runs basic validity checks. */ - initExistingGame(): any { + initExistingGame() { logger.log("Initializing existing game"); - const serializer: any = new SavegameSerializer(); + const serializer = new SavegameSerializer(); try { - const status: any = serializer.deserialize(this.root.savegame.getCurrentDump(), this.root); + const status = serializer.deserialize(this.root.savegame.getCurrentDump(), this.root); if (!status.isGood()) { logger.error("savegame-deserialize-failed:" + status.reason); return false; } } - catch (ex: any) { + catch (ex) { logger.error("Exception during deserialization:", ex); return false; } @@ -167,8 +167,8 @@ export class GameCore { /** * Initializes the render canvas */ - internalInitCanvas(): any { - let canvas: any, context: any; + internalInitCanvas() { + let canvas, context; if (!lastCanvas) { logger.log("Creating new canvas"); canvas = document.createElement("canvas"); @@ -207,7 +207,7 @@ export class GameCore { /** * Destructs the root, freeing all resources */ - destruct(): any { + destruct() { if (lastCanvas && lastCanvas.parentElement) { lastCanvas.parentElement.removeChild(lastCanvas); } @@ -216,8 +216,8 @@ export class GameCore { this.root = null; this.app = null; } - tick(deltaMs: any): any { - const root: any = this.root; + tick(deltaMs) { + const root = this.root; // Extract current real time root.time.updateRealtimeNow(); // Camera is always updated, no matter what @@ -234,7 +234,7 @@ export class GameCore { root.automaticSave.update(); return true; } - shouldRender(): any { + shouldRender() { if (this.root.queue.requireRedraw) { return true; } @@ -247,8 +247,8 @@ export class GameCore { } return true; } - updateLogic(): any { - const root: any = this.root; + updateLogic() { + const root = this.root; root.dynamicTickrate.beginTick(); if (G_IS_DEV && globalConfig.debug.disableLogicTicks) { root.dynamicTickrate.endTick(); @@ -269,14 +269,14 @@ export class GameCore { root.dynamicTickrate.endTick(); return true; } - resize(w: any, h: any): any { + resize(w, h) { this.root.gameWidth = w; this.root.gameHeight = h; resizeHighDPICanvas(this.root.canvas, w, h, globalConfig.smoothing.smoothMainCanvas); this.root.signals.resized.dispatch(w, h); this.root.queue.requireRedraw = true; } - postLoadHook(): any { + postLoadHook() { logger.log("Dispatching post load hook"); this.root.signals.postLoadHook.dispatch(); if (!this.root.gameIsFresh) { @@ -285,9 +285,9 @@ export class GameCore { } this.root.gameInitialized = true; } - draw(): any { - const root: any = this.root; - const systems: any = root.systemMgr.systems; + draw() { + const root = this.root; + const systems = root.systemMgr.systems; this.root.dynamicTickrate.onFrameRendered(); if (!this.shouldRender()) { // Always update hud tho @@ -297,17 +297,17 @@ export class GameCore { this.root.signals.gameFrameStarted.dispatch(); root.queue.requireRedraw = false; // Gather context and save all state - const context: any = root.context; + const context = root.context; context.save(); if (G_IS_DEV) { context.fillStyle = "#a10000"; context.fillRect(0, 0, window.innerWidth * 3, window.innerHeight * 3); } // Compute optimal zoom level and atlas scale - const zoomLevel: any = root.camera.zoomLevel; - const lowQuality: any = root.app.settings.getAllSettings().lowQualityTextures; - const effectiveZoomLevel: any = (zoomLevel / globalConfig.assetsDpi) * getDeviceDPI() * globalConfig.assetsSharpness; - let desiredAtlasScale: any = "0.25"; + const zoomLevel = root.camera.zoomLevel; + const lowQuality = root.app.settings.getAllSettings().lowQualityTextures; + const effectiveZoomLevel = (zoomLevel / globalConfig.assetsDpi) * getDeviceDPI() * globalConfig.assetsSharpness; + let desiredAtlasScale = "0.25"; if (effectiveZoomLevel > 0.5 && !lowQuality) { desiredAtlasScale = ORIGINAL_SPRITE_SCALE; } @@ -315,7 +315,7 @@ export class GameCore { desiredAtlasScale = "0.5"; } // Construct parameters required for drawing - const params: any = new DrawParameters({ + const params = new DrawParameters({ context: context, visibleRect: root.camera.getVisibleRect(), desiredAtlasScale, @@ -335,7 +335,7 @@ export class GameCore { root.hud.update(); // Main rendering order // ----- - const desiredOverlayAlpha: any = this.root.camera.getIsMapOverlayActive() ? 1 : 0; + const desiredOverlayAlpha = this.root.camera.getIsMapOverlayActive() ? 1 : 0; this.overlayAlpha = lerp(this.overlayAlpha, desiredOverlayAlpha, 0.25); // On low performance, skip the fade if (this.root.entityMgr.entities.length > 5000 || this.root.dynamicTickrate.averageFps < 50) { @@ -389,8 +389,8 @@ export class GameCore { root.hud.drawOverlays(params); assert(context.globalAlpha === 1.0, "context.globalAlpha not 1 on frame end"); if (G_IS_DEV && globalConfig.debug.simulateSlowRendering) { - let sum: any = 0; - for (let i: any = 0; i < 1e8; ++i) { + let sum = 0; + for (let i = 0; i < 1e8; ++i) { sum += i; } if (Math.random() > 0.95) { @@ -406,7 +406,7 @@ export class GameCore { round2Digits(zoomLevel) + " / Effective Zoom: " + round2Digits(effectiveZoomLevel), 20, 600); - const stats: any = this.root.buffers.getStats(); + const stats = this.root.buffers.getStats(); context.fillText("Maintained Buffers: " + stats.rootKeys + " root keys / " + @@ -414,7 +414,7 @@ export class GameCore { " buffers / VRAM: " + round2Digits(stats.vramBytes / (1024 * 1024)) + " MB", 20, 620); - const internalStats: any = getBufferStats(); + const internalStats = getBufferStats(); context.fillText("Total Buffers: " + internalStats.bufferCount + " buffers / " + diff --git a/src/ts/game/dynamic_tickrate.ts b/src/ts/game/dynamic_tickrate.ts index 5de77d38..6e1d68eb 100644 --- a/src/ts/game/dynamic_tickrate.ts +++ b/src/ts/game/dynamic_tickrate.ts @@ -1,8 +1,8 @@ import { GameRoot } from "./root"; import { createLogger } from "../core/logging"; import { globalConfig } from "../core/config"; -const logger: any = createLogger("dynamic_tickrate"); -const fpsAccumulationTime: any = 1000; +const logger = createLogger("dynamic_tickrate"); +const fpsAccumulationTime = 1000; export class DynamicTickrate { public root = root; public currentTickStart = null; @@ -13,7 +13,7 @@ export class DynamicTickrate { public averageFps = 60; constructor(root) { - const fixedRate: any = this.root.gameMode.getFixedTickrate(); + const fixedRate = this.root.gameMode.getFixedTickrate(); if (fixedRate) { logger.log("Setting fixed tickrate of", fixedRate); this.setTickRate(fixedRate); @@ -25,12 +25,12 @@ export class DynamicTickrate { } } } - onFrameRendered(): any { + onFrameRendered() { ++this.accumulatedFps; - const now: any = performance.now(); - const timeDuration: any = now - this.accumulatedFpsLastUpdate; + const now = performance.now(); + const timeDuration = now - this.accumulatedFpsLastUpdate; if (timeDuration > fpsAccumulationTime) { - const avgFps: any = (this.accumulatedFps / fpsAccumulationTime) * 1000; + const avgFps = (this.accumulatedFps / fpsAccumulationTime) * 1000; this.averageFps = avgFps; this.accumulatedFps = 0; this.accumulatedFpsLastUpdate = now; @@ -39,7 +39,7 @@ export class DynamicTickrate { /** * Sets the tick rate to N updates per second */ - setTickRate(rate: number): any { + setTickRate(rate: number) { logger.log("Applying tick-rate of", rate); this.currentTickRate = rate; this.deltaMs = 1000.0 / this.currentTickRate; @@ -48,27 +48,27 @@ export class DynamicTickrate { /** * Increases the tick rate marginally */ - increaseTickRate(): any { + increaseTickRate() { if (G_IS_DEV && globalConfig.debug.renderForTrailer) { return; } - const desiredFps: any = this.root.app.settings.getDesiredFps(); + const desiredFps = this.root.app.settings.getDesiredFps(); this.setTickRate(Math.round(Math.min(desiredFps, this.currentTickRate * 1.2))); } /** * Decreases the tick rate marginally */ - decreaseTickRate(): any { + decreaseTickRate() { if (G_IS_DEV && globalConfig.debug.renderForTrailer) { return; } - const desiredFps: any = this.root.app.settings.getDesiredFps(); + const desiredFps = this.root.app.settings.getDesiredFps(); this.setTickRate(Math.round(Math.max(desiredFps / 2, this.currentTickRate * 0.8))); } /** * Call whenever a tick began */ - beginTick(): any { + beginTick() { assert(this.currentTickStart === null, "BeginTick called twice"); this.currentTickStart = performance.now(); if (this.capturedTicks.length > this.currentTickRate * 2) { @@ -76,8 +76,8 @@ export class DynamicTickrate { this.capturedTicks.sort(); this.capturedTicks.splice(0, 10); this.capturedTicks.splice(this.capturedTicks.length - 11, 10); - let average: any = 0; - for (let i: any = 0; i < this.capturedTicks.length; ++i) { + let average = 0; + for (let i = 0; i < this.capturedTicks.length; ++i) { average += this.capturedTicks[i]; } average /= this.capturedTicks.length; @@ -95,9 +95,9 @@ export class DynamicTickrate { /** * Call whenever a tick ended */ - endTick(): any { + endTick() { assert(this.currentTickStart !== null, "EndTick called without BeginTick"); - const duration: any = performance.now() - this.currentTickStart; + const duration = performance.now() - this.currentTickStart; this.capturedTicks.push(duration); this.currentTickStart = null; } diff --git a/src/ts/game/entity.ts b/src/ts/game/entity.ts index 861a7317..bff81e4c 100644 --- a/src/ts/game/entity.ts +++ b/src/ts/game/entity.ts @@ -24,7 +24,7 @@ export class Entity extends BasicSerializableObject { constructor(root) { super(); } - static getId(): any { + static getId() { return "Entity"; } /** @@ -40,10 +40,10 @@ export class Entity extends BasicSerializableObject { /** * Returns a clone of this entity */ - clone(): any { - const staticComp: any = this.components.StaticMapEntity; - const buildingData: any = getBuildingDataFromCode(staticComp.code); - const clone: any = buildingData.metaInstance.createEntity({ + clone() { + const staticComp = this.components.StaticMapEntity; + const buildingData = getBuildingDataFromCode(staticComp.code); + const clone = buildingData.metaInstance.createEntity({ root: this.root, origin: staticComp.origin, originalRotation: staticComp.originalRotation, @@ -51,7 +51,7 @@ export class Entity extends BasicSerializableObject { rotationVariant: buildingData.rotationVariant, variant: buildingData.variant, }); - for (const key: any in this.components) { + for (const key in this.components) { this.components[key] as Component).copyAdditionalStateTo(clone.components[key]); } return clone; @@ -60,14 +60,14 @@ export class Entity extends BasicSerializableObject { * Adds a new component, only possible until the entity is registered on the entity manager, * after that use @see EntityManager.addDynamicComponent */ - addComponent(componentInstance: Component, force: boolean = false): any { + addComponent(componentInstance: Component, force: boolean = false) { if (!force && this.registered) { this.root.entityMgr.attachDynamicComponent(this, componentInstance); return; } assert(force || !this.registered, "Entity already registered, use EntityManager.addDynamicComponent"); - const id: any = (componentInstance.constructor as typeof Component).getId(); + const id = componentInstance.constructor as typeof Component).getId(); assert(!this.components[id], "Component already present"); this.components[id] = componentInstance; } @@ -75,25 +75,25 @@ export class Entity extends BasicSerializableObject { * Removes a given component, only possible until the entity is registered on the entity manager, * after that use @see EntityManager.removeDynamicComponent */ - removeComponent(componentClass: typeof Component, force: boolean = false): any { + removeComponent(componentClass: typeof Component, force: boolean = false) { if (!force && this.registered) { this.root.entityMgr.removeDynamicComponent(this, componentClass); return; } assert(force || !this.registered, "Entity already registered, use EntityManager.removeDynamicComponent"); - const id: any = componentClass.getId(); + const id = componentClass.getId(); assert(this.components[id], "Component does not exist on entity"); delete this.components[id]; } /** * Draws the entity, to override use @see Entity.drawImpl */ - drawDebugOverlays(parameters: DrawParameters): any { - const context: any = parameters.context; - const staticComp: any = this.components.StaticMapEntity; + drawDebugOverlays(parameters: DrawParameters) { + const context = parameters.context; + const staticComp = this.components.StaticMapEntity; if (G_IS_DEV && staticComp && globalConfig.debug.showEntityBounds) { if (staticComp) { - const transformed: any = staticComp.getTileSpaceBounds(); + const transformed = staticComp.getTileSpaceBounds(); context.strokeStyle = "rgba(255, 0, 0, 0.5)"; context.lineWidth = 2; // const boundsSize = 20; @@ -103,15 +103,15 @@ export class Entity extends BasicSerializableObject { } } if (G_IS_DEV && staticComp && globalConfig.debug.showAcceptorEjectors) { - const ejectorComp: any = this.components.ItemEjector; + const ejectorComp = this.components.ItemEjector; if (ejectorComp) { - const ejectorSprite: any = Loader.getSprite("sprites/debug/ejector_slot.png"); - for (let i: any = 0; i < ejectorComp.slots.length; ++i) { - const slot: any = ejectorComp.slots[i]; - const slotTile: any = staticComp.localTileToWorld(slot.pos); - const direction: any = staticComp.localDirectionToWorld(slot.direction); - const directionVector: any = enumDirectionToVector[direction]; - const angle: any = Math.radians(enumDirectionToAngle[direction]); + const ejectorSprite = Loader.getSprite("sprites/debug/ejector_slot.png"); + for (let i = 0; i < ejectorComp.slots.length; ++i) { + const slot = ejectorComp.slots[i]; + const slotTile = staticComp.localTileToWorld(slot.pos); + const direction = staticComp.localDirectionToWorld(slot.direction); + const directionVector = enumDirectionToVector[direction]; + const angle = Math.radians(enumDirectionToAngle[direction]); context.globalAlpha = slot.item ? 1 : 0.2; drawRotatedSprite({ parameters, @@ -123,15 +123,15 @@ export class Entity extends BasicSerializableObject { }); } } - const acceptorComp: any = this.components.ItemAcceptor; + const acceptorComp = this.components.ItemAcceptor; if (acceptorComp) { - const acceptorSprite: any = Loader.getSprite("sprites/misc/acceptor_slot.png"); - for (let i: any = 0; i < acceptorComp.slots.length; ++i) { - const slot: any = acceptorComp.slots[i]; - const slotTile: any = staticComp.localTileToWorld(slot.pos); - const direction: any = staticComp.localDirectionToWorld(slot.direction); - const directionVector: any = enumDirectionToVector[direction]; - const angle: any = Math.radians(enumDirectionToAngle[direction] + 180); + const acceptorSprite = Loader.getSprite("sprites/misc/acceptor_slot.png"); + for (let i = 0; i < acceptorComp.slots.length; ++i) { + const slot = acceptorComp.slots[i]; + const slotTile = staticComp.localTileToWorld(slot.pos); + const direction = staticComp.localDirectionToWorld(slot.direction); + const directionVector = enumDirectionToVector[direction]; + const angle = Math.radians(enumDirectionToAngle[direction] + 180); context.globalAlpha = 0.4; drawRotatedSprite({ parameters, @@ -153,7 +153,7 @@ export class Entity extends BasicSerializableObject { * override, should draw the entity * @abstract */ - drawImpl(parameters: DrawParameters): any { + drawImpl(parameters: DrawParameters) { abstract; } } diff --git a/src/ts/game/entity_manager.ts b/src/ts/game/entity_manager.ts index 303b95a6..d9919fd6 100644 --- a/src/ts/game/entity_manager.ts +++ b/src/ts/game/entity_manager.ts @@ -5,7 +5,7 @@ import { Entity } from "./entity"; import { BasicSerializableObject, types } from "../savegame/serialization"; import { createLogger } from "../core/logging"; import { globalConfig } from "../core/config"; -const logger: any = createLogger("entity_manager"); +const logger = createLogger("entity_manager"); // Manages all entities // NOTICE: We use arrayDeleteValue instead of fastArrayDeleteValue since that does not preserve the order // This is slower but we need it for the street path generation @@ -21,25 +21,25 @@ export class EntityManager extends BasicSerializableObject { constructor(root) { super(); } - static getId(): any { + static getId() { return "EntityManager"; } - static getSchema(): any { + static getSchema() { return { nextUid: types.uint, }; } - getStatsText(): any { + getStatsText() { return this.entities.length + " entities [" + this.destroyList.length + " to kill]"; } // Main update - update(): any { + update() { this.processDestroyList(); } /** * Registers a new entity */ - registerEntity(entity: Entity, uid: number= = null): any { + registerEntity(entity: Entity, uid: number= = null) { if (G_IS_DEV && !globalConfig.debug.disableSlowAsserts) { assert(this.entities.indexOf(entity) < 0, `RegisterEntity() called twice for entity ${entity}`); } @@ -50,7 +50,7 @@ export class EntityManager extends BasicSerializableObject { } this.entities.push(entity); // Register into the componentToEntity map - for (const componentId: any in entity.components) { + for (const componentId in entity.components) { if (entity.components[componentId]) { if (this.componentToEntity[componentId]) { this.componentToEntity[componentId].push(entity); @@ -75,10 +75,10 @@ export class EntityManager extends BasicSerializableObject { /** * Call to attach a new component after the creation of the entity */ - attachDynamicComponent(entity: Entity, component: Component): any { + attachDynamicComponent(entity: Entity, component: Component) { entity.addComponent(component, true); - const componentId: any = (component.constructor as typeof Component).getId(); + const componentId = component.constructor as typeof Component).getId(); if (this.componentToEntity[componentId]) { this.componentToEntity[componentId].push(entity); } @@ -90,10 +90,10 @@ export class EntityManager extends BasicSerializableObject { /** * Call to remove a component after the creation of the entity */ - removeDynamicComponent(entity: Entity, component: typeof Component): any { + removeDynamicComponent(entity: Entity, component: typeof Component) { entity.removeComponent(component, true); - const componentId: any = (component.constructor as typeof Component).getId(); + const componentId = component.constructor as typeof Component).getId(); fastArrayDeleteValue(this.componentToEntity[componentId], entity); this.root.signals.entityComponentRemoved.dispatch(entity); } @@ -102,9 +102,9 @@ export class EntityManager extends BasicSerializableObject { * {} */ findByUid(uid: number, errorWhenNotFound: boolean= = true): Entity { - const arr: any = this.entities; - for (let i: any = 0, len: any = arr.length; i < len; ++i) { - const entity: any = arr[i]; + const arr = this.entities; + for (let i = 0, len = arr.length; i < len; ++i) { + const entity = arr[i]; if (entity.uid === uid) { if (entity.queuedForDestroy || entity.destroyed) { if (errorWhenNotFound) { @@ -127,10 +127,10 @@ export class EntityManager extends BasicSerializableObject { * {} */ getFrozenUidSearchMap(): Map { - const result: any = new Map(); - const array: any = this.entities; - for (let i: any = 0, len: any = array.length; i < len; ++i) { - const entity: any = array[i]; + const result = new Map(); + const array = this.entities; + for (let i = 0, len = array.length; i < len; ++i) { + const entity = array[i]; if (!entity.queuedForDestroy && !entity.destroyed) { result.set(entity.uid, entity); } @@ -147,8 +147,8 @@ export class EntityManager extends BasicSerializableObject { /** * Unregisters all components of an entity from the component to entity mapping */ - unregisterEntityComponents(entity: Entity): any { - for (const componentId: any in entity.components) { + unregisterEntityComponents(entity: Entity) { + for (const componentId in entity.components) { if (entity.components[componentId]) { arrayDeleteValue(this.componentToEntity[componentId], entity); } @@ -156,9 +156,9 @@ export class EntityManager extends BasicSerializableObject { } // Processes the entities to destroy and actually destroys them /* eslint-disable max-statements */ - processDestroyList(): any { - for (let i: any = 0; i < this.destroyList.length; ++i) { - const entity: any = this.destroyList[i]; + processDestroyList() { + for (let i = 0; i < this.destroyList.length; ++i) { + const entity = this.destroyList[i]; // Remove from entities list arrayDeleteValue(this.entities, entity); // Remove from componentToEntity list @@ -172,7 +172,7 @@ export class EntityManager extends BasicSerializableObject { /** * Queues an entity for destruction */ - destroyEntity(entity: Entity): any { + destroyEntity(entity: Entity) { if (entity.destroyed) { logger.error("Tried to destroy already destroyed entity:", entity.uid); return; diff --git a/src/ts/game/game_loading_overlay.ts b/src/ts/game/game_loading_overlay.ts index 709be533..300082c2 100644 --- a/src/ts/game/game_loading_overlay.ts +++ b/src/ts/game/game_loading_overlay.ts @@ -13,7 +13,7 @@ export class GameLoadingOverlay { /** * Removes the overlay if its currently visible */ - removeIfAttached(): any { + removeIfAttached() { if (this.element) { this.element.remove(); this.element = null; @@ -22,13 +22,13 @@ export class GameLoadingOverlay { /** * Returns if the loading overlay is attached */ - isAttached(): any { + isAttached() { return this.element; } /** * Shows a super basic overlay */ - showBasic(): any { + showBasic() { assert(!this.element, "Loading overlay already visible, cant show again"); this.element = document.createElement("div"); this.element.classList.add("gameLoadingOverlay"); @@ -40,22 +40,22 @@ export class GameLoadingOverlay { /** * Adds a text with 'loading' and a spinner */ - internalAddSpinnerAndText(element: HTMLElement): any { - const inner: any = document.createElement("span"); + internalAddSpinnerAndText(element: HTMLElement) { + const inner = document.createElement("span"); inner.classList.add("prefab_LoadingTextWithAnim"); element.appendChild(inner); } /** * Adds a random hint */ - internalAddHint(element: HTMLElement): any { - const hint: any = document.createElement("span"); + internalAddHint(element: HTMLElement) { + const hint = document.createElement("span"); hint.innerHTML = randomChoice(T.tips); hint.classList.add("prefab_GameHint"); element.appendChild(hint); } - internalAddProgressIndicator(element: any): any { - const indicator: any = document.createElement("span"); + internalAddProgressIndicator(element) { + const indicator = document.createElement("span"); indicator.innerHTML = ""; indicator.classList.add("prefab_LoadingProgressIndicator"); element.appendChild(indicator); diff --git a/src/ts/game/game_mode.ts b/src/ts/game/game_mode.ts index d9bada57..0885cc76 100644 --- a/src/ts/game/game_mode.ts +++ b/src/ts/game/game_mode.ts @@ -8,13 +8,13 @@ import { MetaBuilding } from "./meta_building"; import { MetaItemProducerBuilding } from "./buildings/item_producer"; import { BaseHUDPart } from "./hud/base_hud_part"; /** @enum {string} */ -export const enumGameModeIds: any = { +export const enumGameModeIds = { puzzleEdit: "puzzleEditMode", puzzlePlay: "puzzlePlayMode", regular: "regularMode", }; /** @enum {string} */ -export const enumGameModeTypes: any = { +export const enumGameModeTypes = { default: "defaultModeType", puzzle: "puzzleModeType", }; @@ -29,7 +29,7 @@ export class GameMode extends BasicSerializableObject { abstract; return "unknownType"; } - static create(root: GameRoot, id: string = enumGameModeIds.regular, payload: object | undefined = undefined): any { + static create(root: GameRoot, id: string = enumGameModeIds.regular, payload: object | undefined = undefined) { return new (gGameModeRegistry.findById(id))(root, payload); } public root = root; @@ -46,7 +46,7 @@ export class GameMode extends BasicSerializableObject { data: super.serialize(), }; } - deserialize({ data }: object): any { + deserialize({ data }: object) { super.deserialize(data, this.root); } /** {} */ @@ -104,13 +104,13 @@ export class GameMode extends BasicSerializableObject { painting: [], }; } - throughputDoesNotMatter(): any { + throughputDoesNotMatter() { return false; } /** * @abstract */ - adjustZone(w: number = 0, h: number = 0): any { + adjustZone(w: number = 0, h: number = 0) { abstract; return; } diff --git a/src/ts/game/game_mode_registry.ts b/src/ts/game/game_mode_registry.ts index fdfa6f34..c0159763 100644 --- a/src/ts/game/game_mode_registry.ts +++ b/src/ts/game/game_mode_registry.ts @@ -2,7 +2,7 @@ import { gGameModeRegistry } from "../core/global_registries"; import { PuzzleEditGameMode } from "./modes/puzzle_edit"; import { PuzzlePlayGameMode } from "./modes/puzzle_play"; import { RegularGameMode } from "./modes/regular"; -export function initGameModeRegistry(): any { +export function initGameModeRegistry() { gGameModeRegistry.register(PuzzleEditGameMode); gGameModeRegistry.register(PuzzlePlayGameMode); gGameModeRegistry.register(RegularGameMode); diff --git a/src/ts/game/game_speed_registry.ts b/src/ts/game/game_speed_registry.ts index 1f41e6c5..e3f20ea8 100644 --- a/src/ts/game/game_speed_registry.ts +++ b/src/ts/game/game_speed_registry.ts @@ -1,6 +1,6 @@ import { RegularGameSpeed } from "./time/regular_game_speed"; import { gGameSpeedRegistry } from "../core/global_registries"; -export function initGameSpeedRegistry(): any { +export function initGameSpeedRegistry() { gGameSpeedRegistry.register(RegularGameSpeed); // Others are disabled for now } diff --git a/src/ts/game/game_system.ts b/src/ts/game/game_system.ts index cbfa5ad4..8e714432 100644 --- a/src/ts/game/game_system.ts +++ b/src/ts/game/game_system.ts @@ -15,19 +15,19 @@ export class GameSystem { /** * Updates the game system, override to perform logic */ - update(): any { } + update() { } /** * Override, do not call this directly, use startDraw() */ - draw(parameters: DrawParameters): any { } + draw(parameters: DrawParameters) { } /** * Should refresh all caches */ - refreshCaches(): any { } + refreshCaches() { } /** * @see GameSystem.draw Wrapper arround the draw method */ - startDraw(parameters: DrawParameters): any { + startDraw(parameters: DrawParameters) { this.draw(parameters); } } diff --git a/src/ts/game/game_system_manager.ts b/src/ts/game/game_system_manager.ts index 0436c060..e98bbb06 100644 --- a/src/ts/game/game_system_manager.ts +++ b/src/ts/game/game_system_manager.ts @@ -27,7 +27,7 @@ import { ItemProducerSystem } from "./systems/item_producer"; import { ConstantProducerSystem } from "./systems/constant_producer"; import { GoalAcceptorSystem } from "./systems/goal_acceptor"; import { ZoneSystem } from "./systems/zone"; -const logger: any = createLogger("game_system_manager"); +const logger = createLogger("game_system_manager"); export const MODS_ADDITIONAL_SYSTEMS: { [idx: string]: Array<{ id: string; @@ -72,14 +72,14 @@ export class GameSystemManager { /** * Initializes all systems */ - internalInitSystems(): any { - const addBefore: any = (id: any): any => { - const systems: any = MODS_ADDITIONAL_SYSTEMS[id]; + internalInitSystems() { + const addBefore = id => { + const systems = MODS_ADDITIONAL_SYSTEMS[id]; if (systems) { - systems.forEach(({ id, systemClass }: any): any => add(id, systemClass)); + systems.forEach(({ id, systemClass }) => add(id, systemClass)); } }; - const add: any = (id: any, systemClass: any): any => { + const add = (id, systemClass) => { addBefore(id); this.systems[id] = new systemClass(this.root); this.systemUpdateOrder.push(id); @@ -120,7 +120,7 @@ export class GameSystemManager { add("zone", ZoneSystem); } addBefore("end"); - for (const key: any in MODS_ADDITIONAL_SYSTEMS) { + for (const key in MODS_ADDITIONAL_SYSTEMS) { if (!this.systems[key] && key !== "end") { logger.error("Mod system not attached due to invalid 'before': ", key); } @@ -130,15 +130,15 @@ export class GameSystemManager { /** * Updates all systems */ - update(): any { - for (let i: any = 0; i < this.systemUpdateOrder.length; ++i) { - const system: any = this.systems[this.systemUpdateOrder[i]]; + update() { + for (let i = 0; i < this.systemUpdateOrder.length; ++i) { + const system = this.systems[this.systemUpdateOrder[i]]; system.update(); } } - refreshCaches(): any { - for (let i: any = 0; i < this.systemUpdateOrder.length; ++i) { - const system: any = this.systems[this.systemUpdateOrder[i]]; + refreshCaches() { + for (let i = 0; i < this.systemUpdateOrder.length; ++i) { + const system = this.systems[this.systemUpdateOrder[i]]; system.refreshCaches(); } } diff --git a/src/ts/game/game_system_with_filter.ts b/src/ts/game/game_system_with_filter.ts index ce8590b8..320bf920 100644 --- a/src/ts/game/game_system_with_filter.ts +++ b/src/ts/game/game_system_with_filter.ts @@ -8,7 +8,7 @@ import { arrayDelete, arrayDeleteValue } from "../core/utils"; import { globalConfig } from "../core/config"; export class GameSystemWithFilter extends GameSystem { public requiredComponents = requiredComponents; - public requiredComponentIds = requiredComponents.map((component: any): any => component.getId()); + public requiredComponentIds = requiredComponents.map(component => component.getId()); public allEntities: Array = []; /** * Constructs a new game system with the given component filter. It will process @@ -24,8 +24,8 @@ export class GameSystemWithFilter extends GameSystem { this.root.signals.postLoadHook.add(this.internalPostLoadHook, this); this.root.signals.bulkOperationFinished.add(this.refreshCaches, this); } - internalPushEntityIfMatching(entity: Entity): any { - for (let i: any = 0; i < this.requiredComponentIds.length; ++i) { + internalPushEntityIfMatching(entity: Entity) { + for (let i = 0; i < this.requiredComponentIds.length; ++i) { if (!entity.components[this.requiredComponentIds[i]]) { return; } @@ -36,20 +36,20 @@ export class GameSystemWithFilter extends GameSystem { } this.internalRegisterEntity(entity); } - internalCheckEntityAfterComponentRemoval(entity: Entity): any { + internalCheckEntityAfterComponentRemoval(entity: Entity) { if (this.allEntities.indexOf(entity) < 0) { // Entity wasn't interesting anyways return; } - for (let i: any = 0; i < this.requiredComponentIds.length; ++i) { + for (let i = 0; i < this.requiredComponentIds.length; ++i) { if (!entity.components[this.requiredComponentIds[i]]) { // Entity is not interesting anymore arrayDeleteValue(this.allEntities, entity); } } } - internalReconsiderEntityToAdd(entity: Entity): any { - for (let i: any = 0; i < this.requiredComponentIds.length; ++i) { + internalReconsiderEntityToAdd(entity: Entity) { + for (let i = 0; i < this.requiredComponentIds.length; ++i) { if (!entity.components[this.requiredComponentIds[i]]) { return; } @@ -59,36 +59,36 @@ export class GameSystemWithFilter extends GameSystem { } this.internalRegisterEntity(entity); } - refreshCaches(): any { + refreshCaches() { // Remove all entities which are queued for destroy - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; if (entity.queuedForDestroy || entity.destroyed) { this.allEntities.splice(i, 1); i -= 1; } } - this.allEntities.sort((a: any, b: any): any => a.uid - b.uid); + this.allEntities.sort((a, b) => a.uid - b.uid); } /** * Recomputes all target entities after the game has loaded */ - internalPostLoadHook(): any { + internalPostLoadHook() { this.refreshCaches(); } - internalRegisterEntity(entity: Entity): any { + internalRegisterEntity(entity: Entity) { this.allEntities.push(entity); if (this.root.gameInitialized && !this.root.bulkOperationRunning) { // Sort entities by uid so behaviour is predictable - this.allEntities.sort((a: any, b: any): any => a.uid - b.uid); + this.allEntities.sort((a, b) => a.uid - b.uid); } } - internalPopEntityIfMatching(entity: Entity): any { + internalPopEntityIfMatching(entity: Entity) { if (this.root.bulkOperationRunning) { // We do this in refreshCaches afterwards return; } - const index: any = this.allEntities.indexOf(entity); + const index = this.allEntities.indexOf(entity); if (index >= 0) { arrayDelete(this.allEntities, index); } diff --git a/src/ts/game/hints.ts b/src/ts/game/hints.ts index 89777ab2..8afbde40 100644 --- a/src/ts/game/hints.ts +++ b/src/ts/game/hints.ts @@ -1,13 +1,13 @@ import { randomChoice } from "../core/utils"; import { T } from "../translations"; -const hintsShown: any = []; +const hintsShown = []; /** * Finds a new hint to show about the game which the user hasn't seen within this session */ -export function getRandomHint(): any { - let maxTries: any = 100 * T.tips.length; +export function getRandomHint() { + let maxTries = 100 * T.tips.length; while (maxTries-- > 0) { - const hint: any = randomChoice(T.tips); + const hint = randomChoice(T.tips); if (!hintsShown.includes(hint)) { hintsShown.push(hint); return hint; diff --git a/src/ts/game/hub_goals.ts b/src/ts/game/hub_goals.ts index 2a45b390..883c1bd2 100644 --- a/src/ts/game/hub_goals.ts +++ b/src/ts/game/hub_goals.ts @@ -8,42 +8,42 @@ import { enumAnalyticsDataSource } from "./production_analytics"; import { GameRoot } from "./root"; import { enumSubShape, ShapeDefinition } from "./shape_definition"; import { enumHubGoalRewards } from "./tutorial_goals"; -export const MOD_ITEM_PROCESSOR_SPEEDS: any = {}; +export const MOD_ITEM_PROCESSOR_SPEEDS = {}; export class HubGoals extends BasicSerializableObject { - static getId(): any { + static getId() { return "HubGoals"; } - static getSchema(): any { + static getSchema() { return { level: types.uint, storedShapes: types.keyValueMap(types.uint), upgradeLevels: types.keyValueMap(types.uint), }; } - rialize(data: *, root: GameRoot): any { - const errorCode: any = super.deserialize(data); + rialize(data: *, root: GameRoot) { + const errorCode = super.deserialize(data); if (errorCode) { return errorCode; } - const levels: any = root.gameMode.getLevelDefinitions(); + const levels = root.gameMode.getLevelDefinitions(); // If freeplay is not available, clamp the level if (!root.gameMode.getIsFreeplayAvailable()) { this.level = Math.min(this.level, levels.length); } // Compute gained rewards - for (let i: any = 0; i < this.level - 1; ++i) { + for (let i = 0; i < this.level - 1; ++i) { if (i < levels.length) { - const reward: any = levels[i].reward; + const reward = levels[i].reward; this.gainedRewards[reward] = (this.gainedRewards[reward] || 0) + 1; } } // Compute upgrade improvements - const upgrades: any = this.root.gameMode.getUpgrades(); - for (const upgradeId: any in upgrades) { - const tiers: any = upgrades[upgradeId]; - const level: any = this.upgradeLevels[upgradeId] || 0; - let totalImprovement: any = 1; - for (let i: any = 0; i < level; ++i) { + const upgrades = this.root.gameMode.getUpgrades(); + for (const upgradeId in upgrades) { + const tiers = upgrades[upgradeId]; + const level = this.upgradeLevels[upgradeId] || 0; + let totalImprovement = 1; + for (let i = 0; i < level; ++i) { totalImprovement += tiers[i].improvement; } this.upgradeImprovements[upgradeId] = totalImprovement; @@ -69,15 +69,15 @@ export class HubGoals extends BasicSerializableObject { constructor(root) { super(); // Reset levels first - const upgrades: any = this.root.gameMode.getUpgrades(); - for (const key: any in upgrades) { + const upgrades = this.root.gameMode.getUpgrades(); + for (const key in upgrades) { this.upgradeLevels[key] = 0; this.upgradeImprovements[key] = 1; } this.computeNextGoal(); // Allow quickly switching goals in dev mode if (G_IS_DEV) { - window.addEventListener("keydown", (ev: any): any => { + window.addEventListener("keydown", ev => { if (ev.key === "p") { // root is not guaranteed to exist within ~0.5s after loading in if (this.root && this.root.app && this.root.app.gameAnalytics) { @@ -104,7 +104,7 @@ export class HubGoals extends BasicSerializableObject { getShapesStored(definition: ShapeDefinition): number { return this.storedShapes[definition.getHash()] || 0; } - takeShapeByKey(key: string, amount: number): any { + takeShapeByKey(key: string, amount: number) { assert(this.getShapesStoredByKey(key) >= amount, "Can not afford: " + key + " x " + amount); assert(amount >= 0, "Amount < 0 for " + key); assert(Number.isInteger(amount), "Invalid amount: " + amount); @@ -121,7 +121,7 @@ export class HubGoals extends BasicSerializableObject { /** * Returns how much of the current goal was already delivered */ - getCurrentGoalDelivered(): any { + getCurrentGoalDelivered() { if (this.currentGoal.throughputOnly) { return (this.root.productionAnalytics.getCurrentShapeRateRaw(enumAnalyticsDataSource.delivered, this.currentGoal.definition) / globalConfig.analyticsSliceDurationSeconds); } @@ -130,13 +130,13 @@ export class HubGoals extends BasicSerializableObject { /** * Returns the current level of a given upgrade */ - getUpgradeLevel(upgradeId: string): any { + getUpgradeLevel(upgradeId: string) { return this.upgradeLevels[upgradeId] || 0; } /** * Returns whether the given reward is already unlocked */ - isRewardUnlocked(reward: enumHubGoalRewards): any { + isRewardUnlocked(reward: enumHubGoalRewards) { if (G_IS_DEV && globalConfig.debug.allBuildingsUnlocked) { return true; } @@ -154,8 +154,8 @@ export class HubGoals extends BasicSerializableObject { * Handles the given definition, by either accounting it towards the * goal or otherwise granting some points */ - handleDefinitionDelivered(definition: ShapeDefinition): any { - const hash: any = definition.getHash(); + handleDefinitionDelivered(definition: ShapeDefinition) { + const hash = definition.getHash(); this.storedShapes[hash] = (this.storedShapes[hash] || 0) + 1; this.root.signals.shapeDelivered.dispatch(definition); // Check if we have enough for the next level @@ -169,11 +169,11 @@ export class HubGoals extends BasicSerializableObject { /** * Creates the next goal */ - computeNextGoal(): any { - const storyIndex: any = this.level - 1; - const levels: any = this.root.gameMode.getLevelDefinitions(); + computeNextGoal() { + const storyIndex = this.level - 1; + const levels = this.root.gameMode.getLevelDefinitions(); if (storyIndex < levels.length) { - const { shape, required, reward, throughputOnly }: any = levels[storyIndex]; + const { shape, required, reward, throughputOnly } = levels[storyIndex]; this.currentGoal = { definition: this.root.shapeDefinitionMgr.getShapeFromShortKey(shape), required, @@ -183,7 +183,7 @@ export class HubGoals extends BasicSerializableObject { return; } //Floor Required amount to remove confusion - const required: any = Math.min(200, Math.floor(4 + (this.level - 27) * 0.25)); + const required = Math.min(200, Math.floor(4 + (this.level - 27) * 0.25)); this.currentGoal = { definition: this.computeFreeplayShape(this.level), required, @@ -194,8 +194,8 @@ export class HubGoals extends BasicSerializableObject { /** * Called when the level was completed */ - onGoalCompleted(): any { - const reward: any = this.currentGoal.reward; + onGoalCompleted() { + const reward = this.currentGoal.reward; this.gainedRewards[reward] = (this.gainedRewards[reward] || 0) + 1; this.root.app.gameAnalytics.handleLevelCompleted(this.level); ++this.level; @@ -205,15 +205,15 @@ export class HubGoals extends BasicSerializableObject { /** * Returns whether we are playing in free-play */ - isFreePlay(): any { + isFreePlay() { return this.level >= this.root.gameMode.getLevelDefinitions().length; } /** * Returns whether a given upgrade can be unlocked */ - canUnlockUpgrade(upgradeId: string): any { - const tiers: any = this.root.gameMode.getUpgrades()[upgradeId]; - const currentLevel: any = this.getUpgradeLevel(upgradeId); + canUnlockUpgrade(upgradeId: string) { + const tiers = this.root.gameMode.getUpgrades()[upgradeId]; + const currentLevel = this.getUpgradeLevel(upgradeId); if (currentLevel >= tiers.length) { // Max level return false; @@ -221,9 +221,9 @@ export class HubGoals extends BasicSerializableObject { if (G_IS_DEV && globalConfig.debug.upgradesNoCost) { return true; } - const tierData: any = tiers[currentLevel]; - for (let i: any = 0; i < tierData.required.length; ++i) { - const requirement: any = tierData.required[i]; + const tierData = tiers[currentLevel]; + for (let i = 0; i < tierData.required.length; ++i) { + const requirement = tierData.required[i]; if ((this.storedShapes[requirement.shape] || 0) < requirement.amount) { return false; } @@ -235,8 +235,8 @@ export class HubGoals extends BasicSerializableObject { * {} */ getAvailableUpgradeCount(): number { - let count: any = 0; - for (const upgradeId: any in this.root.gameMode.getUpgrades()) { + let count = 0; + for (const upgradeId in this.root.gameMode.getUpgrades()) { if (this.canUnlockUpgrade(upgradeId)) { ++count; } @@ -251,9 +251,9 @@ export class HubGoals extends BasicSerializableObject { if (!this.canUnlockUpgrade(upgradeId)) { return false; } - const upgradeTiers: any = this.root.gameMode.getUpgrades()[upgradeId]; - const currentLevel: any = this.getUpgradeLevel(upgradeId); - const tierData: any = upgradeTiers[currentLevel]; + const upgradeTiers = this.root.gameMode.getUpgrades()[upgradeId]; + const currentLevel = this.getUpgradeLevel(upgradeId); + const tierData = upgradeTiers[currentLevel]; if (!tierData) { return false; } @@ -261,8 +261,8 @@ export class HubGoals extends BasicSerializableObject { // Dont take resources } else { - for (let i: any = 0; i < tierData.required.length; ++i) { - const requirement: any = tierData.required[i]; + for (let i = 0; i < tierData.required.length; ++i) { + const requirement = tierData.required[i]; // Notice: Don't have to check for hash here this.storedShapes[requirement.shape] -= requirement.amount; } @@ -276,8 +276,8 @@ export class HubGoals extends BasicSerializableObject { /** * Picks random colors which are close to each other */ - generateRandomColorSet(rng: RandomNumberGenerator, allowUncolored: any = false): any { - const colorWheel: any = [ + generateRandomColorSet(rng: RandomNumberGenerator, allowUncolored = false) { + const colorWheel = [ enumColors.red, enumColors.yellow, enumColors.green, @@ -287,12 +287,12 @@ export class HubGoals extends BasicSerializableObject { enumColors.red, enumColors.yellow, ]; - const universalColors: any = [enumColors.white]; + const universalColors = [enumColors.white]; if (allowUncolored) { universalColors.push(enumColors.uncolored); } - const index: any = rng.nextIntRange(0, colorWheel.length - 2); - const pickedColors: any = colorWheel.slice(index, index + 3); + const index = rng.nextIntRange(0, colorWheel.length - 2); + const pickedColors = colorWheel.slice(index, index + 3); pickedColors.push(rng.choice(universalColors)); return pickedColors; } @@ -301,12 +301,12 @@ export class HubGoals extends BasicSerializableObject { * {} */ computeFreeplayShape(level: number): ShapeDefinition { - const layerCount: any = clamp(this.level / 25, 2, 4); + const layerCount = clamp(this.level / 25, 2, 4); let layers: Array = []; - const rng: any = new RandomNumberGenerator(this.root.map.seed + "/" + level); - const colors: any = this.generateRandomColorSet(rng, level > 35); - let pickedSymmetry: any = null; // pairs of quadrants that must be the same - let availableShapes: any = [enumSubShape.rect, enumSubShape.circle, enumSubShape.star]; + const rng = new RandomNumberGenerator(this.root.map.seed + "/" + level); + const colors = this.generateRandomColorSet(rng, level > 35); + let pickedSymmetry = null; // pairs of quadrants that must be the same + let availableShapes = [enumSubShape.rect, enumSubShape.circle, enumSubShape.star]; if (rng.next() < 0.5) { pickedSymmetry = [ // radial symmetry @@ -316,7 +316,7 @@ export class HubGoals extends BasicSerializableObject { availableShapes.push(enumSubShape.windmill); // windmill looks good only in radial symmetry } else { - const symmetries: any = [ + const symmetries = [ [ // horizontal axis [0, 3], @@ -342,17 +342,17 @@ export class HubGoals extends BasicSerializableObject { ]; pickedSymmetry = rng.choice(symmetries); } - const randomColor: any = (): any => rng.choice(colors); - const randomShape: any = (): any => rng.choice(availableShapes); - let anyIsMissingTwo: any = false; - for (let i: any = 0; i < layerCount; ++i) { + const randomColor = () => rng.choice(colors); + const randomShape = () => rng.choice(availableShapes); + let anyIsMissingTwo = false; + for (let i = 0; i < layerCount; ++i) { const layer: import("./shape_definition").ShapeLayer = [null, null, null, null]; - for (let j: any = 0; j < pickedSymmetry.length; ++j) { - const group: any = pickedSymmetry[j]; - const shape: any = randomShape(); - const color: any = randomColor(); - for (let k: any = 0; k < group.length; ++k) { - const quad: any = group[k]; + for (let j = 0; j < pickedSymmetry.length; ++j) { + const group = pickedSymmetry[j]; + const shape = randomShape(); + const color = randomColor(); + for (let k = 0; k < group.length; ++k) { + const quad = group[k]; layer[quad] = { subShape: shape, color, @@ -368,7 +368,7 @@ export class HubGoals extends BasicSerializableObject { } layers.push(layer); } - const definition: any = new ShapeDefinition({ layers }); + const definition = new ShapeDefinition({ layers }); return this.root.shapeDefinitionMgr.registerOrReturnHandle(definition); } ////////////// HELPERS diff --git a/src/ts/game/hud/base_hud_part.ts b/src/ts/game/hud/base_hud_part.ts index 8672851f..98cb7b6d 100644 --- a/src/ts/game/hud/base_hud_part.ts +++ b/src/ts/game/hud/base_hud_part.ts @@ -13,26 +13,26 @@ export class BaseHUDPart { /** * Should create all require elements */ - createElements(parent: HTMLElement): any { } + createElements(parent: HTMLElement) { } /** * Should initialize the element, called *after* the elements have been created * @abstract */ - initialize(): any { + initialize() { abstract; } /** * Should update any required logic */ - update(): any { } + update() { } /** * Should draw the hud */ - draw(parameters: DrawParameters): any { } + draw(parameters: DrawParameters) { } /** * Should draw any overlays (screen space) */ - drawOverlays(parameters: DrawParameters): any { } + drawOverlays(parameters: DrawParameters) { } /** * Should return true if the widget has a modal dialog opened and thus * the game does not need to update / redraw @@ -51,21 +51,21 @@ export class BaseHUDPart { /** * Should return true if this overlay is open and currently blocking any user interaction */ - isBlockingOverlay(): any { + isBlockingOverlay() { return false; } /** * Cleans up the hud element, if overridden make sure to call super.cleanup */ - cleanup(): any { + cleanup() { this.cleanupClickDetectors(); } /** * Cleans up all click detectors */ - cleanupClickDetectors(): any { + cleanupClickDetectors() { if (this.clickDetectors) { - for (let i: any = 0; i < this.clickDetectors.length; ++i) { + for (let i = 0; i < this.clickDetectors.length; ++i) { this.clickDetectors[i].cleanup(); } this.clickDetectors = []; @@ -74,20 +74,20 @@ export class BaseHUDPart { /** * Should close the element, in case its supported */ - close(): any { } + close() { } // Helpers /** * Helper method to construct a new click detector */ - trackClicks(element: Element, handler: function, args: import("../../core/click_detector").ClickDetectorConstructorArgs= = {}): any { - const detector: any = new ClickDetector(element, args); + trackClicks(element: Element, handler: function, args: import("../../core/click_detector").ClickDetectorConstructorArgs= = {}) { + const detector = new ClickDetector(element, args); detector.click.add(handler, this); this.registerClickDetector(detector); } /** * Registers a new click detector */ - registerClickDetector(detector: ClickDetector): any { + registerClickDetector(detector: ClickDetector) { this.clickDetectors.push(detector); if (G_IS_DEV) { // @ts-ignore @@ -98,8 +98,8 @@ export class BaseHUDPart { /** * Closes this element when its background is clicked */ - closeOnBackgroundClick(element: HTMLElement, closeMethod: function = null): any { - const bgClickDetector: any = new ClickDetector(element, { + closeOnBackgroundClick(element: HTMLElement, closeMethod: function = null) { + const bgClickDetector = new ClickDetector(element, { preventDefault: true, targetOnly: true, applyCssClass: null, @@ -115,14 +115,14 @@ export class BaseHUDPart { * Forwards the game speed keybindings so you can toggle pause / Fastforward * in the building tooltip and such */ - forwardGameSpeedKeybindings(sourceMapper: KeyActionMapper): any { + forwardGameSpeedKeybindings(sourceMapper: KeyActionMapper) { sourceMapper.forward(this.root.keyMapper, ["gamespeed_pause", "gamespeed_fastforward"]); } /** * Forwards the map movement keybindings so you can move the map with the * arrow keys */ - forwardMapMovementKeybindings(sourceMapper: KeyActionMapper): any { + forwardMapMovementKeybindings(sourceMapper: KeyActionMapper) { sourceMapper.forward(this.root.keyMapper, [ "mapMoveUp", "mapMoveRight", diff --git a/src/ts/game/hud/dynamic_dom_attach.ts b/src/ts/game/hud/dynamic_dom_attach.ts index d52b51d2..d63bf67a 100644 --- a/src/ts/game/hud/dynamic_dom_attach.ts +++ b/src/ts/game/hud/dynamic_dom_attach.ts @@ -26,7 +26,7 @@ export class DynamicDomAttach { /** * Internal method to attach the element */ - internalAttach(): any { + internalAttach() { if (!this.attached) { this.parent.appendChild(this.element); assert(this.element.parentElement === this.parent, "Invalid parent #1"); @@ -36,7 +36,7 @@ export class DynamicDomAttach { /** * Internal method to detach the element */ - internalDetach(): any { + internalDetach() { if (this.attached) { assert(this.element.parentElement === this.parent, "Invalid parent #2"); this.element.parentElement.removeChild(this.element); @@ -46,31 +46,31 @@ export class DynamicDomAttach { /** * Returns whether the element is currently attached */ - isAttached(): any { + isAttached() { return this.attached; } /** * Actually sets the 'hovered' class */ - setIsHoveredClass(isHovered: boolean): any { + setIsHoveredClass(isHovered: boolean) { this.element.classList.toggle("hovered", isHovered); } /** * Call this every frame, and the dom attach class will take care of * everything else */ - update(isVisible: boolean): any { + update(isVisible: boolean) { if (isVisible) { this.lastVisibleTime = this.root ? this.root.time.realtimeNow() : 0; this.internalAttach(); if (this.trackHover && this.root) { - let bounds: any = this.lastComputedBounds; + let bounds = this.lastComputedBounds; // Recompute bounds only once in a while if (!bounds || this.root.time.realtimeNow() - this.lastComputedBoundsTime > 1.0) { bounds = this.lastComputedBounds = this.element.getBoundingClientRect(); this.lastComputedBoundsTime = this.root.time.realtimeNow(); } - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (mousePos) { this.trackedIsHovered.set(mousePos.x > bounds.left && mousePos.x < bounds.right && @@ -92,7 +92,7 @@ export class DynamicDomAttach { this.classAttachTimeout = null; } if (isVisible) { - this.classAttachTimeout = setTimeout((): any => { + this.classAttachTimeout = setTimeout(() => { this.element.classList.add(this.attachClass); }, 15); } diff --git a/src/ts/game/hud/hud.ts b/src/ts/game/hud/hud.ts index aafa354f..75bdb42a 100644 --- a/src/ts/game/hud/hud.ts +++ b/src/ts/game/hud/hud.ts @@ -28,7 +28,7 @@ export class GameHUD { /** * Initializes the hud parts */ - initialize(): any { + initialize() { this.signals = { buildingSelectedForPlacement: new Signal() as TypedSignal<[ MetaBuilding | null @@ -86,18 +86,18 @@ export class GameHUD { if (!G_IS_RELEASE && !G_IS_DEV) { this.parts.betaOverlay = new HUDBetaOverlay(this.root); } - const additionalParts: any = this.root.gameMode.additionalHudParts; - for (const [partId, part]: any of Object.entries(additionalParts)) { + const additionalParts = this.root.gameMode.additionalHudParts; + for (const [partId, part] of Object.entries(additionalParts)) { this.parts[partId] = new part(this.root); } MOD_SIGNALS.hudInitializer.dispatch(this.root); - const frag: any = document.createDocumentFragment(); - for (const key: any in this.parts) { + const frag = document.createDocumentFragment(); + for (const key in this.parts) { MOD_SIGNALS.hudElementInitialized.dispatch(this.parts[key]); this.parts[key].createElements(frag); } document.body.appendChild(frag); - for (const key: any in this.parts) { + for (const key in this.parts) { this.parts[key].initialize(); MOD_SIGNALS.hudElementFinalized.dispatch(this.parts[key]); } @@ -111,16 +111,16 @@ export class GameHUD { /** * Attempts to close all overlays */ - closeAllOverlays(): any { - for (const key: any in this.parts) { + closeAllOverlays() { + for (const key in this.parts) { this.parts[key].close(); } } /** * Returns true if the game logic should be paused */ - shouldPauseGame(): any { - for (const key: any in this.parts) { + shouldPauseGame() { + for (const key in this.parts) { if (this.parts[key].shouldPauseGame()) { return true; } @@ -130,8 +130,8 @@ export class GameHUD { /** * Returns true if the rendering can be paused */ - shouldPauseRendering(): any { - for (const key: any in this.parts) { + shouldPauseRendering() { + for (const key in this.parts) { if (this.parts[key].shouldPauseRendering()) { return true; } @@ -141,8 +141,8 @@ export class GameHUD { /** * Returns true if the rendering can be paused */ - hasBlockingOverlayOpen(): any { - for (const key: any in this.parts) { + hasBlockingOverlayOpen() { + for (const key in this.parts) { if (this.parts[key].isBlockingOverlay()) { return true; } @@ -152,17 +152,17 @@ export class GameHUD { /** * Toggles the ui */ - toggleUi(): any { + toggleUi() { document.body.classList.toggle("uiHidden"); } /** * Updates all parts */ - update(): any { + update() { if (!this.root.gameInitialized) { return; } - for (const key: any in this.parts) { + for (const key in this.parts) { this.parts[key].update(); } /* dev:start */ @@ -174,8 +174,8 @@ export class GameHUD { /** * Draws all parts */ - draw(parameters: DrawParameters): any { - const partsOrder: any = [ + draw(parameters: DrawParameters) { + const partsOrder = [ "massSelector", "buildingPlacer", "blueprintPlacer", @@ -185,7 +185,7 @@ export class GameHUD { "shapeTooltip", "interactiveTutorial", ]; - for (let i: any = 0; i < partsOrder.length; ++i) { + for (let i = 0; i < partsOrder.length; ++i) { if (this.parts[partsOrder[i]]) { this.parts[partsOrder[i]].draw(parameters); } @@ -194,9 +194,9 @@ export class GameHUD { /** * Draws all part overlays */ - drawOverlays(parameters: DrawParameters): any { - const partsOrder: any = ["waypoints", "watermark", "wireInfo"]; - for (let i: any = 0; i < partsOrder.length; ++i) { + drawOverlays(parameters: DrawParameters) { + const partsOrder = ["waypoints", "watermark", "wireInfo"]; + for (let i = 0; i < partsOrder.length; ++i) { if (this.parts[partsOrder[i]]) { this.parts[partsOrder[i]].drawOverlays(parameters); } @@ -205,11 +205,11 @@ export class GameHUD { /** * Cleans up everything */ - cleanup(): any { - for (const key: any in this.parts) { + cleanup() { + for (const key in this.parts) { this.parts[key].cleanup(); } - for (const key: any in this.signals) { + for (const key in this.signals) { this.signals[key].removeAll(); } } diff --git a/src/ts/game/hud/parts/base_toolbar.ts b/src/ts/game/hud/parts/base_toolbar.ts index c3dcdb38..d9e61418 100644 --- a/src/ts/game/hud/parts/base_toolbar.ts +++ b/src/ts/game/hud/parts/base_toolbar.ts @@ -34,15 +34,15 @@ export class HUDBaseToolbar extends BaseHUDPart { /** * Should create all require elements */ - createElements(parent: HTMLElement): any { + createElements(parent: HTMLElement) { this.element = makeDiv(parent, this.htmlElementId, ["ingame_buildingsToolbar"], ""); } /** * {} */ filterBuildings(buildings: Array): Array { - const filtered: any = []; - for (let i: any = 0; i < buildings.length; i++) { + const filtered = []; + for (let i = 0; i < buildings.length; i++) { if (this.root.gameMode.isBuildingExcluded(buildings[i])) { continue; } @@ -57,42 +57,42 @@ export class HUDBaseToolbar extends BaseHUDPart { get allBuildings() { return [...this.primaryBuildings, ...this.secondaryBuildings]; } - initialize(): any { - const actionMapper: any = this.root.keyMapper; - let rowSecondary: any; + initialize() { + const actionMapper = this.root.keyMapper; + let rowSecondary; if (this.secondaryBuildings.length > 0) { rowSecondary = makeDiv(this.element, null, ["buildings", "secondary"]); this.secondaryDomAttach = new DynamicDomAttach(this.root, rowSecondary, { attachClass: "visible", }); } - const rowPrimary: any = makeDiv(this.element, null, ["buildings", "primary"]); - const allBuildings: any = this.allBuildings; - for (let i: any = 0; i < allBuildings.length; ++i) { - const metaBuilding: any = gMetaBuildingRegistry.findByClass(allBuildings[i]); - let rawBinding: any = KEYMAPPINGS.buildings[metaBuilding.getId() + "_" + this.layer]; + const rowPrimary = makeDiv(this.element, null, ["buildings", "primary"]); + const allBuildings = this.allBuildings; + for (let i = 0; i < allBuildings.length; ++i) { + const metaBuilding = gMetaBuildingRegistry.findByClass(allBuildings[i]); + let rawBinding = KEYMAPPINGS.buildings[metaBuilding.getId() + "_" + this.layer]; if (!rawBinding) { rawBinding = KEYMAPPINGS.buildings[metaBuilding.getId()]; } if (rawBinding) { - const binding: any = actionMapper.getBinding(rawBinding); - binding.add((): any => this.selectBuildingForPlacement(metaBuilding)); + const binding = actionMapper.getBinding(rawBinding); + binding.add(() => this.selectBuildingForPlacement(metaBuilding)); } else { globalWarn("Building has no keybinding:", metaBuilding.getId()); } - const itemContainer: any = makeDiv(this.primaryBuildings.includes(allBuildings[i]) ? rowPrimary : rowSecondary, null, ["building"]); + const itemContainer = makeDiv(this.primaryBuildings.includes(allBuildings[i]) ? rowPrimary : rowSecondary, null, ["building"]); itemContainer.setAttribute("data-icon", "building_icons/" + metaBuilding.getId() + ".png"); itemContainer.setAttribute("data-id", metaBuilding.getId()); - const icon: any = makeDiv(itemContainer, null, ["icon"]); - this.trackClicks(icon, (): any => this.selectBuildingForPlacement(metaBuilding), { + const icon = makeDiv(itemContainer, null, ["icon"]); + this.trackClicks(icon, () => this.selectBuildingForPlacement(metaBuilding), { clickSound: null, }); //lock icon for puzzle editor if (this.root.gameMode.getIsEditor() && !this.inRequiredBuildings(metaBuilding)) { - const puzzleLock: any = makeDiv(itemContainer, null, ["puzzle-lock"]); + const puzzleLock = makeDiv(itemContainer, null, ["puzzle-lock"]); itemContainer.classList.toggle("editor", true); - this.trackClicks(puzzleLock, (): any => this.toggleBuildingLock(metaBuilding), { + this.trackClicks(puzzleLock, () => this.toggleBuildingLock(metaBuilding), { clickSound: null, }); } @@ -116,14 +116,14 @@ export class HUDBaseToolbar extends BaseHUDPart { /** * Updates the toolbar */ - update(): any { - const visible: any = this.visibilityCondition(); + update() { + const visible = this.visibilityCondition(); this.domAttach.update(visible); if (visible) { - let recomputeSecondaryToolbarVisibility: any = false; - for (const buildingId: any in this.buildingHandles) { - const handle: any = this.buildingHandles[buildingId]; - const newStatus: any = !handle.puzzleLocked && handle.metaBuilding.getIsUnlocked(this.root); + let recomputeSecondaryToolbarVisibility = false; + for (const buildingId in this.buildingHandles) { + const handle = this.buildingHandles[buildingId]; + const newStatus = !handle.puzzleLocked && handle.metaBuilding.getIsUnlocked(this.root); if (handle.unlocked !== newStatus) { handle.unlocked = newStatus; handle.element.classList.toggle("unlocked", newStatus); @@ -131,9 +131,9 @@ export class HUDBaseToolbar extends BaseHUDPart { } } if (recomputeSecondaryToolbarVisibility && this.secondaryDomAttach) { - let anyUnlocked: any = false; - for (let i: any = 0; i < this.secondaryBuildings.length; ++i) { - const metaClass: any = gMetaBuildingRegistry.findByClass(this.secondaryBuildings[i]); + let anyUnlocked = false; + for (let i = 0; i < this.secondaryBuildings.length; ++i) { + const metaClass = gMetaBuildingRegistry.findByClass(this.secondaryBuildings[i]); if (metaClass.getIsUnlocked(this.root)) { anyUnlocked = true; break; @@ -146,20 +146,20 @@ export class HUDBaseToolbar extends BaseHUDPart { /** * Cycles through all buildings */ - cycleBuildings(): any { - const visible: any = this.visibilityCondition(); + cycleBuildings() { + const visible = this.visibilityCondition(); if (!visible) { return; } - let newBuildingFound: any = false; - let newIndex: any = this.lastSelectedIndex; - const direction: any = this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateInverseModifier).pressed + let newBuildingFound = false; + let newIndex = this.lastSelectedIndex; + const direction = this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateInverseModifier).pressed ? -1 : 1; - for (let i: any = 0; i <= this.primaryBuildings.length; ++i) { + for (let i = 0; i <= this.primaryBuildings.length; ++i) { newIndex = safeModulo(newIndex + direction, this.primaryBuildings.length); - const metaBuilding: any = gMetaBuildingRegistry.findByClass(this.primaryBuildings[newIndex]); - const handle: any = this.buildingHandles[metaBuilding.id]; + const metaBuilding = gMetaBuildingRegistry.findByClass(this.primaryBuildings[newIndex]); + const handle = this.buildingHandles[metaBuilding.id]; if (!handle.selected && handle.unlocked) { newBuildingFound = true; break; @@ -168,17 +168,17 @@ export class HUDBaseToolbar extends BaseHUDPart { if (!newBuildingFound) { return; } - const metaBuildingClass: any = this.primaryBuildings[newIndex]; - const metaBuilding: any = gMetaBuildingRegistry.findByClass(metaBuildingClass); + const metaBuildingClass = this.primaryBuildings[newIndex]; + const metaBuilding = gMetaBuildingRegistry.findByClass(metaBuildingClass); this.selectBuildingForPlacement(metaBuilding); } /** * Called when the selected building got changed */ - onSelectedPlacementBuildingChanged(metaBuilding: MetaBuilding): any { - for (const buildingId: any in this.buildingHandles) { - const handle: any = this.buildingHandles[buildingId]; - const newStatus: any = handle.metaBuilding === metaBuilding; + onSelectedPlacementBuildingChanged(metaBuilding: MetaBuilding) { + for (const buildingId in this.buildingHandles) { + const handle = this.buildingHandles[buildingId]; + const newStatus = handle.metaBuilding === metaBuilding; if (handle.selected !== newStatus) { handle.selected = newStatus; handle.element.classList.toggle("selected", newStatus); @@ -189,7 +189,7 @@ export class HUDBaseToolbar extends BaseHUDPart { } this.element.classList.toggle("buildingSelected", !!metaBuilding); } - selectBuildingForPlacement(metaBuilding: MetaBuilding): any { + selectBuildingForPlacement(metaBuilding: MetaBuilding) { if (!this.visibilityCondition()) { // Not active return; @@ -198,7 +198,7 @@ export class HUDBaseToolbar extends BaseHUDPart { this.root.soundProxy.playUiError(); return STOP_PROPAGATION; } - const handle: any = this.buildingHandles[metaBuilding.getId()]; + const handle = this.buildingHandles[metaBuilding.getId()]; if (handle.puzzleLocked) { handle.puzzleLocked = false; handle.element.classList.toggle("unlocked", false); @@ -206,8 +206,8 @@ export class HUDBaseToolbar extends BaseHUDPart { return; } // Allow clicking an item again to deselect it - for (const buildingId: any in this.buildingHandles) { - const handle: any = this.buildingHandles[buildingId]; + for (const buildingId in this.buildingHandles) { + const handle = this.buildingHandles[buildingId]; if (handle.selected && handle.metaBuilding === metaBuilding) { metaBuilding = null; break; @@ -217,7 +217,7 @@ export class HUDBaseToolbar extends BaseHUDPart { this.root.hud.signals.buildingSelectedForPlacement.dispatch(metaBuilding); this.onSelectedPlacementBuildingChanged(metaBuilding); } - toggleBuildingLock(metaBuilding: MetaBuilding): any { + toggleBuildingLock(metaBuilding: MetaBuilding) { if (!this.visibilityCondition()) { // Not active return; @@ -226,26 +226,26 @@ export class HUDBaseToolbar extends BaseHUDPart { this.root.soundProxy.playUiError(); return STOP_PROPAGATION; } - const handle: any = this.buildingHandles[metaBuilding.getId()]; + const handle = this.buildingHandles[metaBuilding.getId()]; handle.puzzleLocked = !handle.puzzleLocked; handle.element.classList.toggle("unlocked", !handle.puzzleLocked); this.root.soundProxy.playUiClick(); - const entityManager: any = this.root.entityMgr; - for (const entity: any of entityManager.getAllWithComponent(StaticMapEntityComponent)) { - const staticComp: any = entity.components.StaticMapEntity; + const entityManager = this.root.entityMgr; + for (const entity of entityManager.getAllWithComponent(StaticMapEntityComponent)) { + const staticComp = entity.components.StaticMapEntity; if (staticComp.getMetaBuilding().id === metaBuilding.id) { this.root.map.removeStaticEntity(entity); entityManager.destroyEntity(entity); } } entityManager.processDestroyList(); - const currentMetaBuilding: any = this.root.hud.parts.buildingPlacer.currentMetaBuilding; + const currentMetaBuilding = this.root.hud.parts.buildingPlacer.currentMetaBuilding; if (currentMetaBuilding.get() == metaBuilding) { currentMetaBuilding.set(null); } } - inRequiredBuildings(metaBuilding: MetaBuilding): any { - const requiredBuildings: any = [ + inRequiredBuildings(metaBuilding: MetaBuilding) { + const requiredBuildings = [ gMetaBuildingRegistry.findByClass(MetaConstantProducerBuilding), gMetaBuildingRegistry.findByClass(MetaGoalAcceptorBuilding), gMetaBuildingRegistry.findByClass(MetaBlockBuilding), diff --git a/src/ts/game/hud/parts/beta_overlay.ts b/src/ts/game/hud/parts/beta_overlay.ts index e0594a7b..b0a6e87f 100644 --- a/src/ts/game/hud/parts/beta_overlay.ts +++ b/src/ts/game/hud/parts/beta_overlay.ts @@ -1,8 +1,8 @@ import { BaseHUDPart } from "../base_hud_part"; import { makeDiv } from "../../../core/utils"; export class HUDBetaOverlay extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_BetaOverlay", [], "

UNSTABLE BETA VERSION

Unfinalized & potential buggy content!"); } - initialize(): any { } + initialize() { } } diff --git a/src/ts/game/hud/parts/blueprint_placer.ts b/src/ts/game/hud/parts/blueprint_placer.ts index 16a3310e..3f86b9cd 100644 --- a/src/ts/game/hud/parts/blueprint_placer.ts +++ b/src/ts/game/hud/parts/blueprint_placer.ts @@ -11,20 +11,20 @@ import { KEYMAPPINGS } from "../../key_action_mapper"; import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; export class HUDBlueprintPlacer extends BaseHUDPart { - createElements(parent: any): any { - const blueprintCostShape: any = this.root.shapeDefinitionMgr.getShapeFromShortKey(this.root.gameMode.getBlueprintShapeKey()); - const blueprintCostShapeCanvas: any = blueprintCostShape.generateAsCanvas(80); + createElements(parent) { + const blueprintCostShape = this.root.shapeDefinitionMgr.getShapeFromShortKey(this.root.gameMode.getBlueprintShapeKey()); + const blueprintCostShapeCanvas = blueprintCostShape.generateAsCanvas(80); this.costDisplayParent = makeDiv(parent, "ingame_HUD_BlueprintPlacer", [], ``); makeDiv(this.costDisplayParent, null, ["label"], T.ingame.blueprintPlacer.cost); - const costContainer: any = makeDiv(this.costDisplayParent, null, ["costContainer"], ""); + const costContainer = makeDiv(this.costDisplayParent, null, ["costContainer"], ""); this.costDisplayText = makeDiv(costContainer, null, ["costText"], ""); costContainer.appendChild(blueprintCostShapeCanvas); } - initialize(): any { + initialize() { this.root.hud.signals.buildingsSelectedForCopy.add(this.createBlueprintFromBuildings, this); this.currentBlueprint = new TrackedState(this.onBlueprintChanged, this); this.lastBlueprintUsed = null; - const keyActionMapper: any = this.root.keyMapper; + const keyActionMapper = this.root.keyMapper; keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.abortPlacement, this); keyActionMapper.getBinding(KEYMAPPINGS.placement.pipette).add(this.abortPlacement, this); keyActionMapper.getBinding(KEYMAPPINGS.placement.rotateWhilePlacing).add(this.rotateBlueprint, this); @@ -36,10 +36,10 @@ export class HUDBlueprintPlacer extends BaseHUDPart { this.domAttach = new DynamicDomAttach(this.root, this.costDisplayParent); this.trackedCanAfford = new TrackedState(this.onCanAffordChanged, this); } - getHasFreeCopyPaste(): any { + getHasFreeCopyPaste() { return this.root.gameMode.getHasFreeCopyPaste(); } - abortPlacement(): any { + abortPlacement() { if (this.currentBlueprint.get()) { this.currentBlueprint.set(null); return STOP_PROPAGATION; @@ -48,9 +48,9 @@ export class HUDBlueprintPlacer extends BaseHUDPart { /** * Called when the layer was changed */ - onEditModeChanged(layer: Layer): any { + onEditModeChanged(layer: Layer) { // Check if the layer of the blueprint differs and thus we have to deselect it - const blueprint: any = this.currentBlueprint.get(); + const blueprint = this.currentBlueprint.get(); if (blueprint) { if (blueprint.layer !== layer) { this.currentBlueprint.set(null); @@ -60,18 +60,18 @@ export class HUDBlueprintPlacer extends BaseHUDPart { /** * Called when the blueprint is now affordable or not */ - onCanAffordChanged(canAfford: boolean): any { + onCanAffordChanged(canAfford: boolean) { this.costDisplayParent.classList.toggle("canAfford", canAfford); } - update(): any { - const currentBlueprint: any = this.currentBlueprint.get(); + update() { + const currentBlueprint = this.currentBlueprint.get(); this.domAttach.update(!this.getHasFreeCopyPaste() && currentBlueprint && currentBlueprint.getCost() > 0); this.trackedCanAfford.set(currentBlueprint && currentBlueprint.canAfford(this.root)); } /** * Called when the blueprint was changed */ - onBlueprintChanged(blueprint: Blueprint): any { + onBlueprintChanged(blueprint: Blueprint) { if (blueprint) { this.lastBlueprintUsed = blueprint; this.costDisplayText.innerText = "" + blueprint.getCost(); @@ -80,7 +80,7 @@ export class HUDBlueprintPlacer extends BaseHUDPart { /** * mouse down pre handler */ - onMouseDown(pos: Vector, button: enumMouseButton): any { + onMouseDown(pos: Vector, button: enumMouseButton) { if (button === enumMouseButton.right) { if (this.currentBlueprint.get()) { this.abortPlacement(); @@ -88,7 +88,7 @@ export class HUDBlueprintPlacer extends BaseHUDPart { } } else if (button === enumMouseButton.left) { - const blueprint: any = this.currentBlueprint.get(); + const blueprint = this.currentBlueprint.get(); if (!blueprint) { return; } @@ -96,11 +96,11 @@ export class HUDBlueprintPlacer extends BaseHUDPart { this.root.soundProxy.playUiError(); return; } - const worldPos: any = this.root.camera.screenToWorld(pos); - const tile: any = worldPos.toTileSpace(); + const worldPos = this.root.camera.screenToWorld(pos); + const tile = worldPos.toTileSpace(); if (blueprint.tryPlace(this.root, tile)) { if (!this.getHasFreeCopyPaste()) { - const cost: any = blueprint.getCost(); + const cost = blueprint.getCost(); this.root.hubGoals.takeShapeByKey(this.root.gameMode.getBlueprintShapeKey(), cost); } this.root.soundProxy.playUi(SOUNDS.placeBuilding); @@ -111,7 +111,7 @@ export class HUDBlueprintPlacer extends BaseHUDPart { /** * Mouse move handler */ - onMouseMove(): any { + onMouseMove() { // Prevent movement while blueprint is selected if (this.currentBlueprint.get()) { return STOP_PROPAGATION; @@ -120,7 +120,7 @@ export class HUDBlueprintPlacer extends BaseHUDPart { /** * Called when an array of bulidings was selected */ - createBlueprintFromBuildings(uids: Array): any { + createBlueprintFromBuildings(uids: Array) { if (uids.length === 0) { return; } @@ -129,7 +129,7 @@ export class HUDBlueprintPlacer extends BaseHUDPart { /** * Attempts to rotate the current blueprint */ - rotateBlueprint(): any { + rotateBlueprint() { if (this.currentBlueprint.get()) { if (this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateInverseModifier).pressed) { this.currentBlueprint.get().rotateCcw(); @@ -142,7 +142,7 @@ export class HUDBlueprintPlacer extends BaseHUDPart { /** * Attempts to paste the last blueprint */ - pasteBlueprint(): any { + pasteBlueprint() { if (this.lastBlueprintUsed !== null) { if (this.lastBlueprintUsed.layer !== this.root.currentLayer) { // Not compatible @@ -156,18 +156,18 @@ export class HUDBlueprintPlacer extends BaseHUDPart { this.root.soundProxy.playUiError(); } } - draw(parameters: DrawParameters): any { - const blueprint: any = this.currentBlueprint.get(); + draw(parameters: DrawParameters) { + const blueprint = this.currentBlueprint.get(); if (!blueprint) { return; } - const mousePosition: any = this.root.app.mousePosition; + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return; } - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const tile: any = worldPos.toTileSpace(); + const worldPos = this.root.camera.screenToWorld(mousePosition); + const tile = worldPos.toTileSpace(); blueprint.draw(parameters, tile); } } diff --git a/src/ts/game/hud/parts/building_placer.ts b/src/ts/game/hud/parts/building_placer.ts index 756bbc29..5849e137 100644 --- a/src/ts/game/hud/parts/building_placer.ts +++ b/src/ts/game/hud/parts/building_placer.ts @@ -15,7 +15,7 @@ import { makeOffscreenBuffer } from "../../../core/buffer_utils"; import { layers } from "../../root"; import { getCodeFromBuildingData } from "../../building_codes"; export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { - createElements(parent: HTMLElement): any { + createElements(parent: HTMLElement) { this.element = makeDiv(parent, "ingame_HUD_PlacementHints", [], ``); this.buildingInfoElements = {}; this.buildingInfoElements.label = makeDiv(this.element, null, ["buildingLabel"], "Extract"); @@ -25,11 +25,11 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { this.buildingInfoElements.hotkey = makeDiv(this.buildingInfoElements.desc, null, ["hotkey"], ""); this.buildingInfoElements.tutorialImage = makeDiv(this.element, null, ["buildingImage"]); this.variantsElement = makeDiv(parent, "ingame_HUD_PlacerVariants"); - const compact: any = this.root.app.settings.getAllSettings().compactBuildingInfo; + const compact = this.root.app.settings.getAllSettings().compactBuildingInfo; this.element.classList.toggle("compact", compact); this.variantsElement.classList.toggle("compact", compact); } - initialize(): any { + initialize() { super.initialize(); // Bind to signals this.signals.variantChanged.add(this.rerenderVariants, this); @@ -38,7 +38,7 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { this.variantsAttach = new DynamicDomAttach(this.root, this.variantsElement, {}); this.currentInterpolatedCornerTile = new Vector(); this.lockIndicatorSprites = {}; - [...layers, "error"].forEach((layer: any): any => { + [...layers, "error"].forEach(layer => { this.lockIndicatorSprites[layer] = this.makeLockIndicatorSprite(layer); }); // @@ -50,9 +50,9 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { /** * Makes the lock indicator sprite for the given layer */ - makeLockIndicatorSprite(layer: string): any { - const dims: any = 48; - const [canvas, context]: any = makeOffscreenBuffer(dims, dims, { + makeLockIndicatorSprite(layer: string) { + const dims = 48; + const [canvas, context] = makeOffscreenBuffer(dims, dims, { smooth: true, reusable: false, label: "lock-direction-indicator", @@ -60,9 +60,9 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { context.fillStyle = THEME.map.directionLock[layer].color; context.strokeStyle = THEME.map.directionLock[layer].color; context.lineWidth = 2; - const padding: any = 5; - const height: any = dims * 0.5; - const bottom: any = (dims + height) / 2; + const padding = 5; + const height = dims * 0.5; + const bottom = (dims + height) / 2; context.moveTo(padding, bottom); context.lineTo(dims / 2, bottom - height); context.lineTo(dims - padding, bottom); @@ -74,21 +74,21 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { /** * Rerenders the building info dialog */ - rerenderInfoDialog(): any { - const metaBuilding: any = this.currentMetaBuilding.get(); + rerenderInfoDialog() { + const metaBuilding = this.currentMetaBuilding.get(); if (!metaBuilding) { return; } - const variant: any = this.currentVariant.get(); + const variant = this.currentVariant.get(); this.buildingInfoElements.label.innerHTML = T.buildings[metaBuilding.id][variant].name; this.buildingInfoElements.descText.innerHTML = T.buildings[metaBuilding.id][variant].description; - const layer: any = this.root.currentLayer; - let rawBinding: any = KEYMAPPINGS.buildings[metaBuilding.getId() + "_" + layer]; + const layer = this.root.currentLayer; + let rawBinding = KEYMAPPINGS.buildings[metaBuilding.getId() + "_" + layer]; if (!rawBinding) { rawBinding = KEYMAPPINGS.buildings[metaBuilding.getId()]; } if (rawBinding) { - const binding: any = this.root.keyMapper.getBinding(rawBinding); + const binding = this.root.keyMapper.getBinding(rawBinding); this.buildingInfoElements.hotkey.innerHTML = T.ingame.buildingPlacement.hotkeyLabel.replace("", "" + binding.getKeyCodeString() + ""); } else { @@ -99,25 +99,25 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { (variant === defaultBuildingVariant ? "" : "-" + variant) + ".png"); removeAllChildren(this.buildingInfoElements.additionalInfo); - const additionalInfo: any = metaBuilding.getAdditionalStatistics(this.root, this.currentVariant.get()); - for (let i: any = 0; i < additionalInfo.length; ++i) { - const [label, contents]: any = additionalInfo[i]; + const additionalInfo = metaBuilding.getAdditionalStatistics(this.root, this.currentVariant.get()); + for (let i = 0; i < additionalInfo.length; ++i) { + const [label, contents] = additionalInfo[i]; this.buildingInfoElements.additionalInfo.innerHTML += ` ${contents} `; } } - cleanup(): any { + cleanup() { super.cleanup(); this.cleanupVariantClickDetectors(); } /** * Cleans up all variant click detectors */ - cleanupVariantClickDetectors(): any { - for (let i: any = 0; i < this.variantClickDetectors.length; ++i) { - const detector: any = this.variantClickDetectors[i]; + cleanupVariantClickDetectors() { + for (let i = 0; i < this.variantClickDetectors.length; ++i) { + const detector = this.variantClickDetectors[i]; detector.cleanup(); } this.variantClickDetectors = []; @@ -125,16 +125,16 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { /** * Rerenders the variants displayed */ - rerenderVariants(): any { + rerenderVariants() { removeAllChildren(this.variantsElement); this.rerenderInfoDialog(); - const metaBuilding: any = this.currentMetaBuilding.get(); + const metaBuilding = this.currentMetaBuilding.get(); // First, clear up all click detectors this.cleanupVariantClickDetectors(); if (!metaBuilding) { return; } - const availableVariants: any = metaBuilding.getAvailableVariants(this.root); + const availableVariants = metaBuilding.getAvailableVariants(this.root); if (availableVariants.length === 1) { return; } @@ -143,27 +143,27 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { .getBinding(KEYMAPPINGS.placement.cycleBuildingVariants) .getKeyCodeString() + "")); - const container: any = makeDiv(this.variantsElement, null, ["variants"]); - for (let i: any = 0; i < availableVariants.length; ++i) { - const variant: any = availableVariants[i]; - const element: any = makeDiv(container, null, ["variant"]); + const container = makeDiv(this.variantsElement, null, ["variants"]); + for (let i = 0; i < availableVariants.length; ++i) { + const variant = availableVariants[i]; + const element = makeDiv(container, null, ["variant"]); element.classList.toggle("active", variant === this.currentVariant.get()); makeDiv(element, null, ["label"], variant); - const iconSize: any = 64; - const dimensions: any = metaBuilding.getDimensions(variant); - const sprite: any = metaBuilding.getPreviewSprite(0, variant); - const spriteWrapper: any = makeDiv(element, null, ["iconWrap"]); + const iconSize = 64; + const dimensions = metaBuilding.getDimensions(variant); + const sprite = metaBuilding.getPreviewSprite(0, variant); + const spriteWrapper = makeDiv(element, null, ["iconWrap"]); spriteWrapper.setAttribute("data-tile-w", String(dimensions.x)); spriteWrapper.setAttribute("data-tile-h", String(dimensions.y)); spriteWrapper.innerHTML = sprite.getAsHTML(iconSize * dimensions.x, iconSize * dimensions.y); - const detector: any = new ClickDetector(element, { + const detector = new ClickDetector(element, { consumeEvents: true, targetOnly: true, }); - detector.click.add((): any => this.setVariant(variant)); + detector.click.add(() => this.setVariant(variant)); } } - draw(parameters: DrawParameters): any { + draw(parameters: DrawParameters) { if (this.root.camera.getIsMapOverlayActive()) { // Dont allow placing in overview mode this.domAttach.update(false); @@ -172,7 +172,7 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { } this.domAttach.update(!!this.currentMetaBuilding.get()); this.variantsAttach.update(!!this.currentMetaBuilding.get()); - const metaBuilding: any = this.currentMetaBuilding.get(); + const metaBuilding = this.currentMetaBuilding.get(); if (!metaBuilding) { return; } @@ -187,29 +187,29 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { this.drawLayerPeek(parameters); } } - drawLayerPeek(parameters: DrawParameters): any { - const mousePosition: any = this.root.app.mousePosition; + drawLayerPeek(parameters: DrawParameters) { + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return; } - const worldPosition: any = this.root.camera.screenToWorld(mousePosition); + const worldPosition = this.root.camera.screenToWorld(mousePosition); // Draw peeker if (this.root.hud.parts.layerPreview) { this.root.hud.parts.layerPreview.renderPreview(parameters, worldPosition, 1 / this.root.camera.zoomLevel); } } - drawRegularPlacement(parameters: DrawParameters): any { - const mousePosition: any = this.root.app.mousePosition; + drawRegularPlacement(parameters: DrawParameters) { + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return; } - const metaBuilding: any = this.currentMetaBuilding.get(); - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const mouseTile: any = worldPos.toTileSpace(); + const metaBuilding = this.currentMetaBuilding.get(); + const worldPos = this.root.camera.screenToWorld(mousePosition); + const mouseTile = worldPos.toTileSpace(); // Compute best rotation variant - const { rotation, rotationVariant, connectedEntities, }: any = metaBuilding.computeOptimalDirectionAndRotationVariantAtTile({ + const { rotation, rotationVariant, connectedEntities, } = metaBuilding.computeOptimalDirectionAndRotationVariantAtTile({ root: this.root, tile: mouseTile, rotation: this.currentBaseRotation, @@ -218,18 +218,18 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { }); // Check if there are connected entities if (connectedEntities) { - for (let i: any = 0; i < connectedEntities.length; ++i) { - const connectedEntity: any = connectedEntities[i]; - const connectedWsPoint: any = connectedEntity.components.StaticMapEntity.getTileSpaceBounds() + for (let i = 0; i < connectedEntities.length; ++i) { + const connectedEntity = connectedEntities[i]; + const connectedWsPoint = connectedEntity.components.StaticMapEntity.getTileSpaceBounds() .getCenter() .toWorldSpace(); - const startWsPoint: any = mouseTile.toWorldSpaceCenterOfTile(); - const startOffset: any = connectedWsPoint + const startWsPoint = mouseTile.toWorldSpaceCenterOfTile(); + const startOffset = connectedWsPoint .sub(startWsPoint) .normalize() .multiplyScalar(globalConfig.tileSize * 0.3); - const effectiveStartPoint: any = startWsPoint.add(startOffset); - const effectiveEndPoint: any = connectedWsPoint.sub(startOffset); + const effectiveStartPoint = startWsPoint.add(startOffset); + const effectiveEndPoint = connectedWsPoint.sub(startOffset); parameters.context.globalAlpha = 0.6; // parameters.context.lineCap = "round"; parameters.context.strokeStyle = "#7f7"; @@ -244,17 +244,17 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { } // Synchronize rotation and origin this.fakeEntity.layer = metaBuilding.getLayer(); - const staticComp: any = this.fakeEntity.components.StaticMapEntity; + const staticComp = this.fakeEntity.components.StaticMapEntity; staticComp.origin = mouseTile; staticComp.rotation = rotation; metaBuilding.updateVariants(this.fakeEntity, rotationVariant, this.currentVariant.get()); staticComp.code = getCodeFromBuildingData(this.currentMetaBuilding.get(), this.currentVariant.get(), rotationVariant); - const canBuild: any = this.root.logic.checkCanPlaceEntity(this.fakeEntity, {}); + const canBuild = this.root.logic.checkCanPlaceEntity(this.fakeEntity, {}); // Fade in / out parameters.context.lineWidth = 1; // Determine the bounds and visualize them - const entityBounds: any = staticComp.getTileSpaceBounds(); - const drawBorder: any = -3; + const entityBounds = staticComp.getTileSpaceBounds(); + const drawBorder = -3; if (canBuild) { parameters.context.strokeStyle = "rgba(56, 235, 111, 0.5)"; parameters.context.fillStyle = "rgba(56, 235, 111, 0.2)"; @@ -268,7 +268,7 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { // parameters.context.fill(); parameters.context.globalAlpha = 1; // HACK to draw the entity sprite - const previewSprite: any = metaBuilding.getBlueprintSprite(rotationVariant, this.currentVariant.get()); + const previewSprite = metaBuilding.getBlueprintSprite(rotationVariant, this.currentVariant.get()); staticComp.origin = worldPos.divideScalar(globalConfig.tileSize).subScalars(0.5, 0.5); staticComp.drawSpriteOnBoundsClipped(parameters, previewSprite); staticComp.origin = mouseTile; @@ -573,8 +573,8 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { * @param {Vector[]=} ignorePositions * @returns */ - checkForObstales(from: Vector, to: V ignorePositions: Vecto []): any { - om.x === to.x || from.y === /** + checkForObstales(from: Vector, to: V ignorePositions: Vecto []) { + asser=== to.x || from.y === to.y /** * Checks if there are any entities in the way, returns true if there are * @ /** * Checks if there are any entities in the way, returns true if there are @@ -665,22 +665,22 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { * @param {Vector[]=} ignorePositions * @returns */ - checkForObstales(from: Vector, to: Vector, ignorePositions: Vector[]= = []): any { + checkForObstales(from: Vector, to: Vector, ignorePositions: Vector[]= = []) { assert(from.x === to.x || from.y === to.y, "Must be a straight line"); - const prop: any = from.x === to.x ? "y" : "x"; - const current: any = from.copy(); - const metaBuilding: any = this.currentMetaBuilding.get(); + const prop = from.x === to.x ? "y" : "x"; + const current = from.copy(); + const metaBuilding = this.currentMetaBuilding.get(); this.fakeEntity.layer = metaBuilding.getLayer(); - const staticComp: any = this.fakeEntity.components.StaticMapEntity; + const staticComp = this.fakeEntity.components.StaticMapEntity; staticComp.origin = current; staticComp.rotation = 0; metaBuilding.updateVariants(this.fakeEntity, 0, this.currentVariant.get()); staticComp.code = getCodeFromBuildingData(this.currentMetaBuilding.get(), this.currentVariant.get(), 0); - const start: any = Math.min(from[prop], to[prop]); - const end: any = Math.max(from[prop], to[prop]); - for (let i: any = start; i <= end; i++) { + const start = Math.min(from[prop], to[prop]); + const end = Math.max(from[prop], to[prop]); + for (let i = start; i <= end; i++) { current[prop] = i; - if (ignorePositions.some((p: any): any => p.distanceSquare(current) < 0.1)) { + if (ignorePositions.some(p => p.distanceSquare(current) < 0.1)) { continue; } if (!this.root.logic.checkCanPlaceEntity(this.fakeEntity, { allowReplaceBuildings: false })) { @@ -689,13 +689,13 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { } return false; } - drawDirectionLock(parameters: DrawParameters): any { - const mousePosition: any = this.root.app.mousePosition; + drawDirectionLock(parameters: DrawParameters) { + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return; } - const applyStyles: any = (look: any): any => { + const applyStyles = look => { parameters.context.fillStyle = THEME.map.directionLock[look].color; parameters.context.strokeStyle = THEME.map.directionLock[look].background; parameters.context.lineWidth = 10; @@ -703,17 +703,17 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { if (!this.lastDragTile) { // Not dragging yet applyStyles(this.root.currentLayer); - const mouseWorld: any = this.root.camera.screenToWorld(mousePosition); + const mouseWorld = this.root.camera.screenToWorld(mousePosition); parameters.context.beginCircle(mouseWorld.x, mouseWorld.y, 4); parameters.context.fill(); return; } - const mouseWorld: any = this.root.camera.screenToWorld(mousePosition); - const mouseTile: any = mouseWorld.toTileSpace(); - const startLine: any = this.lastDragTile.toWorldSpaceCenterOfTile(); - const endLine: any = mouseTile.toWorldSpaceCenterOfTile(); - const midLine: any = this.currentDirectionLockCorner.toWorldSpaceCenterOfTile(); - const anyObstacle: any = this.checkForObstales(this.lastDragTile, this.currentDirectionLockCorner, [ + const mouseWorld = this.root.camera.screenToWorld(mousePosition); + const mouseTile = mouseWorld.toTileSpace(); + const startLine = this.lastDragTile.toWorldSpaceCenterOfTile(); + const endLine = mouseTile.toWorldSpaceCenterOfTile(); + const midLine = this.currentDirectionLockCorner.toWorldSpaceCenterOfTile(); + const anyObstacle = this.checkForObstales(this.lastDragTile, this.currentDirectionLockCorner, [ this.lastDragTile, mouseTile, ]) || @@ -736,12 +736,12 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { parameters.context.beginCircle(endLine.x, endLine.y, 5); parameters.context.fill(); // Draw arrow - const arrowSprite: any = this.lockIndicatorSprites[anyObstacle ? "error" : this.root.currentLayer]; - const path: any = this.computeDirectionLockPath(); - for (let i: any = 0; i < path.length - 1; i += 1) { - const { rotation, tile }: any = path[i]; - const worldPos: any = tile.toWorldSpaceCenterOfTile(); - const angle: any = Math.radians(rotation); + const arrowSprite = this.lockIndicatorSprites[anyObstacle ? "error" : this.root.currentLayer]; + const path = this.computeDirectionLockPath(); + for (let i = 0; i < path.length - 1; i += 1) { + const { rotation, tile } = path[i]; + const worldPos = tile.toWorldSpaceCenterOfTile(); + const angle = Math.radians(rotation); parameters.context.translate(worldPos.x, worldPos.y); parameters.context.rotate(angle); parameters.context.drawImage(arrowSprite, -6, -globalConfig.halfTileSize - @@ -752,16 +752,16 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { parameters.context.translate(-worldPos.x, -worldPos.y); } } - drawMatchingAcceptorsAndEjectors(parameters: DrawParameters): any { - const acceptorComp: any = this.fakeEntity.components.ItemAcceptor; - const ejectorComp: any = this.fakeEntity.components.ItemEjector; - const staticComp: any = this.fakeEntity.components.StaticMapEntity; - const beltComp: any = this.fakeEntity.components.Belt; - const minerComp: any = this.fakeEntity.components.Miner; - const goodArrowSprite: any = Loader.getSprite("sprites/misc/slot_good_arrow.png"); - const badArrowSprite: any = Loader.getSprite("sprites/misc/slot_bad_arrow.png"); + drawMatchingAcceptorsAndEjectors(parameters: DrawParameters) { + const acceptorComp = this.fakeEntity.components.ItemAcceptor; + const ejectorComp = this.fakeEntity.components.ItemEjector; + const staticComp = this.fakeEntity.components.StaticMapEntity; + const beltComp = this.fakeEntity.components.Belt; + const minerComp = this.fakeEntity.components.Miner; + const goodArrowSprite = Loader.getSprite("sprites/misc/slot_good_arrow.png"); + const badArrowSprite = Loader.getSprite("sprites/misc/slot_bad_arrow.png"); // Just ignore the following code please ... thanks! - const offsetShift: any = 10; + const offsetShift = 10; let acceptorSlots: Array = []; let ejectorSlots: Array = []; if (ejectorComp) { @@ -771,31 +771,31 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { acceptorSlots = acceptorComp.slots.slice(); } if (beltComp) { - const fakeEjectorSlot: any = beltComp.getFakeEjectorSlot(); - const fakeAcceptorSlot: any = beltComp.getFakeAcceptorSlot(); + const fakeEjectorSlot = beltComp.getFakeEjectorSlot(); + const fakeAcceptorSlot = beltComp.getFakeAcceptorSlot(); ejectorSlots.push(fakeEjectorSlot); acceptorSlots.push(fakeAcceptorSlot); } // Go over all slots - for (let i: any = 0; i < acceptorSlots.length; ++i) { - const slot: any = acceptorSlots[i]; - const acceptorSlotWsTile: any = staticComp.localTileToWorld(slot.pos); - const acceptorSlotWsPos: any = acceptorSlotWsTile.toWorldSpaceCenterOfTile(); - const direction: any = slot.direction; - const worldDirection: any = staticComp.localDirectionToWorld(direction); + for (let i = 0; i < acceptorSlots.length; ++i) { + const slot = acceptorSlots[i]; + const acceptorSlotWsTile = staticComp.localTileToWorld(slot.pos); + const acceptorSlotWsPos = acceptorSlotWsTile.toWorldSpaceCenterOfTile(); + const direction = slot.direction; + const worldDirection = staticComp.localDirectionToWorld(direction); // Figure out which tile ejects to this slot - const sourceTile: any = acceptorSlotWsTile.add(enumDirectionToVector[worldDirection]); - let isBlocked: any = false; - let isConnected: any = false; + const sourceTile = acceptorSlotWsTile.add(enumDirectionToVector[worldDirection]); + let isBlocked = false; + let isConnected = false; // Find all entities which are on that tile - const sourceEntities: any = this.root.map.getLayersContentsMultipleXY(sourceTile.x, sourceTile.y); + const sourceEntities = this.root.map.getLayersContentsMultipleXY(sourceTile.x, sourceTile.y); // Check for every entity: - for (let j: any = 0; j < sourceEntities.length; ++j) { - const sourceEntity: any = sourceEntities[j]; - const sourceEjector: any = sourceEntity.components.ItemEjector; - const sourceBeltComp: any = sourceEntity.components.Belt; - const sourceStaticComp: any = sourceEntity.components.StaticMapEntity; - const ejectorAcceptLocalTile: any = sourceStaticComp.worldToLocalTile(acceptorSlotWsTile); + for (let j = 0; j < sourceEntities.length; ++j) { + const sourceEntity = sourceEntities[j]; + const sourceEjector = sourceEntity.components.ItemEjector; + const sourceBeltComp = sourceEntity.components.Belt; + const sourceStaticComp = sourceEntity.components.StaticMapEntity; + const ejectorAcceptLocalTile = sourceStaticComp.worldToLocalTile(acceptorSlotWsTile); // If this entity is on the same layer as the slot - if so, it can either be // connected, or it can not be connected and thus block the input if (sourceEjector && sourceEjector.anySlotEjectsToLocalTile(ejectorAcceptLocalTile)) { @@ -813,8 +813,8 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { isBlocked = true; } } - const alpha: any = isConnected || isBlocked ? 1.0 : 0.3; - const sprite: any = isBlocked ? badArrowSprite : goodArrowSprite; + const alpha = isConnected || isBlocked ? 1.0 : 0.3; + const sprite = isBlocked ? badArrowSprite : goodArrowSprite; parameters.context.globalAlpha = alpha; drawRotatedSprite({ parameters, @@ -828,24 +828,24 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { parameters.context.globalAlpha = 1; } // Go over all slots - for (let ejectorSlotIndex: any = 0; ejectorSlotIndex < ejectorSlots.length; ++ejectorSlotIndex) { - const slot: any = ejectorSlots[ejectorSlotIndex]; - const ejectorSlotLocalTile: any = slot.pos.add(enumDirectionToVector[slot.direction]); - const ejectorSlotWsTile: any = staticComp.localTileToWorld(ejectorSlotLocalTile); - const ejectorSLotWsPos: any = ejectorSlotWsTile.toWorldSpaceCenterOfTile(); - const ejectorSlotWsDirection: any = staticComp.localDirectionToWorld(slot.direction); - let isBlocked: any = false; - let isConnected: any = false; + for (let ejectorSlotIndex = 0; ejectorSlotIndex < ejectorSlots.length; ++ejectorSlotIndex) { + const slot = ejectorSlots[ejectorSlotIndex]; + const ejectorSlotLocalTile = slot.pos.add(enumDirectionToVector[slot.direction]); + const ejectorSlotWsTile = staticComp.localTileToWorld(ejectorSlotLocalTile); + const ejectorSLotWsPos = ejectorSlotWsTile.toWorldSpaceCenterOfTile(); + const ejectorSlotWsDirection = staticComp.localDirectionToWorld(slot.direction); + let isBlocked = false; + let isConnected = false; // Find all entities which are on that tile - const destEntities: any = this.root.map.getLayersContentsMultipleXY(ejectorSlotWsTile.x, ejectorSlotWsTile.y); + const destEntities = this.root.map.getLayersContentsMultipleXY(ejectorSlotWsTile.x, ejectorSlotWsTile.y); // Check for every entity: - for (let i: any = 0; i < destEntities.length; ++i) { - const destEntity: any = destEntities[i]; - const destAcceptor: any = destEntity.components.ItemAcceptor; - const destStaticComp: any = destEntity.components.StaticMapEntity; - const destMiner: any = destEntity.components.Miner; - const destLocalTile: any = destStaticComp.worldToLocalTile(ejectorSlotWsTile); - const destLocalDir: any = destStaticComp.worldDirectionToLocal(ejectorSlotWsDirection); + for (let i = 0; i < destEntities.length; ++i) { + const destEntity = destEntities[i]; + const destAcceptor = destEntity.components.ItemAcceptor; + const destStaticComp = destEntity.components.StaticMapEntity; + const destMiner = destEntity.components.Miner; + const destLocalTile = destStaticComp.worldToLocalTile(ejectorSlotWsTile); + const destLocalDir = destStaticComp.worldDirectionToLocal(ejectorSlotWsDirection); if (destAcceptor && destAcceptor.findMatchingSlot(destLocalTile, destLocalDir)) { // This one is connected, all good isConnected = true; @@ -863,8 +863,8 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic { isBlocked = true; } } - const alpha: any = isConnected || isBlocked ? 1.0 : 0.3; - const sprite: any = isBlocked ? badArrowSprite : goodArrowSprite; + const alpha = isConnected || isBlocked ? 1.0 : 0.3; + const sprite = isBlocked ? badArrowSprite : goodArrowSprite; parameters.context.globalAlpha = alpha; drawRotatedSprite({ parameters, diff --git a/src/ts/game/hud/parts/building_placer_logic.ts b/src/ts/game/hud/parts/building_placer_logic.ts index c09dc4a0..e1cf4dd0 100644 --- a/src/ts/game/hud/parts/building_placer_logic.ts +++ b/src/ts/game/hud/parts/building_placer_logic.ts @@ -24,7 +24,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { * Initializes the logic * @see BaseHUDPart.initialize */ - initialize(): any { + initialize() { /** * We use a fake entity to get information about how a building will look * once placed @@ -55,7 +55,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Current building variant */ - this.currentVariant = new TrackedState((): any => this.signals.variantChanged.dispatch()); + this.currentVariant = new TrackedState(() => this.signals.variantChanged.dispatch()); /** * Whether we are currently drag-deleting */ @@ -83,9 +83,9 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Initializes all bindings */ - initializeBindings(): any { + initializeBindings() { // KEYBINDINGS - const keyActionMapper: any = this.root.keyMapper; + const keyActionMapper = this.root.keyMapper; keyActionMapper.getBinding(KEYMAPPINGS.placement.rotateWhilePlacing).add(this.tryRotate, this); keyActionMapper.getBinding(KEYMAPPINGS.placement.rotateToUp).add(this.trySetRotate, this); keyActionMapper.getBinding(KEYMAPPINGS.placement.rotateToDown).add(this.trySetRotate, this); @@ -101,8 +101,8 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { // BINDINGS TO GAME EVENTS this.root.hud.signals.buildingsSelectedForCopy.add(this.abortPlacement, this); this.root.hud.signals.pasteBlueprintRequested.add(this.abortPlacement, this); - this.root.signals.storyGoalCompleted.add((): any => this.signals.variantChanged.dispatch()); - this.root.signals.upgradePurchased.add((): any => this.signals.variantChanged.dispatch()); + this.root.signals.storyGoalCompleted.add(() => this.signals.variantChanged.dispatch()); + this.root.signals.upgradePurchased.add(() => this.signals.variantChanged.dispatch()); this.root.signals.editModeChanged.add(this.onEditModeChanged, this); // MOUSE BINDINGS this.root.camera.downPreHandler.add(this.onMouseDown, this); @@ -112,8 +112,8 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Called when the edit mode got changed */ - onEditModeChanged(layer: Layer): any { - const metaBuilding: any = this.currentMetaBuilding.get(); + onEditModeChanged(layer: Layer) { + const metaBuilding = this.currentMetaBuilding.get(); if (metaBuilding) { if (metaBuilding.getLayer() !== layer) { // This layer doesn't fit the edit mode anymore @@ -129,7 +129,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { if (!this.root.app.settings.getAllSettings().rotationByBuilding) { return this.currentBaseRotationGeneral; } - const metaBuilding: any = this.currentMetaBuilding.get(); + const metaBuilding = this.currentMetaBuilding.get(); if (metaBuilding && this.preferredBaseRotations.hasOwnProperty(metaBuilding.getId())) { return this.preferredBaseRotations[metaBuilding.getId()]; } @@ -145,7 +145,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { this.currentBaseRotationGeneral = rotation; } else { - const metaBuilding: any = this.currentMetaBuilding.get(); + const metaBuilding = this.currentMetaBuilding.get(); if (metaBuilding) { this.preferredBaseRotations[metaBuilding.getId()] = rotation; } @@ -159,7 +159,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { * {} */ get isDirectionLockActive() { - const metaBuilding: any = this.currentMetaBuilding.get(); + const metaBuilding = this.currentMetaBuilding.get(); return (metaBuilding && metaBuilding.getHasDirectionLockAvailable(this.currentVariant.get()) && this.root.keyMapper.getBinding(KEYMAPPINGS.placementModifiers.lockBeltDirection).pressed); @@ -170,7 +170,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { * {} */ get currentDirectionLockCorner() { - const mousePosition: any = this.root.app.mousePosition; + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return null; @@ -180,11 +180,11 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { return null; } // Figure which points the line visits - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const mouseTile: any = worldPos.toTileSpace(); + const worldPos = this.root.camera.screenToWorld(mousePosition); + const mouseTile = worldPos.toTileSpace(); // Figure initial direction - const dx: any = Math.abs(this.lastDragTile.x - mouseTile.x); - const dy: any = Math.abs(this.lastDragTile.y - mouseTile.y); + const dx = Math.abs(this.lastDragTile.x - mouseTile.x); + const dy = Math.abs(this.lastDragTile.y - mouseTile.y); if (dx === 0 && dy === 0) { // Back at the start. Try a new direction. this.currentDirectionLockSideIndeterminate = true; @@ -203,7 +203,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Aborts the placement */ - abortPlacement(): any { + abortPlacement() { if (this.currentMetaBuilding.get()) { this.currentMetaBuilding.set(null); return STOP_PROPAGATION; @@ -212,7 +212,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Aborts any dragging */ - abortDragging(): any { + abortDragging() { this.currentlyDragging = true; this.currentlyDeleting = false; this.initialPlacementVector = null; @@ -221,14 +221,14 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * @see BaseHUDPart.update */ - update(): any { + update() { // Abort placement if a dialog was shown in the meantime if (this.root.hud.hasBlockingOverlayOpen()) { this.abortPlacement(); return; } // Always update since the camera might have moved - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (mousePos) { this.onMouseMove(mousePos); } @@ -242,8 +242,8 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Tries to rotate the current building */ - tryRotate(): any { - const selectedBuilding: any = this.currentMetaBuilding.get(); + tryRotate() { + const selectedBuilding = this.currentMetaBuilding.get(); if (selectedBuilding) { if (this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateInverseModifier).pressed) { this.currentBaseRotation = (this.currentBaseRotation + 270) % 360; @@ -251,15 +251,15 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { else { this.currentBaseRotation = (this.currentBaseRotation + 90) % 360; } - const staticComp: any = this.fakeEntity.components.StaticMapEntity; + const staticComp = this.fakeEntity.components.StaticMapEntity; staticComp.rotation = this.currentBaseRotation; } } /** * Rotates the current building to the specified direction. */ - trySetRotate(): any { - const selectedBuilding: any = this.currentMetaBuilding.get(); + trySetRotate() { + const selectedBuilding = this.currentMetaBuilding.get(); if (selectedBuilding) { if (this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateToUp).pressed) { this.currentBaseRotation = 0; @@ -273,22 +273,22 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { else if (this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateToLeft).pressed) { this.currentBaseRotation = 270; } - const staticComp: any = this.fakeEntity.components.StaticMapEntity; + const staticComp = this.fakeEntity.components.StaticMapEntity; staticComp.rotation = this.currentBaseRotation; } } /** * Tries to delete the building under the mouse */ - deleteBelowCursor(): any { - const mousePosition: any = this.root.app.mousePosition; + deleteBelowCursor() { + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return false; } - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const tile: any = worldPos.toTileSpace(); - const contents: any = this.root.map.getTileContent(tile, this.root.currentLayer); + const worldPos = this.root.camera.screenToWorld(mousePosition); + const tile = worldPos.toTileSpace(); + const contents = this.root.map.getTileContent(tile, this.root.currentLayer); if (contents) { if (this.root.logic.tryDeleteBuilding(contents)) { this.root.soundProxy.playUi(SOUNDS.destroyBuilding); @@ -300,21 +300,21 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Starts the pipette function */ - startPipette(): any { + startPipette() { // Disable in overview if (this.root.camera.getIsMapOverlayActive()) { return; } - const mousePosition: any = this.root.app.mousePosition; + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return; } - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const tile: any = worldPos.toTileSpace(); - const contents: any = this.root.map.getTileContent(tile, this.root.currentLayer); + const worldPos = this.root.camera.screenToWorld(mousePosition); + const tile = worldPos.toTileSpace(); + const contents = this.root.map.getTileContent(tile, this.root.currentLayer); if (!contents) { - const tileBelow: any = this.root.map.getLowerLayerContentXY(tile.x, tile.y); + const tileBelow = this.root.map.getLowerLayerContentXY(tile.x, tile.y); // Check if there's a shape or color item below, if so select the miner if (tileBelow && this.root.app.settings.getAllSettings().pickMinerOnPatch && @@ -332,8 +332,8 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { return; } // Try to extract the building - const buildingCode: any = contents.components.StaticMapEntity.code; - const extracted: any = getBuildingDataFromCode(buildingCode); + const buildingCode = contents.components.StaticMapEntity.code; + const extracted = getBuildingDataFromCode(buildingCode); // Disable pipetting the hub if (extracted.metaInstance.getId() === gMetaBuildingRegistry.findByClass(MetaHubBuilding).getId()) { this.currentMetaBuilding.set(null); @@ -358,13 +358,13 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Switches the side for the direction lock manually */ - switchDirectionLockSide(): any { + switchDirectionLockSide() { this.currentDirectionLockSide = 1 - this.currentDirectionLockSide; } /** * Checks if the direction lock key got released and if such, resets the placement */ - checkForDirectionLockSwitch({ keyCode }: any): any { + checkForDirectionLockSwitch({ keyCode }: any) { if (keyCode === this.root.keyMapper.getBinding(KEYMAPPINGS.placementModifiers.lockBeltDirection).keyCode) { this.abortDragging(); @@ -373,20 +373,20 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Tries to place the current building at the given tile */ - tryPlaceCurrentBuildingAt(tile: Vector): any { + tryPlaceCurrentBuildingAt(tile: Vector) { if (this.root.camera.getIsMapOverlayActive()) { // Dont allow placing in overview mode return; } - const metaBuilding: any = this.currentMetaBuilding.get(); - const { rotation, rotationVariant }: any = metaBuilding.computeOptimalDirectionAndRotationVariantAtTile({ + const metaBuilding = this.currentMetaBuilding.get(); + const { rotation, rotationVariant } = metaBuilding.computeOptimalDirectionAndRotationVariantAtTile({ root: this.root, tile, rotation: this.currentBaseRotation, variant: this.currentVariant.get(), layer: metaBuilding.getLayer(), }); - const entity: any = this.root.logic.tryPlaceBuilding({ + const entity = this.root.logic.tryPlaceBuilding({ origin: tile, rotation, rotationVariant, @@ -418,32 +418,32 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Cycles through the variants */ - cycleVariants(): any { - const metaBuilding: any = this.currentMetaBuilding.get(); + cycleVariants() { + const metaBuilding = this.currentMetaBuilding.get(); if (!metaBuilding) { this.currentVariant.set(defaultBuildingVariant); } else { - const availableVariants: any = metaBuilding.getAvailableVariants(this.root); - let index: any = availableVariants.indexOf(this.currentVariant.get()); + const availableVariants = metaBuilding.getAvailableVariants(this.root); + let index = availableVariants.indexOf(this.currentVariant.get()); if (index < 0) { index = 0; console.warn("Invalid variant selected:", this.currentVariant.get()); } - const direction: any = this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateInverseModifier) + const direction = this.root.keyMapper.getBinding(KEYMAPPINGS.placement.rotateInverseModifier) .pressed ? -1 : 1; - const newIndex: any = safeModulo(index + direction, availableVariants.length); - const newVariant: any = availableVariants[newIndex]; + const newIndex = safeModulo(index + direction, availableVariants.length); + const newVariant = availableVariants[newIndex]; this.setVariant(newVariant); } } /** * Sets the current variant to the given variant */ - setVariant(variant: string): any { - const metaBuilding: any = this.currentMetaBuilding.get(); + setVariant(variant: string) { + const metaBuilding = this.currentMetaBuilding.get(); this.currentVariant.set(variant); this.preferredVariants[metaBuilding.getId()] = variant; } @@ -451,20 +451,20 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { * Performs the direction locked placement between two points after * releasing the mouse */ - executeDirectionLockedPlacement(): any { - const metaBuilding: any = this.currentMetaBuilding.get(); + executeDirectionLockedPlacement() { + const metaBuilding = this.currentMetaBuilding.get(); if (!metaBuilding) { // No active building return; } // Get path to place - const path: any = this.computeDirectionLockPath(); + const path = this.computeDirectionLockPath(); // Store if we placed anything - let anythingPlaced: any = false; + let anythingPlaced = false; // Perform this in bulk to avoid recalculations - this.root.logic.performBulkOperation((): any => { - for (let i: any = 0; i < path.length; ++i) { - const { rotation, tile }: any = path[i]; + this.root.logic.performBulkOperation(() => { + for (let i = 0; i < path.length; ++i) { + const { rotation, tile } = path[i]; this.currentBaseRotation = rotation; if (this.tryPlaceCurrentBuildingAt(tile)) { anythingPlaced = true; @@ -483,30 +483,30 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { tile: Vector; rotation: number; }> { - const mousePosition: any = this.root.app.mousePosition; + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return []; } - let result: any = []; + let result = []; // Figure which points the line visits - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - let endTile: any = worldPos.toTileSpace(); - let startTile: any = this.lastDragTile; + const worldPos = this.root.camera.screenToWorld(mousePosition); + let endTile = worldPos.toTileSpace(); + let startTile = this.lastDragTile; // if the alt key is pressed, reverse belt planner direction by switching start and end tile if (this.root.keyMapper.getBinding(KEYMAPPINGS.placementModifiers.placeInverse).pressed) { - let tmp: any = startTile; + let tmp = startTile; startTile = endTile; endTile = tmp; } // Place from start to corner - const pathToCorner: any = this.currentDirectionLockCorner.sub(startTile); - const deltaToCorner: any = pathToCorner.normalize().round(); - const lengthToCorner: any = Math.round(pathToCorner.length()); - let currentPos: any = startTile.copy(); - let rotation: any = (Math.round(Math.degrees(deltaToCorner.angle()) / 90) * 90 + 360) % 360; + const pathToCorner = this.currentDirectionLockCorner.sub(startTile); + const deltaToCorner = pathToCorner.normalize().round(); + const lengthToCorner = Math.round(pathToCorner.length()); + let currentPos = startTile.copy(); + let rotation = (Math.round(Math.degrees(deltaToCorner.angle()) / 90) * 90 + 360) % 360; if (lengthToCorner > 0) { - for (let i: any = 0; i < lengthToCorner; ++i) { + for (let i = 0; i < lengthToCorner; ++i) { result.push({ tile: currentPos.copy(), rotation, @@ -515,12 +515,12 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { } } // Place from corner to end - const pathFromCorner: any = endTile.sub(this.currentDirectionLockCorner); - const deltaFromCorner: any = pathFromCorner.normalize().round(); - const lengthFromCorner: any = Math.round(pathFromCorner.length()); + const pathFromCorner = endTile.sub(this.currentDirectionLockCorner); + const deltaFromCorner = pathFromCorner.normalize().round(); + const lengthFromCorner = Math.round(pathFromCorner.length()); if (lengthFromCorner > 0) { rotation = (Math.round(Math.degrees(deltaFromCorner.angle()) / 90) * 90 + 360) % 360; - for (let i: any = 0; i < lengthFromCorner + 1; ++i) { + for (let i = 0; i < lengthFromCorner + 1; ++i) { result.push({ tile: currentPos.copy(), rotation, @@ -540,20 +540,20 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Selects a given building */ - startSelection(metaBuilding: MetaBuilding): any { + startSelection(metaBuilding: MetaBuilding) { this.currentMetaBuilding.set(metaBuilding); } /** * Called when the selected buildings changed */ - onSelectedMetaBuildingChanged(metaBuilding: MetaBuilding): any { + onSelectedMetaBuildingChanged(metaBuilding: MetaBuilding) { this.abortDragging(); this.root.hud.signals.selectedPlacementBuildingChanged.dispatch(metaBuilding); if (metaBuilding) { - const availableVariants: any = metaBuilding.getAvailableVariants(this.root); - const preferredVariant: any = this.preferredVariants[metaBuilding.getId()]; + const availableVariants = metaBuilding.getAvailableVariants(this.root); + const preferredVariant = this.preferredVariants[metaBuilding.getId()]; // Choose last stored variant if possible, otherwise the default one - let variant: any; + let variant; if (!preferredVariant || !availableVariants.includes(preferredVariant)) { variant = availableVariants[0]; } @@ -580,12 +580,12 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * mouse down pre handler */ - onMouseDown(pos: Vector, button: enumMouseButton): any { + onMouseDown(pos: Vector, button: enumMouseButton) { if (this.root.camera.getIsMapOverlayActive()) { // We do not allow dragging if the overlay is active return; } - const metaBuilding: any = this.currentMetaBuilding.get(); + const metaBuilding = this.currentMetaBuilding.get(); // Placement if (button === enumMouseButton.left && metaBuilding) { this.currentlyDragging = true; @@ -617,7 +617,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * mouse move pre handler */ - onMouseMove(pos: Vector): any { + onMouseMove(pos: Vector) { if (this.root.camera.getIsMapOverlayActive()) { return; } @@ -625,10 +625,10 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { if (this.isDirectionLockActive) { return; } - const metaBuilding: any = this.currentMetaBuilding.get(); + const metaBuilding = this.currentMetaBuilding.get(); if ((metaBuilding || this.currentlyDeleting) && this.lastDragTile) { - const oldPos: any = this.lastDragTile; - let newPos: any = this.root.camera.screenToWorld(pos).toTileSpace(); + const oldPos = this.lastDragTile; + let newPos = this.root.camera.screenToWorld(pos).toTileSpace(); // Check if camera is moving, since then we do nothing if (this.root.camera.desiredCenter) { this.lastDragTile = newPos; @@ -640,8 +640,8 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { if (metaBuilding && metaBuilding.getRotateAutomaticallyWhilePlacing(this.currentVariant.get()) && !this.root.keyMapper.getBinding(KEYMAPPINGS.placementModifiers.placementDisableAutoOrientation).pressed) { - const delta: any = newPos.sub(oldPos); - const angleDeg: any = Math.degrees(delta.angle()); + const delta = newPos.sub(oldPos); + const angleDeg = Math.degrees(delta.angle()); this.currentBaseRotation = (Math.round(angleDeg / 90) * 90 + 360) % 360; // Holding alt inverts the placement if (this.root.keyMapper.getBinding(KEYMAPPINGS.placementModifiers.placeInverse).pressed) { @@ -649,21 +649,21 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { } } // bresenham - let x0: any = oldPos.x; - let y0: any = oldPos.y; - let x1: any = newPos.x; - let y1: any = newPos.y; - var dx: any = Math.abs(x1 - x0); - var dy: any = Math.abs(y1 - y0); - var sx: any = x0 < x1 ? 1 : -1; - var sy: any = y0 < y1 ? 1 : -1; - var err: any = dx - dy; - let anythingPlaced: any = false; - let anythingDeleted: any = false; + let x0 = oldPos.x; + let y0 = oldPos.y; + let x1 = newPos.x; + let y1 = newPos.y; + var dx = Math.abs(x1 - x0); + var dy = Math.abs(y1 - y0); + var sx = x0 < x1 ? 1 : -1; + var sy = y0 < y1 ? 1 : -1; + var err = dx - dy; + let anythingPlaced = false; + let anythingDeleted = false; while (this.currentlyDeleting || this.currentMetaBuilding.get()) { if (this.currentlyDeleting) { // Deletion - const contents: any = this.root.map.getLayerContentXY(x0, y0, this.root.currentLayer); + const contents = this.root.map.getLayerContentXY(x0, y0, this.root.currentLayer); if (contents && !contents.queuedForDestroy && !contents.destroyed) { if (this.root.logic.tryDeleteBuilding(contents)) { anythingDeleted = true; @@ -678,7 +678,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { } if (x0 === x1 && y0 === y1) break; - var e2: any = 2 * err; + var e2 = 2 * err; if (e2 > -dy) { err -= dy; x0 += sx; @@ -702,7 +702,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart { /** * Mouse up handler */ - onMouseUp(): any { + onMouseUp() { if (this.root.camera.getIsMapOverlayActive()) { return; } diff --git a/src/ts/game/hud/parts/buildings_toolbar.ts b/src/ts/game/hud/parts/buildings_toolbar.ts index df85f548..776e2340 100644 --- a/src/ts/game/hud/parts/buildings_toolbar.ts +++ b/src/ts/game/hud/parts/buildings_toolbar.ts @@ -45,7 +45,7 @@ export class HUDBuildingsToolbar extends HUDBaseToolbar { MetaFilterBuilding, MetaDisplayBuilding, ], - visibilityCondition: (): any => !this.root.camera.getIsMapOverlayActive() && this.root.currentLayer === "regular", + visibilityCondition: () => !this.root.camera.getIsMapOverlayActive() && this.root.currentLayer === "regular", htmlElementId: "ingame_HUD_BuildingsToolbar", }); } diff --git a/src/ts/game/hud/parts/color_blind_helper.ts b/src/ts/game/hud/parts/color_blind_helper.ts index 13066c9c..f1b9f791 100644 --- a/src/ts/game/hud/parts/color_blind_helper.ts +++ b/src/ts/game/hud/parts/color_blind_helper.ts @@ -8,16 +8,16 @@ import { THEME } from "../../theme"; import { globalConfig } from "../../../core/config"; import { T } from "../../../translations"; export class HUDColorBlindHelper extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.belowTileIndicator = makeDiv(parent, "ingame_HUD_ColorBlindBelowTileHelper", []); } - initialize(): any { + initialize() { this.trackedColorBelowTile = new TrackedState(this.onColorBelowTileChanged, this); } /** * Called when the color below the current tile changed */ - onColorBelowTileChanged(color: enumColors | null): any { + onColorBelowTileChanged(color: enumColors | null) { this.belowTileIndicator.classList.toggle("visible", !!color); if (color) { this.belowTileIndicator.innerText = T.ingame.colors[color]; @@ -28,7 +28,7 @@ export class HUDColorBlindHelper extends BaseHUDPart { * {} */ computeColorBelowTile(): enumColors { - const mousePosition: any = this.root.app.mousePosition; + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return null; @@ -37,23 +37,23 @@ export class HUDColorBlindHelper extends BaseHUDPart { // Not in regular mode return null; } - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const tile: any = worldPos.toTileSpace(); - const contents: any = this.root.map.getTileContent(tile, this.root.currentLayer); + const worldPos = this.root.camera.screenToWorld(mousePosition); + const tile = worldPos.toTileSpace(); + const contents = this.root.map.getTileContent(tile, this.root.currentLayer); if (contents && !contents.components.Miner) { - const beltComp: any = contents.components.Belt; + const beltComp = contents.components.Belt; // Check if the belt has a color item if (beltComp) { - const item: any = beltComp.assignedPath.findItemAtTile(tile); + const item = beltComp.assignedPath.findItemAtTile(tile); if (item && item.getItemType() === "color") { return item as ColorItem).color; } } // Check if we are ejecting an item, if so use that color - const ejectorComp: any = contents.components.ItemEjector; + const ejectorComp = contents.components.ItemEjector; if (ejectorComp) { - for (let i: any = 0; i < ejectorComp.slots.length; ++i) { - const slot: any = ejectorComp.slots[i]; + for (let i = 0; i < ejectorComp.slots.length; ++i) { + const slot = ejectorComp.slots[i]; if (slot.item && slot.item.getItemType() === "color") { return slot.item as ColorItem).color; } @@ -62,30 +62,30 @@ export class HUDColorBlindHelper extends BaseHUDPart { } else { // We hovered a lower layer, show the color there - const lowerLayer: any = this.root.map.getLowerLayerContentXY(tile.x, tile.y); + const lowerLayer = this.root.map.getLowerLayerContentXY(tile.x, tile.y); if (lowerLayer && lowerLayer.getItemType() === "color") { return lowerLayer as ColorItem).color; } } return null; } - update(): any { + update() { this.trackedColorBelowTile.set(this.computeColorBelowTile()); } /** * Draws the currently selected tile */ - draw(parameters: DrawParameters): any { - const mousePosition: any = this.root.app.mousePosition; + draw(parameters: DrawParameters) { + const mousePosition = this.root.app.mousePosition; if (!mousePosition) { // Not on screen return null; } - const below: any = this.computeColorBelowTile(); + const below = this.computeColorBelowTile(); if (below) { // We have something below our tile - const worldPos: any = this.root.camera.screenToWorld(mousePosition); - const tile: any = worldPos.toTileSpace().toWorldSpace(); + const worldPos = this.root.camera.screenToWorld(mousePosition); + const tile = worldPos.toTileSpace().toWorldSpace(); parameters.context.strokeStyle = THEME.map.colorBlindPickerTile; parameters.context.lineWidth = 1; parameters.context.beginPath(); diff --git a/src/ts/game/hud/parts/constant_signal_edit.ts b/src/ts/game/hud/parts/constant_signal_edit.ts index e2c417fd..b2aade09 100644 --- a/src/ts/game/hud/parts/constant_signal_edit.ts +++ b/src/ts/game/hud/parts/constant_signal_edit.ts @@ -18,17 +18,17 @@ export const MODS_ADDITIONAL_CONSTANT_SIGNAL_RESOLVER: { [x: string]: (entity: Entity) => BaseItem; } = {}; export class HUDConstantSignalEdit extends BaseHUDPart { - initialize(): any { + initialize() { this.root.camera.downPreHandler.add(this.downPreHandler, this); } - downPreHandler(pos: Vector, button: enumMouseButton): any { + downPreHandler(pos: Vector, button: enumMouseButton) { if (this.root.currentLayer !== "wires") { return; } - const tile: any = this.root.camera.screenToWorld(pos).toTileSpace(); - const contents: any = this.root.map.getLayerContentXY(tile.x, tile.y, "wires"); + const tile = this.root.camera.screenToWorld(pos).toTileSpace(); + const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "wires"); if (contents) { - const constantComp: any = contents.components.ConstantSignal; + const constantComp = contents.components.ConstantSignal; if (constantComp) { if (button === enumMouseButton.left) { this.editConstantSignal(contents, { @@ -44,42 +44,42 @@ export class HUDConstantSignalEdit extends BaseHUDPart { */ editConstantSignal(entity: Entity, { deleteOnCancel = true }: { deleteOnCancel: boolean=; - }): any { + }) { if (!entity.components.ConstantSignal) { return; } // Ok, query, but also save the uid because it could get stale - const uid: any = entity.uid; - const signal: any = entity.components.ConstantSignal.signal; - const signalValueInput: any = new FormElementInput({ + const uid = entity.uid; + const signal = entity.components.ConstantSignal.signal; + const signalValueInput = new FormElementInput({ id: "signalValue", label: fillInLinkIntoTranslation(T.dialogs.editSignal.descShortKey, THIRDPARTY_URLS.shapeViewer), placeholder: "", defaultValue: signal ? signal.getAsCopyableKey() : "", - validator: (val: any): any => this.parseSignalCode(entity, val), + validator: val => this.parseSignalCode(entity, val), }); - const items: any = [...Object.values(COLOR_ITEM_SINGLETONS)]; + const items = [...Object.values(COLOR_ITEM_SINGLETONS)]; if (entity.components.WiredPins) { items.unshift(BOOL_FALSE_SINGLETON, BOOL_TRUE_SINGLETON); items.push(this.root.shapeDefinitionMgr.getShapeItemFromShortKey(this.root.gameMode.getBlueprintShapeKey())); } else { // producer which can produce virtually anything - const shapes: any = ["CuCuCuCu", "RuRuRuRu", "WuWuWuWu", "SuSuSuSu"]; - items.unshift(...shapes.reverse().map((key: any): any => this.root.shapeDefinitionMgr.getShapeItemFromShortKey(key))); + const shapes = ["CuCuCuCu", "RuRuRuRu", "WuWuWuWu", "SuSuSuSu"]; + items.unshift(...shapes.reverse().map(key => this.root.shapeDefinitionMgr.getShapeItemFromShortKey(key))); } if (this.root.gameMode.hasHub()) { items.push(this.root.shapeDefinitionMgr.getShapeItemFromDefinition(this.root.hubGoals.currentGoal.definition)); } if (this.root.hud.parts.pinnedShapes) { - items.push(...this.root.hud.parts.pinnedShapes.pinnedShapes.map((key: any): any => this.root.shapeDefinitionMgr.getShapeItemFromShortKey(key))); + items.push(...this.root.hud.parts.pinnedShapes.pinnedShapes.map(key => this.root.shapeDefinitionMgr.getShapeItemFromShortKey(key))); } - const itemInput: any = new FormElementItemChooser({ + const itemInput = new FormElementItemChooser({ id: "signalItem", label: null, items, }); - const dialog: any = new DialogWithForm({ + const dialog = new DialogWithForm({ app: this.root.app, title: T.dialogs.editConstantProducer.title, desc: T.dialogs.editSignal.descItems, @@ -89,17 +89,17 @@ export class HUDConstantSignalEdit extends BaseHUDPart { }); this.root.hud.parts.dialogs.internalShowDialog(dialog); // When confirmed, set the signal - const closeHandler: any = (): any => { + const closeHandler = () => { if (!this.root || !this.root.entityMgr) { // Game got stopped return; } - const entityRef: any = this.root.entityMgr.findByUid(uid, false); + const entityRef = this.root.entityMgr.findByUid(uid, false); if (!entityRef) { // outdated return; } - const constantComp: any = entityRef.components.ConstantSignal; + const constantComp = entityRef.components.ConstantSignal; if (!constantComp) { // no longer interesting return; @@ -111,26 +111,26 @@ export class HUDConstantSignalEdit extends BaseHUDPart { constantComp.signal = this.parseSignalCode(entity, signalValueInput.getValue()); } }; - dialog.buttonSignals.ok.add((): any => { + dialog.buttonSignals.ok.add(() => { closeHandler(); }); - dialog.valueChosen.add((): any => { + dialog.valueChosen.add(() => { dialog.closeRequested.dispatch(); closeHandler(); }); // When cancelled, destroy the entity again if (deleteOnCancel) { - dialog.buttonSignals.cancel.add((): any => { + dialog.buttonSignals.cancel.add(() => { if (!this.root || !this.root.entityMgr) { // Game got stopped return; } - const entityRef: any = this.root.entityMgr.findByUid(uid, false); + const entityRef = this.root.entityMgr.findByUid(uid, false); if (!entityRef) { // outdated return; } - const constantComp: any = entityRef.components.ConstantSignal; + const constantComp = entityRef.components.ConstantSignal; if (!constantComp) { // no longer interesting return; @@ -149,7 +149,7 @@ export class HUDConstantSignalEdit extends BaseHUDPart { return null; } code = trim(code); - const codeLower: any = code.toLowerCase(); + const codeLower = code.toLowerCase(); if (MODS_ADDITIONAL_CONSTANT_SIGNAL_RESOLVER[codeLower]) { return MODS_ADDITIONAL_CONSTANT_SIGNAL_RESOLVER[codeLower].apply(this, [entity]); } diff --git a/src/ts/game/hud/parts/debug_changes.ts b/src/ts/game/hud/parts/debug_changes.ts index 4d810dc4..d09a55ac 100644 --- a/src/ts/game/hud/parts/debug_changes.ts +++ b/src/ts/game/hud/parts/debug_changes.ts @@ -10,14 +10,14 @@ export type DebugChange = { }; export class HUDChangesDebugger extends BaseHUDPart { - createElements(parent: any): any { } - initialize(): any { + createElements(parent) { } + initialize() { this.changes = []; } /** * Renders a new change */ - renderChange(label: string, area: Rectangle, fillColor: string, timeToDisplay: number= = 0.3): any { + renderChange(label: string, area: Rectangle, fillColor: string, timeToDisplay: number= = 0.3) { this.changes.push({ label, area: area.clone(), @@ -25,11 +25,11 @@ export class HUDChangesDebugger extends BaseHUDPart { hideAt: this.root.time.realtimeNow() + timeToDisplay, }); } - update(): any { - const now: any = this.root.time.realtimeNow(); + update() { + const now = this.root.time.realtimeNow(); // Detect outdated changes - for (let i: any = 0; i < this.changes.length; ++i) { - const change: any = this.changes[i]; + for (let i = 0; i < this.changes.length; ++i) { + const change = this.changes[i]; if (change.hideAt <= now) { this.changes.splice(i, 1); i -= 1; @@ -37,9 +37,9 @@ export class HUDChangesDebugger extends BaseHUDPart { } } } - draw(parameters: DrawParameters): any { - for (let i: any = 0; i < this.changes.length; ++i) { - const change: any = this.changes[i]; + draw(parameters: DrawParameters) { + for (let i = 0; i < this.changes.length; ++i) { + const change = this.changes[i]; parameters.context.fillStyle = change.fillColor; parameters.context.globalAlpha = 0.2; parameters.context.fillRect(change.area.x * globalConfig.tileSize, change.area.y * globalConfig.tileSize, change.area.w * globalConfig.tileSize, change.area.h * globalConfig.tileSize); diff --git a/src/ts/game/hud/parts/debug_info.ts b/src/ts/game/hud/parts/debug_info.ts index 9a513f86..fd933c52 100644 --- a/src/ts/game/hud/parts/debug_info.ts +++ b/src/ts/game/hud/parts/debug_info.ts @@ -5,51 +5,51 @@ import { KEYMAPPINGS } from "../../key_action_mapper"; import { Vector } from "../../../core/vector"; import { TrackedState } from "../../../core/tracked_state"; /** @enum {string} */ -const enumDebugOverlayMode: any = { disabled: "disabled", regular: "regular", detailed: "detailed" }; +const enumDebugOverlayMode = { disabled: "disabled", regular: "regular", detailed: "detailed" }; /** * Specifies which mode follows after which mode * @enum {enumDebugOverlayMode} */ -const enumDebugOverlayModeNext: any = { +const enumDebugOverlayModeNext = { [enumDebugOverlayMode.disabled]: enumDebugOverlayMode.regular, [enumDebugOverlayMode.regular]: enumDebugOverlayMode.detailed, [enumDebugOverlayMode.detailed]: enumDebugOverlayMode.disabled, }; -const UPDATE_INTERVAL_SECONDS: any = 0.25; +const UPDATE_INTERVAL_SECONDS = 0.25; export class HUDDebugInfo extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_DebugInfo", []); - const tickRateElement: any = makeDiv(this.element, null, ["tickRate"]); - this.trackedTickRate = new TrackedState((str: any): any => (tickRateElement.innerText = str)); - const tickDurationElement: any = makeDiv(this.element, null, ["tickDuration"]); - this.trackedTickDuration = new TrackedState((str: any): any => (tickDurationElement.innerText = str)); - const fpsElement: any = makeDiv(this.element, null, ["fps"]); - this.trackedFPS = new TrackedState((str: any): any => (fpsElement.innerText = str)); - const mousePositionElement: any = makeDiv(this.element, null, ["mousePosition"]); - this.trackedMousePosition = new TrackedState((str: any): any => (mousePositionElement.innerHTML = str)); - const cameraPositionElement: any = makeDiv(this.element, null, ["cameraPosition"]); - this.trackedCameraPosition = new TrackedState((str: any): any => (cameraPositionElement.innerHTML = str)); + const tickRateElement = makeDiv(this.element, null, ["tickRate"]); + this.trackedTickRate = new TrackedState(str => (tickRateElement.innerText = str)); + const tickDurationElement = makeDiv(this.element, null, ["tickDuration"]); + this.trackedTickDuration = new TrackedState(str => (tickDurationElement.innerText = str)); + const fpsElement = makeDiv(this.element, null, ["fps"]); + this.trackedFPS = new TrackedState(str => (fpsElement.innerText = str)); + const mousePositionElement = makeDiv(this.element, null, ["mousePosition"]); + this.trackedMousePosition = new TrackedState(str => (mousePositionElement.innerHTML = str)); + const cameraPositionElement = makeDiv(this.element, null, ["cameraPosition"]); + this.trackedCameraPosition = new TrackedState(str => (cameraPositionElement.innerHTML = str)); this.versionElement = makeDiv(this.element, null, ["version"], "version unknown"); } - initialize(): any { + initialize() { this.lastTick = 0; this.trackedMode = new TrackedState(this.onModeChanged, this); this.domAttach = new DynamicDomAttach(this.root, this.element); - this.root.keyMapper.getBinding(KEYMAPPINGS.ingame.toggleFPSInfo).add((): any => this.cycleModes()); + this.root.keyMapper.getBinding(KEYMAPPINGS.ingame.toggleFPSInfo).add(() => this.cycleModes()); // Set initial mode this.trackedMode.set(enumDebugOverlayMode.disabled); } /** * Called when the mode changed */ - onModeChanged(mode: enumDebugOverlayMode): any { + onModeChanged(mode: enumDebugOverlayMode) { this.element.setAttribute("data-mode", mode); this.versionElement.innerText = `${G_BUILD_VERSION} @ ${G_APP_ENVIRONMENT} @ ${G_BUILD_COMMIT_HASH}`; } /** * Updates the labels */ - updateLabels(): any { + updateLabels() { this.trackedTickRate.set("Tickrate: " + this.root.dynamicTickrate.currentTickRate); this.trackedFPS.set("FPS: " + Math.round(this.root.dynamicTickrate.averageFps) + @@ -61,27 +61,27 @@ export class HUDDebugInfo extends BaseHUDPart { /** * Updates the detailed information */ - updateDetailedInformation(): any { - const mousePos: any = this.root.app.mousePosition || new Vector(0, 0); - const mouseTile: any = this.root.camera.screenToWorld(mousePos).toTileSpace(); - const cameraTile: any = this.root.camera.center.toTileSpace(); + updateDetailedInformation() { + const mousePos = this.root.app.mousePosition || new Vector(0, 0); + const mouseTile = this.root.camera.screenToWorld(mousePos).toTileSpace(); + const cameraTile = this.root.camera.center.toTileSpace(); this.trackedMousePosition.set(`Mouse: ${mouseTile.x} / ${mouseTile.y}`); this.trackedCameraPosition.set(`Camera: ${cameraTile.x} / ${cameraTile.y}`); } /** * Cycles through the different modes */ - cycleModes(): any { + cycleModes() { this.trackedMode.set(enumDebugOverlayModeNext[this.trackedMode.get()]); } - update(): any { - const visible: any = this.trackedMode.get() !== enumDebugOverlayMode.disabled; + update() { + const visible = this.trackedMode.get() !== enumDebugOverlayMode.disabled; this.domAttach.update(visible); if (!visible) { return; } // Periodically update the text - const now: any = this.root.time.realtimeNow(); + const now = this.root.time.realtimeNow(); if (now - this.lastTick > UPDATE_INTERVAL_SECONDS) { this.lastTick = now; this.updateLabels(); diff --git a/src/ts/game/hud/parts/entity_debugger.ts b/src/ts/game/hud/parts/entity_debugger.ts index 3c2e4658..83033749 100644 --- a/src/ts/game/hud/parts/entity_debugger.ts +++ b/src/ts/game/hud/parts/entity_debugger.ts @@ -8,7 +8,7 @@ import { DynamicDomAttach } from "../dynamic_dom_attach"; * Allows to inspect entities by pressing F8 while hovering them */ export class HUDEntityDebugger extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_EntityDebugger", [], ` Use F8 to toggle this overlay @@ -19,8 +19,8 @@ export class HUDEntityDebugger extends BaseHUDPart { `); this.componentsElem = this.element.querySelector(".entityComponents"); } - initialize(): any { - this.root.gameState.inputReciever.keydown.add((key: any): any => { + initialize() { + this.root.gameState.inputReciever.keydown.add(key => { if (key.keyCode === 119) { // F8 this.pickEntity(); @@ -33,20 +33,20 @@ export class HUDEntityDebugger extends BaseHUDPart { this.lastUpdate = 0; this.domAttach = new DynamicDomAttach(this.root, this.element); } - pickEntity(): any { - const mousePos: any = this.root.app.mousePosition; + pickEntity() { + const mousePos = this.root.app.mousePosition; if (!mousePos) { return; } - const worldPos: any = this.root.camera.screenToWorld(mousePos); - const worldTile: any = worldPos.toTileSpace(); - const entity: any = this.root.map.getTileContent(worldTile, this.root.currentLayer); + const worldPos = this.root.camera.screenToWorld(mousePos); + const worldTile = worldPos.toTileSpace(); + const entity = this.root.map.getTileContent(worldTile, this.root.currentLayer); this.selectedEntity = entity; if (entity) { this.rerenderFull(entity); } } - propertyToHTML(name: string, val: any, indent: number = 0, recursion: Array = []): any { + propertyToHTML(name: string, val: any, indent: number = 0, recursion: Array = []) { if (indent > 20) { return; } @@ -56,19 +56,19 @@ export class HUDEntityDebugger extends BaseHUDPart { // Get type class name (like Array, Object, Vector...) - let typeName: any = `(${val.constructor ? val.constructor.name : "unknown"})`; + let typeName = `(${val.constructor ? val.constructor.name : "unknown"})`; if (Array.isArray(val)) { typeName = `(Array[${val.length}])`; } if (val instanceof Vector) { typeName = `(Vector[${val.x}, ${val.y}])`; } - const colorStyle: any = `color: hsl(${30 * indent}, 100%, 80%)`; - let html: any = `
+ const colorStyle = `color: hsl(${30 * indent}, 100%, 80%)`; + let html = `
${name} ${typeName}
`; - for (const property: any in val) { - let hiddenValue: any = null; + for (const property in val) { + let hiddenValue = null; if (val[property] == this.root) { hiddenValue = ""; } @@ -86,7 +86,7 @@ export class HUDEntityDebugger extends BaseHUDPart { html += "
"; return html; } - const displayValue: any = (val + "") + const displayValue = (val + "") .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">"); @@ -95,18 +95,18 @@ export class HUDEntityDebugger extends BaseHUDPart { /** * Rerenders the whole container */ - rerenderFull(entity: Entity): any { + rerenderFull(entity: Entity) { removeAllChildren(this.componentsElem); - let html: any = ""; - const property: any = (strings: any, val: any): any => ` ${val}`; + let html = ""; + const property = (strings, val) => ` ${val}`; html += property `registered ${!!entity.registered}`; html += property `uid ${entity.uid}`; html += property `destroyed ${!!entity.destroyed}`; - for (const componentId: any in entity.components) { - const data: any = entity.components[componentId]; + for (const componentId in entity.components) { + const data = entity.components[componentId]; html += "
"; html += "" + componentId + "
"; - for (const property: any in data) { + for (const property in data) { // Put entity into recursion list, so it won't get "expanded" html += this.propertyToHTML(property, data[property], 0, [entity]); } @@ -114,7 +114,7 @@ export class HUDEntityDebugger extends BaseHUDPart { } this.componentsElem.innerHTML = html; } - update(): any { + update() { this.domAttach.update(!!this.selectedEntity); } } diff --git a/src/ts/game/hud/parts/game_menu.ts b/src/ts/game/hud/parts/game_menu.ts index 5311aac3..b291fc3e 100644 --- a/src/ts/game/hud/parts/game_menu.ts +++ b/src/ts/game/hud/parts/game_menu.ts @@ -7,15 +7,15 @@ import { KEYMAPPINGS } from "../../key_action_mapper"; import { DynamicDomAttach } from "../dynamic_dom_attach"; import { TrackedState } from "../../../core/tracked_state"; export class HUDGameMenu extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_GameMenu"); - const buttons: any = [ + const buttons = [ { id: "shop", label: "Upgrades", - handler: (): any => this.root.hud.parts.shop.show(), + handler: () => this.root.hud.parts.shop.show(), keybinding: KEYMAPPINGS.ingame.menuOpenShop, - badge: (): any => this.root.hubGoals.getAvailableUpgradeCount(), + badge: () => this.root.hubGoals.getAvailableUpgradeCount(), notification: [ T.ingame.notifications.newUpgrade, enumNotificationType.upgrade, @@ -23,25 +23,25 @@ export class HUDGameMenu extends BaseHUDPart { string, enumNotificationType ]), - visible: (): any => !this.root.app.settings.getAllSettings().offerHints || this.root.hubGoals.level >= 3, + visible: () => !this.root.app.settings.getAllSettings().offerHints || this.root.hubGoals.level >= 3, }, { id: "stats", label: "Stats", - handler: (): any => this.root.hud.parts.statistics.show(), + handler: () => this.root.hud.parts.statistics.show(), keybinding: KEYMAPPINGS.ingame.menuOpenStats, - visible: (): any => !this.root.app.settings.getAllSettings().offerHints || this.root.hubGoals.level >= 3, + visible: () => !this.root.app.settings.getAllSettings().offerHints || this.root.hubGoals.level >= 3, }, ]; this.badgesToUpdate = []; this.visibilityToUpdate = []; - buttons.forEach(({ id, label, handler, keybinding, badge, notification, visible }: any): any => { - const button: any = document.createElement("button"); + buttons.forEach(({ id, label, handler, keybinding, badge, notification, visible }) => { + const button = document.createElement("button"); button.classList.add(id); this.element.appendChild(button); this.trackClicks(button, handler); if (keybinding) { - const binding: any = this.root.keyMapper.getBinding(keybinding); + const binding = this.root.keyMapper.getBinding(keybinding); binding.add(handler); } if (visible) { @@ -52,7 +52,7 @@ export class HUDGameMenu extends BaseHUDPart { }); } if (badge) { - const badgeElement: any = makeDiv(button, null, ["badge"]); + const badgeElement = makeDiv(button, null, ["badge"]); this.badgesToUpdate.push({ badge, lastRenderAmount: 0, @@ -68,29 +68,29 @@ export class HUDGameMenu extends BaseHUDPart { this.trackClicks(this.saveButton, this.startSave); this.trackClicks(this.settingsButton, this.openSettings); } - initialize(): any { + initialize() { this.root.signals.gameSaved.add(this.onGameSaved, this); this.trackedIsSaving = new TrackedState(this.onIsSavingChanged, this); } - update(): any { - let playSound: any = false; - let notifications: any = new Set(); + update() { + let playSound = false; + let notifications = new Set(); // Check whether we are saving this.trackedIsSaving.set(!!this.root.gameState.currentSavePromise); // Update visibility of buttons - for (let i: any = 0; i < this.visibilityToUpdate.length; ++i) { - const { condition, domAttach }: any = this.visibilityToUpdate[i]; + for (let i = 0; i < this.visibilityToUpdate.length; ++i) { + const { condition, domAttach } = this.visibilityToUpdate[i]; domAttach.update(condition()); } // Check for notifications and badges - for (let i: any = 0; i < this.badgesToUpdate.length; ++i) { - const { badge, button, badgeElement, lastRenderAmount, notification, condition, }: any = this.badgesToUpdate[i]; + for (let i = 0; i < this.badgesToUpdate.length; ++i) { + const { badge, button, badgeElement, lastRenderAmount, notification, condition, } = this.badgesToUpdate[i]; if (condition && !condition()) { // Do not show notifications for invisible buttons continue; } // Check if the amount shown differs from the one shown last frame - const amount: any = badge(); + const amount = badge(); if (lastRenderAmount !== amount) { if (amount > 0) { badgeElement.innerText = amount; @@ -110,21 +110,21 @@ export class HUDGameMenu extends BaseHUDPart { if (playSound) { this.root.soundProxy.playUi(SOUNDS.badgeNotification); } - notifications.forEach(([notification, type]: any): any => { + notifications.forEach(([notification, type]) => { this.root.hud.signals.notification.dispatch(notification, type); }); } - onIsSavingChanged(isSaving: any): any { + onIsSavingChanged(isSaving) { this.saveButton.classList.toggle("saving", isSaving); } - onGameSaved(): any { + onGameSaved() { this.saveButton.classList.toggle("animEven"); this.saveButton.classList.toggle("animOdd"); } - startSave(): any { + startSave() { this.root.gameState.doSave(); } - openSettings(): any { + openSettings() { this.root.hud.parts.settingsMenu.show(); } } diff --git a/src/ts/game/hud/parts/interactive_tutorial.ts b/src/ts/game/hud/parts/interactive_tutorial.ts index 2de171e9..a5ea6a1c 100644 --- a/src/ts/game/hud/parts/interactive_tutorial.ts +++ b/src/ts/game/hud/parts/interactive_tutorial.ts @@ -20,29 +20,29 @@ import { MetaTrashBuilding } from "../../buildings/trash"; import { SOUNDS } from "../../../platform/sound"; import { THEME } from "../../theme"; // @todo: Make dictionary -const tutorialsByLevel: any = [ +const tutorialsByLevel = [ // Level 1 [ // 1.1. place an extractor { id: "1_1_extractor", - condition: oot: GameRoot): any => root.entityMgr.getAllWithComponent(MinerComponent).length === 0, + condition: oot: GameRoot) => root.entityMgr.getAllWithComponent(MinerComponent).length === 0, }, // 1.2. connect to hub { id: "1_2_conveyor", - condition: oot: GameRoot): any => { - const paths: any = root.systemMgr.systems.belt.beltPaths; - const miners: any = root.entityMgr.getAllWithComponent(MinerComponent); - for (let i: any = 0; i < paths.length; i++) { - const path: any = paths[i]; - const acceptingEntity: any = path.computeAcceptingEntityAndSlot().entity; + condition: oot: GameRoot) => { + const paths = root.systemMgr.systems.belt.beltPaths; + const miners = root.entityMgr.getAllWithComponent(MinerComponent); + for (let i = 0; i < paths.length; i++) { + const path = paths[i]; + const acceptingEntity = path.computeAcceptingEntityAndSlot().entity; if (!acceptingEntity || !acceptingEntity.components.Hub) { continue; } // Find a miner which delivers to this belt path - for (let k: any = 0; k < miners.length; ++k) { - const miner: any = miners[k]; + for (let k = 0; k < miners.length; ++k) { + const miner = miners[k]; if (miner.components.ItemEjector.slots[0].cachedBeltPath === path) { return false; } @@ -54,7 +54,7 @@ const tutorialsByLevel: any = [ // 1.3 wait for completion { id: "1_3_expand", - condition: oot: GameRoot): any => true, + condition: oot: GameRoot) => true, }, ], // Level 2 @@ -62,23 +62,23 @@ const tutorialsByLevel: any = [ // 2.1 place a cutter { id: "2_1_place_cutter", - condition: oot: GameRoot): any => root.entityMgr + condition: oot: GameRoot) => root.entityMgr .getAllWithComponent(ItemProcessorComponent) - .filter((e: any): any => e.components.ItemProcessor.type === enumItemProcessorTypes.cutter).length === + .filter(e => e.components.ItemProcessor.type === enumItemProcessorTypes.cutter).length === 0, }, // 2.2 place trash { id: "2_2_place_trash", - condition: oot: GameRoot): any => root.entityMgr + condition: oot: GameRoot) => root.entityMgr .getAllWithComponent(ItemProcessorComponent) - .filter((e: any): any => e.components.ItemProcessor.type === enumItemProcessorTypes.trash).length === + .filter(e => e.components.ItemProcessor.type === enumItemProcessorTypes.trash).length === 0, }, // 2.3 place more cutters { id: "2_3_more_cutters", - condition: oot: GameRoot): any => true, + condition: oot: GameRoot) => true, }, ], // Level 3 @@ -86,14 +86,14 @@ const tutorialsByLevel: any = [ // 3.1. rectangles { id: "3_1_rectangles", - condition: oot: GameRoot): any => + condition: oot: GameRoot) => // 4 miners placed above rectangles and 10 delivered root.hubGoals.getCurrentGoalDelivered() < 10 || - root.entityMgr.getAllWithComponent(MinerComponent).filter((entity: any): any => { - const tile: any = entity.components.StaticMapEntity.origin; - const below: any = root.map.getLowerLayerContentXY(tile.x, tile.y); + root.entityMgr.getAllWithComponent(MinerComponent).filter(entity => { + const tile = entity.components.StaticMapEntity.origin; + const below = root.map.getLowerLayerContentXY(tile.x, tile.y); if (below && below.getItemType() === "shape") { - const shape: any = (below as ShapeItem).definition.getHash(); + const shape = below as ShapeItem).definition.getHash(); return shape === "RuRuRuRu"; } return false; @@ -122,45 +122,45 @@ const tutorialsByLevel: any = [ // 21.1 place quad painter { id: "21_1_place_quad_painter", - condition: oot: GameRoot): any => root.entityMgr + condition: oot: GameRoot) => root.entityMgr .getAllWithComponent(ItemProcessorComponent) - .filter((e: any): any => e.components.ItemProcessor.type === enumItemProcessorTypes.painterQuad) + .filter(e => e.components.ItemProcessor.type === enumItemProcessorTypes.painterQuad) .length === 0, }, // 21.2 switch to wires layer { id: "21_2_switch_to_wires", - condition: oot: GameRoot): any => root.entityMgr.getAllWithComponent(WireComponent).length < 5, + condition: oot: GameRoot) => root.entityMgr.getAllWithComponent(WireComponent).length < 5, }, // 21.3 place button { id: "21_3_place_button", - condition: oot: GameRoot): any => root.entityMgr.getAllWithComponent(LeverComponent).length === 0, + condition: oot: GameRoot) => root.entityMgr.getAllWithComponent(LeverComponent).length === 0, }, // 21.4 activate button { id: "21_4_press_button", - condition: oot: GameRoot): any => root.entityMgr.getAllWithComponent(LeverComponent).some((e: any): any => !e.components.Lever.toggled), + condition: oot: GameRoot) => root.entityMgr.getAllWithComponent(LeverComponent).some(e => !e.components.Lever.toggled), }, ], ]; export class HUDInteractiveTutorial extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_InteractiveTutorial", ["animEven"], ` ${T.ingame.interactiveTutorial.title} `); this.elementDescription = makeDiv(this.element, null, ["desc"]); this.elementGif = makeDiv(this.element, null, ["helperGif"]); } - cleanup(): any { + cleanup() { document.documentElement.setAttribute("data-tutorial-step", ""); } - initialize(): any { + initialize() { this.domAttach = new DynamicDomAttach(this.root, this.element, { trackHover: true }); this.currentHintId = new TrackedState(this.onHintChanged, this); document.documentElement.setAttribute("data-tutorial-step", ""); } - onHintChanged(hintId: any): any { + onHintChanged(hintId) { this.elementDescription.innerHTML = T.ingame.interactiveTutorial.hints[hintId]; document.documentElement.setAttribute("data-tutorial-step", hintId); this.elementGif.style.backgroundImage = @@ -171,13 +171,13 @@ export class HUDInteractiveTutorial extends BaseHUDPart { this.root.app.sound.playUiSound(SOUNDS.tutorialStep); } } - update(): any { + update() { // Compute current hint - const thisLevelHints: any = tutorialsByLevel[this.root.hubGoals.level - 1]; - let targetHintId: any = null; + const thisLevelHints = tutorialsByLevel[this.root.hubGoals.level - 1]; + let targetHintId = null; if (thisLevelHints) { - for (let i: any = 0; i < thisLevelHints.length; ++i) { - const hint: any = thisLevelHints[i]; + for (let i = 0; i < thisLevelHints.length; ++i) { + const hint = thisLevelHints[i]; if (hint.condition(this.root)) { targetHintId = hint.id; break; @@ -187,23 +187,23 @@ export class HUDInteractiveTutorial extends BaseHUDPart { this.currentHintId.set(targetHintId); this.domAttach.update(!!targetHintId); } - draw(parameters: DrawParameters): any { - const animation: any = smoothPulse(this.root.time.now()); - const currentBuilding: any = this.root.hud.parts.buildingPlacer.currentMetaBuilding.get(); + draw(parameters: DrawParameters) { + const animation = smoothPulse(this.root.time.now()); + const currentBuilding = this.root.hud.parts.buildingPlacer.currentMetaBuilding.get(); if (["1_1_extractor"].includes(this.currentHintId.get())) { if (currentBuilding && currentBuilding.getId() === gMetaBuildingRegistry.findByClass(MetaMinerBuilding).getId()) { // Find closest circle patch to hub - let closest: any = null; - let closestDistance: any = 1e10; - for (let i: any = 0; i > -globalConfig.mapChunkSize; --i) { - for (let j: any = 0; j < globalConfig.mapChunkSize; ++j) { - const resourceItem: any = this.root.map.getLowerLayerContentXY(i, j); + let closest = null; + let closestDistance = 1e10; + for (let i = 0; i > -globalConfig.mapChunkSize; --i) { + for (let j = 0; j < globalConfig.mapChunkSize; ++j) { + const resourceItem = this.root.map.getLowerLayerContentXY(i, j); if (resourceItem instanceof ShapeItem && resourceItem.definition.getHash() === "CuCuCuCu") { - let distance: any = Math.hypot(i, j); + let distance = Math.hypot(i, j); if (!closest || distance < closestDistance) { - const tile: any = new Vector(i, j); + const tile = new Vector(i, j); if (!this.root.map.getTileContent(tile, "regular")) { closest = tile; closestDistance = distance; @@ -227,12 +227,12 @@ export class HUDInteractiveTutorial extends BaseHUDPart { if (currentBuilding && currentBuilding.getId() === gMetaBuildingRegistry.findByClass(MetaBeltBuilding).getId()) { // Find closest miner - const miners: any = this.root.entityMgr.getAllWithComponent(MinerComponent); - let closest: any = null; - let closestDistance: any = 1e10; - for (let i: any = 0; i < miners.length; i++) { - const miner: any = miners[i]; - const distance: any = miner.components.StaticMapEntity.origin.lengthSquare(); + const miners = this.root.entityMgr.getAllWithComponent(MinerComponent); + let closest = null; + let closestDistance = 1e10; + for (let i = 0; i < miners.length; i++) { + const miner = miners[i]; + const distance = miner.components.StaticMapEntity.origin.lengthSquare(); if (![0, 90].includes(miner.components.StaticMapEntity.rotation)) { continue; } @@ -242,12 +242,12 @@ export class HUDInteractiveTutorial extends BaseHUDPart { } if (closest) { // draw line from miner to hub -> But respect orientation - const staticComp: any = closest.components.StaticMapEntity; - const offset: any = staticComp.rotation === 0 ? new Vector(0.5, 0) : new Vector(1, 0.5); - const anchor: any = staticComp.rotation === 0 + const staticComp = closest.components.StaticMapEntity; + const offset = staticComp.rotation === 0 ? new Vector(0.5, 0) : new Vector(1, 0.5); + const anchor = staticComp.rotation === 0 ? new Vector(staticComp.origin.x + 0.5, 0.5) : new Vector(-0.5, staticComp.origin.y + 0.5); - const target: any = staticComp.rotation === 0 ? new Vector(-2.1, 0.5) : new Vector(-0.5, 2.1); + const target = staticComp.rotation === 0 ? new Vector(-2.1, 0.5) : new Vector(-0.5, 2.1); parameters.context.globalAlpha = 0.1 + animation * 0.1; parameters.context.strokeStyle = "rgb(74, 237, 134)"; parameters.context.lineWidth = globalConfig.tileSize / 2; @@ -257,11 +257,11 @@ export class HUDInteractiveTutorial extends BaseHUDPart { parameters.context.lineTo(target.x * globalConfig.tileSize, target.y * globalConfig.tileSize); parameters.context.stroke(); parameters.context.globalAlpha = 1; - const arrowSprite: any = this.root.hud.parts.buildingPlacer.lockIndicatorSprites.regular; - let arrows: any = []; - let pos: any = staticComp.origin.add(offset); - let delta: any = anchor.sub(pos).normalize(); - let maxIter: any = 999; + const arrowSprite = this.root.hud.parts.buildingPlacer.lockIndicatorSprites.regular; + let arrows = []; + let pos = staticComp.origin.add(offset); + let delta = anchor.sub(pos).normalize(); + let maxIter = 999; while (pos.distanceSquare(anchor) > 1 && maxIter-- > 0) { pos = pos.add(delta); arrows.push({ @@ -271,7 +271,7 @@ export class HUDInteractiveTutorial extends BaseHUDPart { } pos = anchor.copy(); delta = target.sub(pos).normalize(); - const localDelta: any = staticComp.rotation === 0 ? new Vector(-1.5, -0.5) : new Vector(-0.5, 0.5); + const localDelta = staticComp.rotation === 0 ? new Vector(-1.5, -0.5) : new Vector(-0.5, 0.5); while (pos.distanceSquare(target) > 1 && maxIter-- > 0) { pos = pos.add(delta); arrows.push({ @@ -279,10 +279,10 @@ export class HUDInteractiveTutorial extends BaseHUDPart { rotation: 90 - staticComp.rotation, }); } - for (let i: any = 0; i < arrows.length; i++) { - const { pos, rotation }: any = arrows[i]; - const worldPos: any = pos.toWorldSpaceCenterOfTile(); - const angle: any = Math.radians(rotation); + for (let i = 0; i < arrows.length; i++) { + const { pos, rotation } = arrows[i]; + const worldPos = pos.toWorldSpaceCenterOfTile(); + const angle = Math.radians(rotation); parameters.context.translate(worldPos.x, worldPos.y); parameters.context.rotate(angle); parameters.context.drawImage(arrowSprite, -6, -globalConfig.halfTileSize - @@ -297,7 +297,7 @@ export class HUDInteractiveTutorial extends BaseHUDPart { parameters.context.fillStyle = THEME.map.tutorialDragText; parameters.context.font = "15px GameFont"; if (staticComp.rotation === 0) { - const pos: any = staticComp.origin.toWorldSpace().subScalars(2, 10); + const pos = staticComp.origin.toWorldSpace().subScalars(2, 10); parameters.context.translate(pos.x, pos.y); parameters.context.rotate(-Math.radians(90)); parameters.context.fillText(T.ingame.interactiveTutorial.hints["1_2_hold_and_drag"], 0, 0); @@ -305,7 +305,7 @@ export class HUDInteractiveTutorial extends BaseHUDPart { parameters.context.translate(-pos.x, -pos.y); } else { - const pos: any = staticComp.origin.toWorldSpace().addScalars(40, 50); + const pos = staticComp.origin.toWorldSpace().addScalars(40, 50); parameters.context.fillText(T.ingame.interactiveTutorial.hints["1_2_hold_and_drag"], pos.x, pos.y); } } @@ -315,13 +315,13 @@ export class HUDInteractiveTutorial extends BaseHUDPart { // Find cutters if (currentBuilding && currentBuilding.getId() === gMetaBuildingRegistry.findByClass(MetaTrashBuilding).getId()) { - const entities: any = this.root.entityMgr.getAllWithComponent(ItemProcessorComponent); - for (let i: any = 0; i < entities.length; i++) { - const entity: any = entities[i]; + const entities = this.root.entityMgr.getAllWithComponent(ItemProcessorComponent); + for (let i = 0; i < entities.length; i++) { + const entity = entities[i]; if (entity.components.ItemProcessor.type !== enumItemProcessorTypes.cutter) { continue; } - const slot: any = entity.components.StaticMapEntity.localTileToWorld(new Vector(1, -1)).toWorldSpace(); + const slot = entity.components.StaticMapEntity.localTileToWorld(new Vector(1, -1)).toWorldSpace(); parameters.context.fillStyle = "rgba(74, 237, 134, " + (0.5 - animation * 0.2) + ")"; parameters.context.strokeStyle = "rgb(74, 237, 134)"; parameters.context.lineWidth = 2; diff --git a/src/ts/game/hud/parts/keybinding_overlay.ts b/src/ts/game/hud/parts/keybinding_overlay.ts index cd8bb041..21ea147a 100644 --- a/src/ts/game/hud/parts/keybinding_overlay.ts +++ b/src/ts/game/hud/parts/keybinding_overlay.ts @@ -4,8 +4,8 @@ import { getStringForKeyCode, KEYCODE_LMB, KEYCODE_MMB, KEYCODE_RMB, KEYMAPPINGS import { enumHubGoalRewards } from "../../tutorial_goals"; import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; -const DIVIDER_TOKEN: any = "/"; -const ADDER_TOKEN: any = "+"; +const DIVIDER_TOKEN = "/"; +const ADDER_TOKEN = "+"; export type KeyCode = { keyCode: number; }; @@ -24,7 +24,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { * {} */ get buildingPlacementActive() { - const placer: any = this.root.hud.parts.buildingPlacer; + const placer = this.root.hud.parts.buildingPlacer; return !this.mapOverviewActive && placer && !!placer.currentMetaBuilding.get(); } /** @@ -33,7 +33,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { * {} */ get buildingPlacementSupportsBeltPlanner() { - const placer: any = this.root.hud.parts.buildingPlacer; + const placer = this.root.hud.parts.buildingPlacer; return (!this.mapOverviewActive && placer && placer.currentMetaBuilding.get() && @@ -45,7 +45,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { * {} */ get buildingPlacementStaysInPlacement() { - const placer: any = this.root.hud.parts.buildingPlacer; + const placer = this.root.hud.parts.buildingPlacer; return (!this.mapOverviewActive && placer && placer.currentMetaBuilding.get() && @@ -56,7 +56,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { * {} */ get blueprintPlacementActive() { - const placer: any = this.root.hud.parts.blueprintPlacer; + const placer = this.root.hud.parts.blueprintPlacer; return placer && !!placer.currentBlueprint.get(); } /** @@ -64,7 +64,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { * {} */ get beltPlannerActive() { - const placer: any = this.root.hud.parts.buildingPlacer; + const placer = this.root.hud.parts.buildingPlacer; return !this.mapOverviewActive && placer && placer.isDirectionLockActive; } /** @@ -72,7 +72,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { * {} */ get lastBlueprintAvailable() { - const placer: any = this.root.hud.parts.blueprintPlacer; + const placer = this.root.hud.parts.blueprintPlacer; return placer && !!placer.lastBlueprintUsed; } /** @@ -80,7 +80,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { * {} */ get anythingSelectedOnMap() { - const selector: any = this.root.hud.parts.massSelector; + const selector = this.root.hud.parts.massSelector; return selector && selector.selectedUids.size > 0; } /** @@ -100,9 +100,9 @@ export class HUDKeybindingOverlay extends BaseHUDPart { /** * Initializes the element */ - createElements(parent: HTMLElement): any { - const mapper: any = this.root.keyMapper; - const k: any = KEYMAPPINGS; + createElements(parent: HTMLElement) { + const mapper = this.root.keyMapper; + const k = KEYMAPPINGS; this.keybindings = [ { // Move map - Including mouse @@ -115,7 +115,7 @@ export class HUDKeybindingOverlay extends BaseHUDPart { k.navigation.mapMoveDown, k.navigation.mapMoveRight, ], - condition: (): any => !this.anyPlacementActive, + condition: () => !this.anyPlacementActive, }, { // Move map - No mouse @@ -126,103 +126,103 @@ export class HUDKeybindingOverlay extends BaseHUDPart { k.navigation.mapMoveDown, k.navigation.mapMoveRight, ], - condition: (): any => this.anyPlacementActive, + condition: () => this.anyPlacementActive, }, { // [OVERVIEW] Create marker with right click label: T.ingame.keybindingsOverlay.createMarker, keys: [KEYCODE_RMB], - condition: (): any => this.mapOverviewActive && !this.blueprintPlacementActive, + condition: () => this.mapOverviewActive && !this.blueprintPlacementActive, }, { // Cancel placement label: T.ingame.keybindingsOverlay.stopPlacement, keys: [KEYCODE_RMB], - condition: (): any => this.anyPlacementActive, + condition: () => this.anyPlacementActive, }, { // Delete with right click label: T.ingame.keybindingsOverlay.delete, keys: [KEYCODE_RMB], - condition: (): any => !this.anyPlacementActive && !this.mapOverviewActive && !this.anythingSelectedOnMap, + condition: () => !this.anyPlacementActive && !this.mapOverviewActive && !this.anythingSelectedOnMap, }, { // Pipette label: T.ingame.keybindingsOverlay.pipette, keys: [k.placement.pipette], - condition: (): any => !this.mapOverviewActive && !this.blueprintPlacementActive, + condition: () => !this.mapOverviewActive && !this.blueprintPlacementActive, }, { // Area select label: T.ingame.keybindingsOverlay.selectBuildings, keys: [k.massSelect.massSelectStart, ADDER_TOKEN, KEYCODE_LMB], - condition: (): any => !this.anyPlacementActive && !this.anythingSelectedOnMap, + condition: () => !this.anyPlacementActive && !this.anythingSelectedOnMap, }, { // Place building label: T.ingame.keybindingsOverlay.placeBuilding, keys: [KEYCODE_LMB], - condition: (): any => this.anyPlacementActive, + condition: () => this.anyPlacementActive, }, { // Rotate label: T.ingame.keybindingsOverlay.rotateBuilding, keys: [k.placement.rotateWhilePlacing], - condition: (): any => this.anyPlacementActive && !this.beltPlannerActive, + condition: () => this.anyPlacementActive && !this.beltPlannerActive, }, { // [BELT PLANNER] Flip Side label: T.ingame.keybindingsOverlay.plannerSwitchSide, keys: [k.placement.switchDirectionLockSide], - condition: (): any => this.beltPlannerActive, + condition: () => this.beltPlannerActive, }, { // Place last blueprint label: T.ingame.keybindingsOverlay.pasteLastBlueprint, keys: [k.massSelect.pasteLastBlueprint], - condition: (): any => !this.blueprintPlacementActive && this.lastBlueprintAvailable, + condition: () => !this.blueprintPlacementActive && this.lastBlueprintAvailable, }, { // Belt planner label: T.ingame.keybindingsOverlay.lockBeltDirection, keys: [k.placementModifiers.lockBeltDirection], - condition: (): any => this.buildingPlacementSupportsBeltPlanner && !this.beltPlannerActive, + condition: () => this.buildingPlacementSupportsBeltPlanner && !this.beltPlannerActive, }, { // [SELECTION] Destroy label: T.ingame.keybindingsOverlay.delete, keys: [k.massSelect.confirmMassDelete], - condition: (): any => this.anythingSelectedOnMap, + condition: () => this.anythingSelectedOnMap, }, { // [SELECTION] Cancel label: T.ingame.keybindingsOverlay.clearSelection, keys: [k.general.back], - condition: (): any => this.anythingSelectedOnMap, + condition: () => this.anythingSelectedOnMap, }, { // [SELECTION] Cut label: T.ingame.keybindingsOverlay.cutSelection, keys: [k.massSelect.massSelectCut], - condition: (): any => this.anythingSelectedOnMap, + condition: () => this.anythingSelectedOnMap, }, { // [SELECTION] Copy label: T.ingame.keybindingsOverlay.copySelection, keys: [k.massSelect.massSelectCopy], - condition: (): any => this.anythingSelectedOnMap, + condition: () => this.anythingSelectedOnMap, }, { // [SELECTION] Clear label: T.ingame.keybindingsOverlay.clearBelts, keys: [k.massSelect.massSelectClear], - condition: (): any => this.anythingSelectedOnMap, + condition: () => this.anythingSelectedOnMap, }, { // Switch layers label: T.ingame.keybindingsOverlay.switchLayers, keys: [k.ingame.switchLayers], - condition: (): any => this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_wires_painter_and_levers), + condition: () => this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_wires_painter_and_levers), }, ]; if (!this.root.app.settings.getAllSettings().alwaysMultiplace) { @@ -230,15 +230,15 @@ export class HUDKeybindingOverlay extends BaseHUDPart { // Multiplace label: T.ingame.keybindingsOverlay.placeMultiple, keys: [k.placementModifiers.placeMultiple], - condition: (): any => this.anyPlacementActive && !this.buildingPlacementStaysInPlacement, + condition: () => this.anyPlacementActive && !this.buildingPlacementStaysInPlacement, }); } this.element = makeDiv(parent, "ingame_HUD_KeybindingOverlay", []); - for (let i: any = 0; i < this.keybindings.length; ++i) { - let html: any = ""; - const handle: any = this.keybindings[i]; - for (let k: any = 0; k < handle.keys.length; ++k) { - const key: any = handle.keys[k]; + for (let i = 0; i < this.keybindings.length; ++i) { + let html = ""; + const handle = this.keybindings[i]; + for (let k = 0; k < handle.keys.length; ++k) { + const key = handle.keys[k]; switch (key) { case KEYCODE_LMB: html += ``; @@ -264,15 +264,15 @@ export class HUDKeybindingOverlay extends BaseHUDPart { handle.cachedVisibility = false; } } - initialize(): any { + initialize() { this.domAttach = new DynamicDomAttach(this.root, this.element, { trackHover: true, }); } - update(): any { - for (let i: any = 0; i < this.keybindings.length; ++i) { - const handle: any = this.keybindings[i]; - const visibility: any = handle.condition(); + update() { + for (let i = 0; i < this.keybindings.length; ++i) { + const handle = this.keybindings[i]; + const visibility = handle.condition(); if (visibility !== handle.cachedVisibility) { handle.cachedVisibility = visibility; handle.cachedElement.classList.toggle("visible", visibility); diff --git a/src/ts/game/hud/parts/layer_preview.ts b/src/ts/game/hud/parts/layer_preview.ts index 50cc6e55..38dd719f 100644 --- a/src/ts/game/hud/parts/layer_preview.ts +++ b/src/ts/game/hud/parts/layer_preview.ts @@ -9,16 +9,16 @@ import { BaseHUDPart } from "../base_hud_part"; * Helper class which allows peaking through to the wires layer */ export class HUDLayerPreview extends BaseHUDPart { - initialize(): any { + initialize() { this.initializeCanvas(); - this.root.signals.aboutToDestruct.add((): any => freeCanvas(this.canvas)); + this.root.signals.aboutToDestruct.add(() => freeCanvas(this.canvas)); this.root.signals.resized.add(this.initializeCanvas, this); this.previewOverlay = Loader.getSprite("sprites/wires/wires_preview.png"); } /** * (re) initializes the canvas */ - initializeCanvas(): any { + initializeCanvas() { if (this.canvas) { freeCanvas(this.canvas); delete this.canvas; @@ -26,7 +26,7 @@ export class HUDLayerPreview extends BaseHUDPart { } // Compute how big the preview should be this.previewSize = Math.round(Math.min(1024, Math.min(this.root.gameWidth, this.root.gameHeight) * 0.8)); - const [canvas, context]: any = makeOffscreenBuffer(this.previewSize, this.previewSize, { + const [canvas, context] = makeOffscreenBuffer(this.previewSize, this.previewSize, { smooth: true, label: "layerPeeker", reusable: true, @@ -39,24 +39,24 @@ export class HUDLayerPreview extends BaseHUDPart { * Prepares the canvas to render at the given worldPos and the given camera scale * */ - prepareCanvasForPreview(worldPos: Vector, scale: number): any { + prepareCanvasForPreview(worldPos: Vector, scale: number) { this.context.clearRect(0, 0, this.previewSize, this.previewSize); this.context.fillStyle = THEME.map.wires.previewColor; this.context.fillRect(0, 0, this.previewSize, this.previewSize); - const dimensions: any = scale * this.previewSize; - const startWorldX: any = worldPos.x - dimensions / 2; - const startWorldY: any = worldPos.y - dimensions / 2; - const startTileX: any = Math.floor(startWorldX / globalConfig.tileSize); - const startTileY: any = Math.floor(startWorldY / globalConfig.tileSize); - const tileDimensions: any = Math.ceil(dimensions / globalConfig.tileSize); + const dimensions = scale * this.previewSize; + const startWorldX = worldPos.x - dimensions / 2; + const startWorldY = worldPos.y - dimensions / 2; + const startTileX = Math.floor(startWorldX / globalConfig.tileSize); + const startTileY = Math.floor(startWorldY / globalConfig.tileSize); + const tileDimensions = Math.ceil(dimensions / globalConfig.tileSize); this.context.save(); this.context.scale(1 / scale, 1 / scale); this.context.translate(startTileX * globalConfig.tileSize - startWorldX, startTileY * globalConfig.tileSize - startWorldY); - for (let dx: any = 0; dx < tileDimensions; ++dx) { - for (let dy: any = 0; dy < tileDimensions; ++dy) { - const tileX: any = dx + startTileX; - const tileY: any = dy + startTileY; - const content: any = this.root.map.getLayerContentXY(tileX, tileY, "wires"); + for (let dx = 0; dx < tileDimensions; ++dx) { + for (let dy = 0; dy < tileDimensions; ++dy) { + const tileX = dx + startTileX; + const tileY = dy + startTileY; + const content = this.root.map.getLayerContentXY(tileX, tileY, "wires"); if (content) { MapChunkView.drawSingleWiresOverviewTile({ context: this.context, @@ -77,12 +77,12 @@ export class HUDLayerPreview extends BaseHUDPart { /** * Renders the preview at the given position */ - renderPreview(parameters: import("../../../core/draw_utils").DrawParameters, worldPos: Vector, scale: number): any { + renderPreview(parameters: import("../../../core/draw_utils").DrawParameters, worldPos: Vector, scale: number) { if (this.root.currentLayer !== "regular") { // Only supporting wires right now return; } - const canvas: any = this.prepareCanvasForPreview(worldPos, scale); + const canvas = this.prepareCanvasForPreview(worldPos, scale); parameters.context.globalAlpha = 0.3; parameters.context.drawImage(canvas, worldPos.x - (scale * this.previewSize) / 2, worldPos.y - (scale * this.previewSize) / 2, scale * this.previewSize, scale * this.previewSize); parameters.context.globalAlpha = 1; diff --git a/src/ts/game/hud/parts/lever_toggle.ts b/src/ts/game/hud/parts/lever_toggle.ts index 3cfb0c65..2f19dc66 100644 --- a/src/ts/game/hud/parts/lever_toggle.ts +++ b/src/ts/game/hud/parts/lever_toggle.ts @@ -3,14 +3,14 @@ import { Vector } from "../../../core/vector"; import { enumMouseButton } from "../../camera"; import { BaseHUDPart } from "../base_hud_part"; export class HUDLeverToggle extends BaseHUDPart { - initialize(): any { + initialize() { this.root.camera.downPreHandler.add(this.downPreHandler, this); } - downPreHandler(pos: Vector, button: enumMouseButton): any { - const tile: any = this.root.camera.screenToWorld(pos).toTileSpace(); - const contents: any = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); + downPreHandler(pos: Vector, button: enumMouseButton) { + const tile = this.root.camera.screenToWorld(pos).toTileSpace(); + const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); if (contents) { - const leverComp: any = contents.components.Lever; + const leverComp = contents.components.Lever; if (leverComp) { if (button === enumMouseButton.left) { leverComp.toggled = !leverComp.toggled; diff --git a/src/ts/game/hud/parts/mass_selector.ts b/src/ts/game/hud/parts/mass_selector.ts index 30ea02b6..ecd2855f 100644 --- a/src/ts/game/hud/parts/mass_selector.ts +++ b/src/ts/game/hud/parts/mass_selector.ts @@ -13,10 +13,10 @@ import { KEYMAPPINGS } from "../../key_action_mapper"; import { THEME } from "../../theme"; import { enumHubGoalRewards } from "../../tutorial_goals"; import { BaseHUDPart } from "../base_hud_part"; -const logger: any = createLogger("hud/mass_selector"); +const logger = createLogger("hud/mass_selector"); export class HUDMassSelector extends BaseHUDPart { - createElements(parent: any): any { } - initialize(): any { + createElements(parent) { } + initialize() { this.currentSelectionStartWorld = null; this.currentSelectionEnd = null; this.selectedUids = new Set(); @@ -38,14 +38,14 @@ export class HUDMassSelector extends BaseHUDPart { /** * Handles the destroy callback and makes sure we clean our list */ - onEntityDestroyed(entity: Entity): any { + onEntityDestroyed(entity: Entity) { if (this.root.bulkOperationRunning) { return; } this.selectedUids.delete(entity.uid); } - onBack(): any { + onBack() { // Clear entities on escape if (this.selectedUids.size > 0) { this.selectedUids = new Set(); @@ -55,28 +55,28 @@ export class HUDMassSelector extends BaseHUDPart { /** * Clears the entire selection */ - clearSelection(): any { + clearSelection() { this.selectedUids = new Set(); } - confirmDelete(): any { + confirmDelete() { if (!this.root.app.settings.getAllSettings().disableCutDeleteWarnings && this.selectedUids.size > 100) { - const { ok }: any = this.root.hud.parts.dialogs.showWarning(T.dialogs.massDeleteConfirm.title, T.dialogs.massDeleteConfirm.desc.replace("", "" + formatBigNumberFull(this.selectedUids.size)), ["cancel:good:escape", "ok:bad:enter"]); - ok.add((): any => this.doDelete()); + const { ok } = this.root.hud.parts.dialogs.showWarning(T.dialogs.massDeleteConfirm.title, T.dialogs.massDeleteConfirm.desc.replace("", "" + formatBigNumberFull(this.selectedUids.size)), ["cancel:good:escape", "ok:bad:enter"]); + ok.add(() => this.doDelete()); } else { this.doDelete(); } } - doDelete(): any { - const entityUids: any = Array.from(this.selectedUids); + doDelete() { + const entityUids = Array.from(this.selectedUids); // Build mapping from uid to entity const mapUidToEntity: Map = this.root.entityMgr.getFrozenUidSearchMap(); - let count: any = 0; - this.root.logic.performBulkOperation((): any => { - for (let i: any = 0; i < entityUids.length; ++i) { - const uid: any = entityUids[i]; - const entity: any = mapUidToEntity.get(uid); + let count = 0; + this.root.logic.performBulkOperation(() => { + for (let i = 0; i < entityUids.length; ++i) { + const uid = entityUids[i]; + const entity = mapUidToEntity.get(uid); if (!entity) { logger.error("Entity not found by uid:", uid); continue; @@ -93,10 +93,10 @@ export class HUDMassSelector extends BaseHUDPart { // Clear uids later this.selectedUids = new Set(); } - showBlueprintsNotUnlocked(): any { + showBlueprintsNotUnlocked() { this.root.hud.parts.dialogs.showInfo(T.dialogs.blueprintsNotUnlocked.title, T.dialogs.blueprintsNotUnlocked.desc); } - startCopy(): any { + startCopy() { if (this.selectedUids.size > 0) { if (!this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) { this.showBlueprintsNotUnlocked(); @@ -110,49 +110,49 @@ export class HUDMassSelector extends BaseHUDPart { this.root.soundProxy.playUiError(); } } - clearBelts(): any { - for (const uid: any of this.selectedUids) { - const entity: any = this.root.entityMgr.findByUid(uid); - for (const component: any of Object.values(entity.components)) { + clearBelts() { + for (const uid of this.selectedUids) { + const entity = this.root.entityMgr.findByUid(uid); + for (const component of Object.values(entity.components)) { component as Component).clear(); } } this.selectedUids = new Set(); } - confirmCut(): any { + confirmCut() { if (!this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) { this.showBlueprintsNotUnlocked(); } else if (!this.root.app.settings.getAllSettings().disableCutDeleteWarnings && this.selectedUids.size > 100) { - const { ok }: any = this.root.hud.parts.dialogs.showWarning(T.dialogs.massCutConfirm.title, T.dialogs.massCutConfirm.desc.replace("", "" + formatBigNumberFull(this.selectedUids.size)), ["cancel:good:escape", "ok:bad:enter"]); - ok.add((): any => this.doCut()); + const { ok } = this.root.hud.parts.dialogs.showWarning(T.dialogs.massCutConfirm.title, T.dialogs.massCutConfirm.desc.replace("", "" + formatBigNumberFull(this.selectedUids.size)), ["cancel:good:escape", "ok:bad:enter"]); + ok.add(() => this.doCut()); } else { this.doCut(); } } - doCut(): any { + doCut() { if (this.selectedUids.size > 0) { - const entityUids: any = Array.from(this.selectedUids); - const cutAction: any = (): any => { + const entityUids = Array.from(this.selectedUids); + const cutAction = () => { // copy code relies on entities still existing, so must copy before deleting. this.root.hud.signals.buildingsSelectedForCopy.dispatch(entityUids); - for (let i: any = 0; i < entityUids.length; ++i) { - const uid: any = entityUids[i]; - const entity: any = this.root.entityMgr.findByUid(uid); + for (let i = 0; i < entityUids.length; ++i) { + const uid = entityUids[i]; + const entity = this.root.entityMgr.findByUid(uid); if (!this.root.logic.tryDeleteBuilding(entity)) { logger.error("Error in mass cut, could not remove building"); this.selectedUids.delete(uid); } } }; - const blueprint: any = Blueprint.fromUids(this.root, entityUids); + const blueprint = Blueprint.fromUids(this.root, entityUids); if (blueprint.canAfford(this.root)) { cutAction(); } else { - const { cancel, ok }: any = this.root.hud.parts.dialogs.showWarning(T.dialogs.massCutInsufficientConfirm.title, T.dialogs.massCutInsufficientConfirm.desc, ["cancel:good:escape", "ok:bad:enter"]); + const { cancel, ok } = this.root.hud.parts.dialogs.showWarning(T.dialogs.massCutInsufficientConfirm.title, T.dialogs.massCutInsufficientConfirm.desc, ["cancel:good:escape", "ok:bad:enter"]); ok.add(cutAction); } this.root.soundProxy.playUiClick(); @@ -164,7 +164,7 @@ export class HUDMassSelector extends BaseHUDPart { /** * mouse down pre handler */ - onMouseDown(pos: Vector, mouseButton: enumMouseButton): any { + onMouseDown(pos: Vector, mouseButton: enumMouseButton) { if (!this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectStart).pressed) { return; } @@ -182,24 +182,24 @@ export class HUDMassSelector extends BaseHUDPart { /** * mouse move pre handler */ - onMouseMove(pos: Vector): any { + onMouseMove(pos: Vector) { if (this.currentSelectionStartWorld) { this.currentSelectionEnd = pos.copy(); } } - onMouseUp(): any { + onMouseUp() { if (this.currentSelectionStartWorld) { - const worldStart: any = this.currentSelectionStartWorld; - const worldEnd: any = this.root.camera.screenToWorld(this.currentSelectionEnd); - const tileStart: any = worldStart.toTileSpace(); - const tileEnd: any = worldEnd.toTileSpace(); - const realTileStart: any = tileStart.min(tileEnd); - const realTileEnd: any = tileStart.max(tileEnd); - for (let x: any = realTileStart.x; x <= realTileEnd.x; ++x) { - for (let y: any = realTileStart.y; y <= realTileEnd.y; ++y) { - const contents: any = this.root.map.getLayerContentXY(x, y, this.root.currentLayer); + const worldStart = this.currentSelectionStartWorld; + const worldEnd = this.root.camera.screenToWorld(this.currentSelectionEnd); + const tileStart = worldStart.toTileSpace(); + const tileEnd = worldEnd.toTileSpace(); + const realTileStart = tileStart.min(tileEnd); + const realTileEnd = tileStart.max(tileEnd); + for (let x = realTileStart.x; x <= realTileEnd.x; ++x) { + for (let y = realTileStart.y; y <= realTileEnd.y; ++y) { + const contents = this.root.map.getLayerContentXY(x, y, this.root.currentLayer); if (contents && this.root.logic.canDeleteBuilding(contents)) { - const staticComp: any = contents.components.StaticMapEntity; + const staticComp = contents.components.StaticMapEntity; if (!staticComp.getMetaBuilding().getIsRemovable(this.root)) { continue; } @@ -211,17 +211,17 @@ export class HUDMassSelector extends BaseHUDPart { this.currentSelectionEnd = null; } } - draw(parameters: DrawParameters): any { - const boundsBorder: any = 2; + draw(parameters: DrawParameters) { + const boundsBorder = 2; if (this.currentSelectionStartWorld) { - const worldStart: any = this.currentSelectionStartWorld; - const worldEnd: any = this.root.camera.screenToWorld(this.currentSelectionEnd); - const realWorldStart: any = worldStart.min(worldEnd); - const realWorldEnd: any = worldStart.max(worldEnd); - const tileStart: any = worldStart.toTileSpace(); - const tileEnd: any = worldEnd.toTileSpace(); - const realTileStart: any = tileStart.min(tileEnd); - const realTileEnd: any = tileStart.max(tileEnd); + const worldStart = this.currentSelectionStartWorld; + const worldEnd = this.root.camera.screenToWorld(this.currentSelectionEnd); + const realWorldStart = worldStart.min(worldEnd); + const realWorldEnd = worldStart.max(worldEnd); + const tileStart = worldStart.toTileSpace(); + const tileEnd = worldEnd.toTileSpace(); + const realTileStart = tileStart.min(tileEnd); + const realTileEnd = tileStart.max(tileEnd); parameters.context.lineWidth = 1; parameters.context.fillStyle = THEME.map.selectionBackground; parameters.context.strokeStyle = THEME.map.selectionOutline; @@ -231,22 +231,22 @@ export class HUDMassSelector extends BaseHUDPart { parameters.context.stroke(); parameters.context.fillStyle = THEME.map.selectionOverlay; parameters.context.beginPath(); - const renderedUids: any = new Set(); - for (let x: any = realTileStart.x; x <= realTileEnd.x; ++x) { - for (let y: any = realTileStart.y; y <= realTileEnd.y; ++y) { - const contents: any = this.root.map.getLayerContentXY(x, y, this.root.currentLayer); + const renderedUids = new Set(); + for (let x = realTileStart.x; x <= realTileEnd.x; ++x) { + for (let y = realTileStart.y; y <= realTileEnd.y; ++y) { + const contents = this.root.map.getLayerContentXY(x, y, this.root.currentLayer); if (contents && this.root.logic.canDeleteBuilding(contents)) { // Prevent rendering the overlay twice - const uid: any = contents.uid; + const uid = contents.uid; if (renderedUids.has(uid)) { continue; } renderedUids.add(uid); - const staticComp: any = contents.components.StaticMapEntity; + const staticComp = contents.components.StaticMapEntity; if (!staticComp.getMetaBuilding().getIsRemovable(this.root)) { continue; } - const bounds: any = staticComp.getTileSpaceBounds(); + const bounds = staticComp.getTileSpaceBounds(); parameters.context.rect(bounds.x * globalConfig.tileSize + boundsBorder, bounds.y * globalConfig.tileSize + boundsBorder, bounds.w * globalConfig.tileSize - 2 * boundsBorder, bounds.h * globalConfig.tileSize - 2 * boundsBorder); } } @@ -255,10 +255,10 @@ export class HUDMassSelector extends BaseHUDPart { } parameters.context.fillStyle = THEME.map.selectionOverlay; parameters.context.beginPath(); - this.selectedUids.forEach((uid: any): any => { - const entity: any = this.root.entityMgr.findByUid(uid); - const staticComp: any = entity.components.StaticMapEntity; - const bounds: any = staticComp.getTileSpaceBounds(); + this.selectedUids.forEach(uid => { + const entity = this.root.entityMgr.findByUid(uid); + const staticComp = entity.components.StaticMapEntity; + const bounds = staticComp.getTileSpaceBounds(); parameters.context.rect(bounds.x * globalConfig.tileSize + boundsBorder, bounds.y * globalConfig.tileSize + boundsBorder, bounds.w * globalConfig.tileSize - 2 * boundsBorder, bounds.h * globalConfig.tileSize - 2 * boundsBorder); }); parameters.context.fill(); diff --git a/src/ts/game/hud/parts/miner_highlight.ts b/src/ts/game/hud/parts/miner_highlight.ts index 5d95bd2c..be77b888 100644 --- a/src/ts/game/hud/parts/miner_highlight.ts +++ b/src/ts/game/hud/parts/miner_highlight.ts @@ -6,9 +6,9 @@ import { Entity } from "../../entity"; import { THEME } from "../../theme"; import { BaseHUDPart } from "../base_hud_part"; export class HUDMinerHighlight extends BaseHUDPart { - initialize(): any { } - draw(parameters: import("../../../core/draw_utils").DrawParameters): any { - const mousePos: any = this.root.app.mousePosition; + initialize() { } + draw(parameters: import("../../../core/draw_utils").DrawParameters) { + const mousePos = this.root.app.mousePosition; if (!mousePos) { // Mouse pos not ready return; @@ -21,36 +21,36 @@ export class HUDMinerHighlight extends BaseHUDPart { // Not within the map overlay return; } - const worldPos: any = this.root.camera.screenToWorld(mousePos); - const hoveredTile: any = worldPos.toTileSpace(); - const contents: any = this.root.map.getTileContent(hoveredTile, "regular"); + const worldPos = this.root.camera.screenToWorld(mousePos); + const hoveredTile = worldPos.toTileSpace(); + const contents = this.root.map.getTileContent(hoveredTile, "regular"); if (!contents) { // Empty tile return; } - const minerComp: any = contents.components.Miner; + const minerComp = contents.components.Miner; if (!minerComp || !minerComp.chainable) { // Not a chainable miner return; } - const lowerContents: any = this.root.map.getLowerLayerContentXY(hoveredTile.x, hoveredTile.y); + const lowerContents = this.root.map.getLowerLayerContentXY(hoveredTile.x, hoveredTile.y); if (!lowerContents) { // Not connected return; } parameters.context.fillStyle = THEME.map.connectedMiners.overlay; - const connectedEntities: any = this.findConnectedMiners(contents); - for (let i: any = 0; i < connectedEntities.length; ++i) { - const entity: any = connectedEntities[i]; - const staticComp: any = entity.components.StaticMapEntity; + const connectedEntities = this.findConnectedMiners(contents); + for (let i = 0; i < connectedEntities.length; ++i) { + const entity = connectedEntities[i]; + const staticComp = entity.components.StaticMapEntity; parameters.context.beginRoundedRect(staticComp.origin.x * globalConfig.tileSize + 5, staticComp.origin.y * globalConfig.tileSize + 5, globalConfig.tileSize - 10, globalConfig.tileSize - 10, 3); parameters.context.fill(); } - const throughput: any = round2Digits(connectedEntities.length * this.root.hubGoals.getMinerBaseSpeed()); - const maxThroughput: any = this.root.hubGoals.getBeltBaseSpeed(); - const tooltipLocation: any = this.root.camera.screenToWorld(mousePos); - const scale: any = (1 / this.root.camera.zoomLevel) * this.root.app.getEffectiveUiScale(); - const isCapped: any = throughput > maxThroughput; + const throughput = round2Digits(connectedEntities.length * this.root.hubGoals.getMinerBaseSpeed()); + const maxThroughput = this.root.hubGoals.getBeltBaseSpeed(); + const tooltipLocation = this.root.camera.screenToWorld(mousePos); + const scale = (1 / this.root.camera.zoomLevel) * this.root.app.getEffectiveUiScale(); + const isCapped = throughput > maxThroughput; // Background parameters.context.fillStyle = THEME.map.connectedMiners.background; parameters.context.beginRoundedRect(tooltipLocation.x + 5 * scale, tooltipLocation.y - 3 * scale, (isCapped ? 100 : 65) * scale, (isCapped ? 45 : 30) * scale, 2); @@ -76,25 +76,25 @@ export class HUDMinerHighlight extends BaseHUDPart { * {} The connected miners */ findConnectedMiners(entity: Entity, seenUids: Set = new Set()): Array { - let results: any = []; - const origin: any = entity.components.StaticMapEntity.origin; + let results = []; + const origin = entity.components.StaticMapEntity.origin; if (!seenUids.has(entity.uid)) { seenUids.add(entity.uid); results.push(entity); } // Check for the miner which we connect to - const connectedMiner: any = this.root.systemMgr.systems.miner.findChainedMiner(entity); + const connectedMiner = this.root.systemMgr.systems.miner.findChainedMiner(entity); if (connectedMiner && !seenUids.has(connectedMiner.uid)) { results.push(connectedMiner); seenUids.add(connectedMiner.uid); results.push(...this.findConnectedMiners(connectedMiner, seenUids)); } // Search within a 1x1 grid - this assumes miners are always 1x1 - for (let dx: any = -1; dx <= 1; ++dx) { - for (let dy: any = -1; dy <= 1; ++dy) { - const contents: any = this.root.map.getTileContent(new Vector(origin.x + dx, origin.y + dy), "regular"); + for (let dx = -1; dx <= 1; ++dx) { + for (let dy = -1; dy <= 1; ++dy) { + const contents = this.root.map.getTileContent(new Vector(origin.x + dx, origin.y + dy), "regular"); if (contents) { - const minerComp: any = contents.components.Miner; + const minerComp = contents.components.Miner; if (minerComp && minerComp.chainable) { // Found a miner connected to this entity if (!seenUids.has(contents.uid)) { diff --git a/src/ts/game/hud/parts/modal_dialogs.ts b/src/ts/game/hud/parts/modal_dialogs.ts index 53948324..6973aed2 100644 --- a/src/ts/game/hud/parts/modal_dialogs.ts +++ b/src/ts/game/hud/parts/modal_dialogs.ts @@ -18,33 +18,33 @@ export class HUDModalDialogs extends BaseHUDPart { super(root); } // For use inside of the game, implementation of base hud part - initialize(): any { + initialize() { this.dialogParent = document.getElementById("ingame_HUD_ModalDialogs"); this.domWatcher = new DynamicDomAttach(this.root, this.dialogParent); } - shouldPauseRendering(): any { + shouldPauseRendering() { // return this.dialogStack.length > 0; // @todo: Check if change this affects anything return false; } - shouldPauseGame(): any { + shouldPauseGame() { // @todo: Check if this change affects anything return false; } - createElements(parent: any): any { + createElements(parent) { return makeDiv(parent, "ingame_HUD_ModalDialogs"); } // For use outside of the game - initializeToElement(element: any): any { + initializeToElement(element) { assert(element, "No element for dialogs given"); this.dialogParent = element; } - isBlockingOverlay(): any { + isBlockingOverlay() { return this.dialogStack.length > 0; } // Methods - showInfo(title: string, text: string, buttons: Array = ["ok:good"]): any { - const dialog: any = new Dialog({ + showInfo(title: string, text: string, buttons: Array = ["ok:good"]) { + const dialog = new Dialog({ app: this.app, title: title, contentHTML: text, @@ -57,8 +57,8 @@ export class HUDModalDialogs extends BaseHUDPart { } return dialog.buttonSignals; } - showWarning(title: string, text: string, buttons: Array = ["ok:good"]): any { - const dialog: any = new Dialog({ + showWarning(title: string, text: string, buttons: Array = ["ok:good"]) { + const dialog = new Dialog({ app: this.app, title: title, contentHTML: text, @@ -71,8 +71,8 @@ export class HUDModalDialogs extends BaseHUDPart { } return dialog.buttonSignals; } - showFeatureRestrictionInfo(feature: string, textPrefab: string = T.dialogs.featureRestriction.desc): any { - const dialog: any = new Dialog({ + showFeatureRestrictionInfo(feature: string, textPrefab: string = T.dialogs.featureRestriction.desc) { + const dialog = new Dialog({ app: this.app, title: T.dialogs.featureRestriction.title, contentHTML: textPrefab.replace("", feature), @@ -83,13 +83,13 @@ export class HUDModalDialogs extends BaseHUDPart { if (this.app) { this.app.sound.playUiSound(SOUNDS.dialogOk); } - dialog.buttonSignals.getStandalone.add((): any => { + dialog.buttonSignals.getStandalone.add(() => { openStandaloneLink(this.app, "shapez_demo_dialog"); }); return dialog.buttonSignals; } - showOptionChooser(title: any, options: any): any { - const dialog: any = new DialogOptionChooser({ + showOptionChooser(title, options) { + const dialog = new DialogOptionChooser({ app: this.app, title, options, @@ -98,13 +98,13 @@ export class HUDModalDialogs extends BaseHUDPart { return dialog.buttonSignals; } // Returns method to be called when laoding finishd - showLoadingDialog(text: any = ""): any { - const dialog: any = new DialogLoading(this.app, text); + showLoadingDialog(text = "") { + const dialog = new DialogLoading(this.app, text); this.internalShowDialog(dialog); return this.closeDialog.bind(this, dialog); } - internalShowDialog(dialog: any): any { - const elem: any = dialog.createElement(); + internalShowDialog(dialog) { + const elem = dialog.createElement(); dialog.setIndex(1000 + this.dialogStack.length); // Hide last dialog in queue if (this.dialogStack.length > 0) { @@ -120,15 +120,15 @@ export class HUDModalDialogs extends BaseHUDPart { // IMPORTANT: Attach element directly, otherwise double submit is possible this.update(); } - update(): any { + update() { if (this.domWatcher) { this.domWatcher.update(this.dialogStack.length > 0); } } - closeDialog(dialog: any): any { + closeDialog(dialog) { dialog.destroy(); - let index: any = -1; - for (let i: any = 0; i < this.dialogStack.length; ++i) { + let index = -1; + for (let i = 0; i < this.dialogStack.length; ++i) { if (this.dialogStack[i] === dialog) { index = i; break; @@ -142,16 +142,16 @@ export class HUDModalDialogs extends BaseHUDPart { } document.body.classList.toggle("modalDialogActive", this.dialogStack.length > 0); } - close(): any { - for (let i: any = 0; i < this.dialogStack.length; ++i) { - const dialog: any = this.dialogStack[i]; + close() { + for (let i = 0; i < this.dialogStack.length; ++i) { + const dialog = this.dialogStack[i]; dialog.destroy(); } this.dialogStack = []; } - cleanup(): any { + cleanup() { super.cleanup(); - for (let i: any = 0; i < this.dialogStack.length; ++i) { + for (let i = 0; i < this.dialogStack.length; ++i) { this.dialogStack[i].destroy(); } this.dialogStack = []; diff --git a/src/ts/game/hud/parts/next_puzzle.ts b/src/ts/game/hud/parts/next_puzzle.ts index dd56d447..86102e85 100644 --- a/src/ts/game/hud/parts/next_puzzle.ts +++ b/src/ts/game/hud/parts/next_puzzle.ts @@ -5,7 +5,7 @@ import { makeDiv } from "../../../core/utils"; import { T } from "../../../translations"; import { BaseHUDPart } from "../base_hud_part"; export class HUDPuzzleNextPuzzle extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_PuzzleNextPuzzle"); this.button = document.createElement("button"); this.button.classList.add("button"); @@ -13,9 +13,9 @@ export class HUDPuzzleNextPuzzle extends BaseHUDPart { this.element.appendChild(this.button); this.trackClicks(this.button, this.nextPuzzle); } - initialize(): any { } - nextPuzzle(): any { - const gameMode: any = (this.root.gameMode as PuzzlePlayGameMode); + initialize() { } + nextPuzzle() { + const gameMode = this.root.gameMode as PuzzlePlayGameMode); this.root.gameState.moveToState("PuzzleMenuState", { continueQueue: gameMode.nextPuzzles, }); diff --git a/src/ts/game/hud/parts/notifications.ts b/src/ts/game/hud/parts/notifications.ts index 42844242..21452bec 100644 --- a/src/ts/game/hud/parts/notifications.ts +++ b/src/ts/game/hud/parts/notifications.ts @@ -2,7 +2,7 @@ import { makeDiv } from "../../../core/utils"; import { T } from "../../../translations"; import { BaseHUDPart } from "../base_hud_part"; /** @enum {string} */ -export const enumNotificationType: any = { +export const enumNotificationType = { saved: "saved", upgrade: "upgrade", success: "success", @@ -10,29 +10,29 @@ export const enumNotificationType: any = { warning: "warning", error: "error", }; -const notificationDuration: any = 3; +const notificationDuration = 3; export class HUDNotifications extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_Notifications", [], ``); } - initialize(): any { + initialize() { this.root.hud.signals.notification.add(this.internalShowNotification, this); this.notificationElements = []; // Automatic notifications - this.root.signals.gameSaved.add((): any => this.internalShowNotification(T.ingame.notifications.gameSaved, enumNotificationType.saved)); + this.root.signals.gameSaved.add(() => this.internalShowNotification(T.ingame.notifications.gameSaved, enumNotificationType.saved)); } - internalShowNotification(message: string, type: enumNotificationType): any { - const element: any = makeDiv(this.element, null, ["notification", "type-" + type], message); + internalShowNotification(message: string, type: enumNotificationType) { + const element = makeDiv(this.element, null, ["notification", "type-" + type], message); element.setAttribute("data-icon", "icons/notification_" + type + ".png"); this.notificationElements.push({ element, expireAt: this.root.time.realtimeNow() + notificationDuration, }); } - update(): any { - const now: any = this.root.time.realtimeNow(); - for (let i: any = 0; i < this.notificationElements.length; ++i) { - const handle: any = this.notificationElements[i]; + update() { + const now = this.root.time.realtimeNow(); + for (let i = 0; i < this.notificationElements.length; ++i) { + const handle = this.notificationElements[i]; if (handle.expireAt <= now) { handle.element.remove(); this.notificationElements.splice(i, 1); diff --git a/src/ts/game/hud/parts/pinned_shapes.ts b/src/ts/game/hud/parts/pinned_shapes.ts index 0a97a5c7..6bb1068b 100644 --- a/src/ts/game/hud/parts/pinned_shapes.ts +++ b/src/ts/game/hud/parts/pinned_shapes.ts @@ -25,13 +25,13 @@ export class HUDPinnedShapes extends BaseHUDPart { constructor(root) { super(root); } - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_PinnedShapes", []); } /** * Serializes the pinned shapes */ - serialize(): any { + serialize() { return { shapes: this.pinnedShapes, }; @@ -41,7 +41,7 @@ export class HUDPinnedShapes extends BaseHUDPart { */ deserialize(data: { shapes: Array; - }): any { + }) { if (!data || !data.shapes || !Array.isArray(data.shapes)) { return "Invalid pinned shapes data: " + JSON.stringify(data); } @@ -50,7 +50,7 @@ export class HUDPinnedShapes extends BaseHUDPart { /** * Initializes the hud component */ - initialize(): any { + initialize() { // Connect to any relevant signals this.root.signals.storyGoalCompleted.add(this.rerenderFull, this); this.root.signals.upgradePurchased.add(this.updateShapesAfterUpgrade, this); @@ -63,14 +63,14 @@ export class HUDPinnedShapes extends BaseHUDPart { /** * Updates all shapes after an upgrade has been purchased and removes the unused ones */ - updateShapesAfterUpgrade(): any { - for (let i: any = 0; i < this.pinnedShapes.length; ++i) { - const key: any = this.pinnedShapes[i]; + updateShapesAfterUpgrade() { + for (let i = 0; i < this.pinnedShapes.length; ++i) { + const key = this.pinnedShapes[i]; if (key === this.root.gameMode.getBlueprintShapeKey()) { // Ignore blueprint shapes continue; } - let goal: any = this.findGoalValueForShape(key); + let goal = this.findGoalValueForShape(key); if (!goal) { // Seems no longer relevant this.pinnedShapes.splice(i, 1); @@ -84,7 +84,7 @@ export class HUDPinnedShapes extends BaseHUDPart { * the story goal. If its the blueprint shape, no goal is returned. Otherwise * it's searched for upgrades. */ - findGoalValueForShape(key: string): any { + findGoalValueForShape(key: string) { if (key === this.root.hubGoals.currentGoal.definition.getHash()) { return this.root.hubGoals.currentGoal.required; } @@ -92,17 +92,17 @@ export class HUDPinnedShapes extends BaseHUDPart { return null; } // Check if this shape is required for any upgrade - const upgrades: any = this.root.gameMode.getUpgrades(); - for (const upgradeId: any in upgrades) { - const upgradeTiers: any = upgrades[upgradeId]; - const currentTier: any = this.root.hubGoals.getUpgradeLevel(upgradeId); - const tierHandle: any = upgradeTiers[currentTier]; + const upgrades = this.root.gameMode.getUpgrades(); + for (const upgradeId in upgrades) { + const upgradeTiers = upgrades[upgradeId]; + const currentTier = this.root.hubGoals.getUpgradeLevel(upgradeId); + const tierHandle = upgradeTiers[currentTier]; if (!tierHandle) { // Max level continue; } - for (let i: any = 0; i < tierHandle.required.length; ++i) { - const { shape, amount }: any = tierHandle.required[i]; + for (let i = 0; i < tierHandle.required.length; ++i) { + const { shape, amount } = tierHandle.required[i]; if (shape === key) { return amount; } @@ -113,7 +113,7 @@ export class HUDPinnedShapes extends BaseHUDPart { /** * Returns whether a given shape is currently pinned */ - isShapePinned(key: string): any { + isShapePinned(key: string) { if (key === this.root.hubGoals.currentGoal.definition.getHash() || key === this.root.gameMode.getBlueprintShapeKey()) { // This is a "special" shape which is always pinned @@ -124,17 +124,17 @@ export class HUDPinnedShapes extends BaseHUDPart { /** * Rerenders the whole component */ - rerenderFull(): any { - const currentGoal: any = this.root.hubGoals.currentGoal; - const currentKey: any = currentGoal.definition.getHash(); + rerenderFull() { + const currentGoal = this.root.hubGoals.currentGoal; + const currentKey = currentGoal.definition.getHash(); // First, remove all old shapes - for (let i: any = 0; i < this.handles.length; ++i) { + for (let i = 0; i < this.handles.length; ++i) { this.handles[i].element.remove(); - const detector: any = this.handles[i].detector; + const detector = this.handles[i].detector; if (detector) { detector.cleanup(); } - const infoDetector: any = this.handles[i].infoDetector; + const infoDetector = this.handles[i].infoDetector; if (infoDetector) { infoDetector.cleanup(); } @@ -156,8 +156,8 @@ export class HUDPinnedShapes extends BaseHUDPart { }); } // Pin manually pinned shapes - for (let i: any = 0; i < this.pinnedShapes.length; ++i) { - const key: any = this.pinnedShapes[i]; + for (let i = 0; i < this.pinnedShapes.length; ++i) { + const key = this.pinnedShapes[i]; if (key !== currentKey) { this.internalPinShape({ key }); } @@ -171,17 +171,17 @@ export class HUDPinnedShapes extends BaseHUDPart { canUnpin: boolean=; className: string=; throughputOnly: boolean=; - }): any { - const definition: any = this.root.shapeDefinitionMgr.getShapeFromShortKey(key); - const element: any = makeDiv(this.element, null, ["shape"]); - const canvas: any = definition.generateAsCanvas(120); + }) { + const definition = this.root.shapeDefinitionMgr.getShapeFromShortKey(key); + const element = makeDiv(this.element, null, ["shape"]); + const canvas = definition.generateAsCanvas(120); element.appendChild(canvas); if (className) { element.classList.add(className); } - let detector: any = null; + let detector = null; if (canUnpin) { - const unpinButton: any = document.createElement("button"); + const unpinButton = document.createElement("button"); unpinButton.classList.add("unpinButton"); element.appendChild(unpinButton); element.classList.add("removable"); @@ -190,14 +190,14 @@ export class HUDPinnedShapes extends BaseHUDPart { preventDefault: true, targetOnly: true, }); - detector.click.add((): any => this.unpinShape(key)); + detector.click.add(() => this.unpinShape(key)); } else { element.classList.add("marked"); } // Show small info icon - let infoDetector: any; - const infoButton: any = document.createElement("button"); + let infoDetector; + const infoButton = document.createElement("button"); infoButton.classList.add("infoButton"); element.appendChild(infoButton); infoDetector = new ClickDetector(infoButton, { @@ -205,9 +205,9 @@ export class HUDPinnedShapes extends BaseHUDPart { preventDefault: true, targetOnly: true, }); - infoDetector.click.add((): any => this.root.hud.signals.viewShapeDetailsRequested.dispatch(definition)); - const amountLabel: any = makeDiv(element, null, ["amountLabel"], ""); - const goal: any = this.findGoalValueForShape(key); + infoDetector.click.add(() => this.root.hud.signals.viewShapeDetailsRequested.dispatch(definition)); + const amountLabel = makeDiv(element, null, ["amountLabel"], ""); + const goal = this.findGoalValueForShape(key); if (goal) { makeDiv(element, null, ["goalLabel"], "/" + formatBigNumber(goal)); } @@ -225,11 +225,11 @@ export class HUDPinnedShapes extends BaseHUDPart { /** * Updates all amount labels */ - update(): any { - for (let i: any = 0; i < this.handles.length; ++i) { - const handle: any = this.handles[i]; - let currentValue: any = this.root.hubGoals.getShapesStoredByKey(handle.key); - let currentValueFormatted: any = formatBigNumber(currentValue); + update() { + for (let i = 0; i < this.handles.length; ++i) { + const handle = this.handles[i]; + let currentValue = this.root.hubGoals.getShapesStoredByKey(handle.key); + let currentValueFormatted = formatBigNumber(currentValue); if (handle.throughputOnly) { currentValue = this.root.productionAnalytics.getCurrentShapeRateRaw(enumAnalyticsDataSource.delivered, handle.definition) / globalConfig.analyticsSliceDurationSeconds; @@ -238,7 +238,7 @@ export class HUDPinnedShapes extends BaseHUDPart { if (currentValueFormatted !== handle.lastRenderedValue) { handle.lastRenderedValue = currentValueFormatted; handle.amountLabel.innerText = currentValueFormatted; - const goal: any = this.findGoalValueForShape(handle.key); + const goal = this.findGoalValueForShape(handle.key); handle.element.classList.toggle("completed", goal && currentValue > goal); } } @@ -246,7 +246,7 @@ export class HUDPinnedShapes extends BaseHUDPart { /** * Unpins a shape */ - unpinShape(key: string): any { + unpinShape(key: string) { console.log("unpin", key); arrayDeleteValue(this.pinnedShapes, key); this.rerenderFull(); @@ -254,8 +254,8 @@ export class HUDPinnedShapes extends BaseHUDPart { /** * Requests to pin a new shape */ - pinNewShape(definition: ShapeDefinition): any { - const key: any = definition.getHash(); + pinNewShape(definition: ShapeDefinition) { + const key = definition.getHash(); if (key === this.root.hubGoals.currentGoal.definition.getHash()) { // Can not pin current goal return; diff --git a/src/ts/game/hud/parts/puzzle_back_to_menu.ts b/src/ts/game/hud/parts/puzzle_back_to_menu.ts index 77da111b..a293273c 100644 --- a/src/ts/game/hud/parts/puzzle_back_to_menu.ts +++ b/src/ts/game/hud/parts/puzzle_back_to_menu.ts @@ -1,16 +1,16 @@ import { makeDiv } from "../../../core/utils"; import { BaseHUDPart } from "../base_hud_part"; export class HUDPuzzleBackToMenu extends BaseHUDPart { - createElements(parent: any): any { - const key: any = this.root.gameMode.getId(); + createElements(parent) { + const key = this.root.gameMode.getId(); this.element = makeDiv(parent, "ingame_HUD_PuzzleBackToMenu"); this.button = document.createElement("button"); this.button.classList.add("button"); this.element.appendChild(this.button); this.trackClicks(this.button, this.back); } - initialize(): any { } - back(): any { + initialize() { } + back() { this.root.gameState.goBackToMenu(); } } diff --git a/src/ts/game/hud/parts/puzzle_complete_notification.ts b/src/ts/game/hud/parts/puzzle_complete_notification.ts index 389a0269..090f8735 100644 --- a/src/ts/game/hud/parts/puzzle_complete_notification.ts +++ b/src/ts/game/hud/parts/puzzle_complete_notification.ts @@ -8,7 +8,7 @@ import { T } from "../../../translations"; import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; export class HUDPuzzleCompleteNotification extends BaseHUDPart { - initialize(): any { + initialize() { this.visible = false; this.domAttach = new DynamicDomAttach(this.root, this.element, { timeToKeepSeconds: 0, @@ -17,78 +17,78 @@ export class HUDPuzzleCompleteNotification extends BaseHUDPart { this.userDidLikePuzzle = false; this.timeOfCompletion = 0; } - createElements(parent: any): any { + createElements(parent) { this.inputReciever = new InputReceiver("puzzle-complete"); this.element = makeDiv(parent, "ingame_HUD_PuzzleCompleteNotification", ["noBlur"]); - const dialog: any = makeDiv(this.element, null, ["dialog"]); + const dialog = makeDiv(this.element, null, ["dialog"]); this.elemTitle = makeDiv(dialog, null, ["title"], T.ingame.puzzleCompletion.title); this.elemContents = makeDiv(dialog, null, ["contents"]); this.elemActions = makeDiv(dialog, null, ["actions"]); - const stepLike: any = makeDiv(this.elemContents, null, ["step", "stepLike"]); + const stepLike = makeDiv(this.elemContents, null, ["step", "stepLike"]); makeDiv(stepLike, null, ["title"], T.ingame.puzzleCompletion.titleLike); - const likeButtons: any = makeDiv(stepLike, null, ["buttons"]); + const likeButtons = makeDiv(stepLike, null, ["buttons"]); this.buttonLikeYes = document.createElement("button"); this.buttonLikeYes.classList.add("liked-yes"); likeButtons.appendChild(this.buttonLikeYes); - this.trackClicks(this.buttonLikeYes, (): any => { + this.trackClicks(this.buttonLikeYes, () => { this.userDidLikePuzzle = !this.userDidLikePuzzle; this.updateState(); }); - const buttonBar: any = document.createElement("div"); + const buttonBar = document.createElement("div"); buttonBar.classList.add("buttonBar"); this.elemContents.appendChild(buttonBar); this.continueBtn = document.createElement("button"); this.continueBtn.classList.add("continue", "styledButton"); this.continueBtn.innerText = T.ingame.puzzleCompletion.continueBtn; buttonBar.appendChild(this.continueBtn); - this.trackClicks(this.continueBtn, (): any => { + this.trackClicks(this.continueBtn, () => { this.close(false); }); this.menuBtn = document.createElement("button"); this.menuBtn.classList.add("menu", "styledButton"); this.menuBtn.innerText = T.ingame.puzzleCompletion.menuBtn; buttonBar.appendChild(this.menuBtn); - this.trackClicks(this.menuBtn, (): any => { + this.trackClicks(this.menuBtn, () => { this.close(true); }); - const gameMode: any = (this.root.gameMode as PuzzlePlayGameMode); + const gameMode = this.root.gameMode as PuzzlePlayGameMode); if (gameMode.nextPuzzles.length > 0) { this.nextPuzzleBtn = document.createElement("button"); this.nextPuzzleBtn.classList.add("nextPuzzle", "styledButton"); this.nextPuzzleBtn.innerText = T.ingame.puzzleCompletion.nextPuzzle; buttonBar.appendChild(this.nextPuzzleBtn); - this.trackClicks(this.nextPuzzleBtn, (): any => { + this.trackClicks(this.nextPuzzleBtn, () => { this.nextPuzzle(); }); } } - updateState(): any { + updateState() { this.buttonLikeYes.classList.toggle("active", this.userDidLikePuzzle === true); } - show(): any { + show() { this.root.soundProxy.playUi(SOUNDS.levelComplete); this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever); this.visible = true; this.timeOfCompletion = this.root.time.now(); } - cleanup(): any { + cleanup() { this.root.app.inputMgr.makeSureDetached(this.inputReciever); } - isBlockingOverlay(): any { + isBlockingOverlay() { return this.visible; } - nextPuzzle(): any { - const gameMode: any = (this.root.gameMode as PuzzlePlayGameMode); - gameMode.trackCompleted(this.userDidLikePuzzle, Math.round(this.timeOfCompletion)).then((): any => { + nextPuzzle() { + const gameMode = this.root.gameMode as PuzzlePlayGameMode); + gameMode.trackCompleted(this.userDidLikePuzzle, Math.round(this.timeOfCompletion)).then(() => { this.root.gameState.moveToState("PuzzleMenuState", { continueQueue: gameMode.nextPuzzles, }); }); } - close(toMenu: any): any { + close(toMenu) { this.root.gameMode as PuzzlePlayGameMode) .trackCompleted(this.userDidLikePuzzle, Math.round(this.timeOfCompletion)) - .then((): any => { + .then(() => { if (toMenu) { this.root.gameState.moveToState("PuzzleMenuState"); } @@ -98,7 +98,7 @@ export class HUDPuzzleCompleteNotification extends BaseHUDPart { } }); } - update(): any { + update() { this.domAttach.update(this.visible); } } diff --git a/src/ts/game/hud/parts/puzzle_dlc_logo.ts b/src/ts/game/hud/parts/puzzle_dlc_logo.ts index 26f9909d..b934f464 100644 --- a/src/ts/game/hud/parts/puzzle_dlc_logo.ts +++ b/src/ts/game/hud/parts/puzzle_dlc_logo.ts @@ -1,10 +1,10 @@ import { makeDiv } from "../../../core/utils"; import { BaseHUDPart } from "../base_hud_part"; export class HUDPuzzleDLCLogo extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_PuzzleDLCLogo"); parent.appendChild(this.element); } - initialize(): any { } - next(): any { } + initialize() { } + next() { } } diff --git a/src/ts/game/hud/parts/puzzle_editor_controls.ts b/src/ts/game/hud/parts/puzzle_editor_controls.ts index e7b264f1..cac80c2d 100644 --- a/src/ts/game/hud/parts/puzzle_editor_controls.ts +++ b/src/ts/game/hud/parts/puzzle_editor_controls.ts @@ -2,13 +2,13 @@ import { makeDiv } from "../../../core/utils"; import { T } from "../../../translations"; import { BaseHUDPart } from "../base_hud_part"; export class HUDPuzzleEditorControls extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_PuzzleEditorControls"); this.element.innerHTML = T.ingame.puzzleEditorControls.instructions - .map((text: any): any => `${text}`) + .map(text => `${text}`) .join(""); this.titleElement = makeDiv(parent, "ingame_HUD_PuzzleEditorTitle"); this.titleElement.innerText = T.ingame.puzzleEditorControls.title; } - initialize(): any { } + initialize() { } } diff --git a/src/ts/game/hud/parts/puzzle_editor_review.ts b/src/ts/game/hud/parts/puzzle_editor_review.ts index cb524cbc..b1fbaffa 100644 --- a/src/ts/game/hud/parts/puzzle_editor_review.ts +++ b/src/ts/game/hud/parts/puzzle_editor_review.ts @@ -12,15 +12,15 @@ import { StaticMapEntityComponent } from "../../components/static_map_entity"; import { ShapeItem } from "../../items/shape_item"; import { ShapeDefinition } from "../../shape_definition"; import { BaseHUDPart } from "../base_hud_part"; -const trim: any = require("trim"); -const logger: any = createLogger("puzzle-review"); +const trim = require("trim"); +const logger = createLogger("puzzle-review"); export class HUDPuzzleEditorReview extends BaseHUDPart { constructor(root) { super(root); } - createElements(parent: any): any { - const key: any = this.root.gameMode.getId(); + createElements(parent) { + const key = this.root.gameMode.getId(); this.element = makeDiv(parent, "ingame_HUD_PuzzleEditorReview"); this.button = document.createElement("button"); this.button.classList.add("button"); @@ -28,24 +28,24 @@ export class HUDPuzzleEditorReview extends BaseHUDPart { this.element.appendChild(this.button); this.trackClicks(this.button, this.startReview); } - initialize(): any { } - startReview(): any { - const validationError: any = this.validatePuzzle(); + initialize() { } + startReview() { + const validationError = this.validatePuzzle(); if (validationError) { this.root.hud.parts.dialogs.showWarning(T.puzzleMenu.validation.title, validationError); return; } - const closeLoading: any = this.root.hud.parts.dialogs.showLoadingDialog(T.puzzleMenu.validatingPuzzle); + const closeLoading = this.root.hud.parts.dialogs.showLoadingDialog(T.puzzleMenu.validatingPuzzle); // Wait a bit, so the user sees the puzzle actually got validated - setTimeout((): any => { + setTimeout(() => { // Manually simulate ticks this.root.logic.clearAllBeltsAndItems(); - const maxTicks: any = this.root.gameMode.getFixedTickrate() * globalConfig.puzzleValidationDurationSeconds; - const deltaMs: any = this.root.dynamicTickrate.deltaMs; + const maxTicks = this.root.gameMode.getFixedTickrate() * globalConfig.puzzleValidationDurationSeconds; + const deltaMs = this.root.dynamicTickrate.deltaMs; logger.log("Simulating up to", maxTicks, "ticks, start=", this.root.time.now().toFixed(1)); - const now: any = performance.now(); - let simulatedTicks: any = 0; - for (let i: any = 0; i < maxTicks; ++i) { + const now = performance.now(); + let simulatedTicks = 0; + for (let i = 0; i < maxTicks; ++i) { // Perform logic tick this.root.time.performTicks(deltaMs, this.root.gameState.core.boundInternalTick); simulatedTicks++; @@ -53,7 +53,7 @@ export class HUDPuzzleEditorReview extends BaseHUDPart { break; } } - const duration: any = performance.now() - now; + const duration = performance.now() - now; logger.log("Simulated", simulatedTicks, "ticks, end=", this.root.time.now().toFixed(1), "duration=", duration.toFixed(2), "ms"); console.log("duration: " + duration); closeLoading(); @@ -63,7 +63,7 @@ export class HUDPuzzleEditorReview extends BaseHUDPart { return; } //if we reached maximum ticks and the puzzle still isn't completed - const validationError: any = this.validatePuzzle(); + const validationError = this.validatePuzzle(); if (simulatedTicks == maxTicks && validationError) { this.root.hud.parts.dialogs.showWarning(T.puzzleMenu.validation.title, validationError); return; @@ -71,85 +71,85 @@ export class HUDPuzzleEditorReview extends BaseHUDPart { this.startSubmit(); }, 750); } - startSubmit(title: any = "", shortKey: any = ""): any { - const regex: any = /^[a-zA-Z0-9_\- ]{4,20}$/; - const nameInput: any = new FormElementInput({ + startSubmit(title = "", shortKey = "") { + const regex = /^[a-zA-Z0-9_\- ]{4,20}$/; + const nameInput = new FormElementInput({ id: "nameInput", label: T.dialogs.submitPuzzle.descName, placeholder: T.dialogs.submitPuzzle.placeholderName, defaultValue: title, - validator: (val: any): any => trim(val).match(regex) && trim(val).length > 0, + validator: val => trim(val).match(regex) && trim(val).length > 0, }); - let items: any = new Set(); - const acceptors: any = this.root.entityMgr.getAllWithComponent(GoalAcceptorComponent); - for (const acceptor: any of acceptors) { - const item: any = acceptor.components.GoalAcceptor.item; + let items = new Set(); + const acceptors = this.root.entityMgr.getAllWithComponent(GoalAcceptorComponent); + for (const acceptor of acceptors) { + const item = acceptor.components.GoalAcceptor.item; if (item.getItemType() === "shape") { items.add(item); } } while (items.size < 8) { // add some randoms - const item: any = this.root.hubGoals.computeFreeplayShape(Math.round(10 + Math.random() * 10000)); + const item = this.root.hubGoals.computeFreeplayShape(Math.round(10 + Math.random() * 10000)); items.add(new ShapeItem(item)); } - const itemInput: any = new FormElementItemChooser({ + const itemInput = new FormElementItemChooser({ id: "signalItem", label: fillInLinkIntoTranslation(T.dialogs.submitPuzzle.descIcon, THIRDPARTY_URLS.shapeViewer), items: Array.from(items), }); - const shapeKeyInput: any = new FormElementInput({ + const shapeKeyInput = new FormElementInput({ id: "shapeKeyInput", label: null, placeholder: "CuCuCuCu", defaultValue: shortKey, - validator: (val: any): any => ShapeDefinition.isValidShortKey(trim(val)), + validator: val => ShapeDefinition.isValidShortKey(trim(val)), }); - const dialog: any = new DialogWithForm({ + const dialog = new DialogWithForm({ app: this.root.app, title: T.dialogs.submitPuzzle.title, desc: "", formElements: [nameInput, itemInput, shapeKeyInput], buttons: ["ok:good:enter"], }); - itemInput.valueChosen.add((value: any): any => { + itemInput.valueChosen.add(value => { shapeKeyInput.setValue(value.definition.getHash()); }); this.root.hud.parts.dialogs.internalShowDialog(dialog); - dialog.buttonSignals.ok.add((): any => { - const title: any = trim(nameInput.getValue()); - const shortKey: any = trim(shapeKeyInput.getValue()); + dialog.buttonSignals.ok.add(() => { + const title = trim(nameInput.getValue()); + const shortKey = trim(shapeKeyInput.getValue()); this.doSubmitPuzzle(title, shortKey); }); } - doSubmitPuzzle(title: any, shortKey: any): any { - const serialized: any = new PuzzleSerializer().generateDumpFromGameRoot(this.root); + doSubmitPuzzle(title, shortKey) { + const serialized = new PuzzleSerializer().generateDumpFromGameRoot(this.root); logger.log("Submitting puzzle, title=", title, "shortKey=", shortKey); if (G_IS_DEV) { logger.log("Serialized data:", serialized); } - const closeLoading: any = this.root.hud.parts.dialogs.showLoadingDialog(T.puzzleMenu.submittingPuzzle); + const closeLoading = this.root.hud.parts.dialogs.showLoadingDialog(T.puzzleMenu.submittingPuzzle); this.root.app.clientApi .apiSubmitPuzzle({ title, shortKey, data: serialized, }) - .then((): any => { + .then(() => { closeLoading(); - const { ok }: any = this.root.hud.parts.dialogs.showInfo(T.dialogs.puzzleSubmitOk.title, T.dialogs.puzzleSubmitOk.desc); - ok.add((): any => this.root.gameState.moveToState("PuzzleMenuState")); - }, (err: any): any => { + const { ok } = this.root.hud.parts.dialogs.showInfo(T.dialogs.puzzleSubmitOk.title, T.dialogs.puzzleSubmitOk.desc); + ok.add(() => this.root.gameState.moveToState("PuzzleMenuState")); + }, err => { closeLoading(); logger.warn("Failed to submit puzzle:", err); - const signals: any = this.root.hud.parts.dialogs.showWarning(T.dialogs.puzzleSubmitError.title, T.dialogs.puzzleSubmitError.desc + " " + err, ["cancel", "retry:good"]); - signals.retry.add((): any => this.startSubmit(title, shortKey)); + const signals = this.root.hud.parts.dialogs.showWarning(T.dialogs.puzzleSubmitError.title, T.dialogs.puzzleSubmitError.desc + " " + err, ["cancel", "retry:good"]); + signals.retry.add(() => this.startSubmit(title, shortKey)); }); } - validatePuzzle(): any { + validatePuzzle() { // Check there is at least one constant producer and goal acceptor - const producers: any = this.root.entityMgr.getAllWithComponent(ConstantSignalComponent); - const acceptors: any = this.root.entityMgr.getAllWithComponent(GoalAcceptorComponent); + const producers = this.root.entityMgr.getAllWithComponent(ConstantSignalComponent); + const acceptors = this.root.entityMgr.getAllWithComponent(GoalAcceptorComponent); if (producers.length === 0) { return T.puzzleMenu.validation.noProducers; } @@ -157,19 +157,19 @@ export class HUDPuzzleEditorReview extends BaseHUDPart { return T.puzzleMenu.validation.noGoalAcceptors; } // Check if all acceptors satisfy the constraints - for (const acceptor: any of acceptors) { - const goalComp: any = acceptor.components.GoalAcceptor; + for (const acceptor of acceptors) { + const goalComp = acceptor.components.GoalAcceptor; if (!goalComp.item) { return T.puzzleMenu.validation.goalAcceptorNoItem; } - const required: any = globalConfig.goalAcceptorItemsRequired; + const required = globalConfig.goalAcceptorItemsRequired; if (goalComp.currentDeliveredItems < required) { return T.puzzleMenu.validation.goalAcceptorRateNotMet; } } // Check if all buildings are within the area - const entities: any = this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent); - for (const entity: any of entities) { + const entities = this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent); + for (const entity of entities) { if (this.root.systemMgr.systems.zone.prePlacementCheck(entity) === STOP_PROPAGATION) { return T.puzzleMenu.validation.buildingOutOfBounds; } diff --git a/src/ts/game/hud/parts/puzzle_editor_settings.ts b/src/ts/game/hud/parts/puzzle_editor_settings.ts index 7b153d25..f6fae9c1 100644 --- a/src/ts/game/hud/parts/puzzle_editor_settings.ts +++ b/src/ts/game/hud/parts/puzzle_editor_settings.ts @@ -10,12 +10,12 @@ import { MetaGoalAcceptorBuilding } from "../../buildings/goal_acceptor"; import { StaticMapEntityComponent } from "../../components/static_map_entity"; import { PuzzleGameMode } from "../../modes/puzzle"; import { BaseHUDPart } from "../base_hud_part"; -const logger: any = createLogger("puzzle-editor"); +const logger = createLogger("puzzle-editor"); export class HUDPuzzleEditorSettings extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_PuzzleEditorSettings"); if (this.root.gameMode.getBuildableZones()) { - const bind: any = (selector: any, handler: any): any => this.trackClicks(this.element.querySelector(selector), handler); + const bind = (selector, handler) => this.trackClicks(this.element.querySelector(selector), handler); this.zone = makeDiv(this.element, null, ["section", "zone"], ` @@ -44,27 +44,27 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart {
`); - bind(".zoneWidth .minus", (): any => this.modifyZone(-1, 0)); - bind(".zoneWidth .plus", (): any => this.modifyZone(1, 0)); - bind(".zoneHeight .minus", (): any => this.modifyZone(0, -1)); - bind(".zoneHeight .plus", (): any => this.modifyZone(0, 1)); + bind(".zoneWidth .minus", () => this.modifyZone(-1, 0)); + bind(".zoneWidth .plus", () => this.modifyZone(1, 0)); + bind(".zoneHeight .minus", () => this.modifyZone(0, -1)); + bind(".zoneHeight .plus", () => this.modifyZone(0, 1)); bind("button.trim", this.trim); bind("button.clearItems", this.clearItems); bind("button.resetPuzzle", this.resetPuzzle); } } - clearItems(): any { + clearItems() { this.root.logic.clearAllBeltsAndItems(); } - resetPuzzle(): any { - for (const entity: any of this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent)) { - const staticComp: any = entity.components.StaticMapEntity; - const goalComp: any = entity.components.GoalAcceptor; + resetPuzzle() { + for (const entity of this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent)) { + const staticComp = entity.components.StaticMapEntity; + const goalComp = entity.components.GoalAcceptor; if (goalComp) { goalComp.clear(); } if ([MetaGoalAcceptorBuilding, MetaConstantProducerBuilding, MetaBlockBuilding] - .map((metaClass: any): any => gMetaBuildingRegistry.findByClass(metaClass).id) + .map(metaClass => gMetaBuildingRegistry.findByClass(metaClass).id) .includes(staticComp.getMetaBuilding().id)) { continue; } @@ -73,17 +73,17 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart { } this.root.entityMgr.processDestroyList(); } - trim(): any { + trim() { // Now, find the center - const buildings: any = this.root.entityMgr.entities.slice(); + const buildings = this.root.entityMgr.entities.slice(); if (buildings.length === 0) { // nothing to do return; } - let minRect: any = null; - for (const building: any of buildings) { - const staticComp: any = building.components.StaticMapEntity; - const bounds: any = staticComp.getTileSpaceBounds(); + let minRect = null; + for (const building of buildings) { + const staticComp = building.components.StaticMapEntity; + const bounds = staticComp.getTileSpaceBounds(); if (!minRect) { minRect = bounds; } @@ -91,8 +91,8 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart { minRect = minRect.getUnion(bounds); } } - const mode: any = (this.root.gameMode as PuzzleGameMode); - const moveByInverse: any = minRect.getCenter().round(); + const mode = this.root.gameMode as PuzzleGameMode); + const moveByInverse = minRect.getCenter().round(); // move buildings if (moveByInverse.length() > 0) { // increase area size @@ -100,17 +100,17 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart { mode.zoneHeight = globalConfig.puzzleMaxBoundsSize; // First, remove any items etc this.root.logic.clearAllBeltsAndItems(); - this.root.logic.performImmutableOperation((): any => { + this.root.logic.performImmutableOperation(() => { // 1. remove all buildings - for (const building: any of buildings) { + for (const building of buildings) { if (!this.root.logic.tryDeleteBuilding(building)) { assertAlways(false, "Failed to remove building in trim"); } } // 2. place them again, but centered - for (const building: any of buildings) { - const staticComp: any = building.components.StaticMapEntity; - const result: any = this.root.logic.tryPlaceBuilding({ + for (const building of buildings) { + const staticComp = building.components.StaticMapEntity; + const result = this.root.logic.tryPlaceBuilding({ origin: staticComp.origin.sub(moveByInverse), building: staticComp.getMetaBuilding(), originalRotation: staticComp.originalRotation, @@ -122,7 +122,7 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart { this.root.bulkOperationRunning = false; assertAlways(false, "Failed to re-place building in trim"); } - for (const key: any in building.components) { + for (const key in building.components) { building .components[key] as import("../../../core/global_registries").Component).copyAdditionalStateTo(result.components[key]); } @@ -130,8 +130,8 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart { }); } // 3. Actually trim - let w: any = mode.zoneWidth; - let h: any = mode.zoneHeight; + let w = mode.zoneWidth; + let h = mode.zoneHeight; while (!this.anyBuildingOutsideZone(w - 1, h)) { --w; } @@ -142,28 +142,28 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart { mode.zoneHeight = h; this.updateZoneValues(); } - initialize(): any { + initialize() { this.visible = true; this.updateZoneValues(); } - anyBuildingOutsideZone(width: any, height: any): any { + anyBuildingOutsideZone(width, height) { if (Math.min(width, height) < globalConfig.puzzleMinBoundsSize) { return true; } - const newZone: any = Rectangle.centered(width, height); - const entities: any = this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent); - for (const entity: any of entities) { - const staticComp: any = entity.components.StaticMapEntity; - const bounds: any = staticComp.getTileSpaceBounds(); + const newZone = Rectangle.centered(width, height); + const entities = this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent); + for (const entity of entities) { + const staticComp = entity.components.StaticMapEntity; + const bounds = staticComp.getTileSpaceBounds(); if (!newZone.intersectsFully(bounds)) { return true; } } } - modifyZone(deltaW: any, deltaH: any): any { - const mode: any = (this.root.gameMode as PuzzleGameMode); - const newWidth: any = mode.zoneWidth + deltaW; - const newHeight: any = mode.zoneHeight + deltaH; + modifyZone(deltaW, deltaH) { + const mode = this.root.gameMode as PuzzleGameMode); + const newWidth = mode.zoneWidth + deltaW; + const newHeight = mode.zoneHeight + deltaH; if (Math.min(newWidth, newHeight) < globalConfig.puzzleMinBoundsSize) { return; } @@ -178,8 +178,8 @@ export class HUDPuzzleEditorSettings extends BaseHUDPart { mode.zoneHeight = newHeight; this.updateZoneValues(); } - updateZoneValues(): any { - const mode: any = (this.root.gameMode as PuzzleGameMode); + updateZoneValues() { + const mode = this.root.gameMode as PuzzleGameMode); this.element.querySelector(".zoneWidth > .value").textContent = String(mode.zoneWidth); this.element.querySelector(".zoneHeight > .value").textContent = String(mode.zoneHeight); } diff --git a/src/ts/game/hud/parts/puzzle_play_metadata.ts b/src/ts/game/hud/parts/puzzle_play_metadata.ts index 68d59ea1..2a3408f7 100644 --- a/src/ts/game/hud/parts/puzzle_play_metadata.ts +++ b/src/ts/game/hud/parts/puzzle_play_metadata.ts @@ -4,13 +4,13 @@ import type { PuzzlePlayGameMode } from "../../modes/puzzle_play"; import { formatBigNumberFull, formatSeconds, makeDiv } from "../../../core/utils"; import { T } from "../../../translations"; import { BaseHUDPart } from "../base_hud_part"; -const copy: any = require("clipboard-copy"); +const copy = require("clipboard-copy"); export class HUDPuzzlePlayMetadata extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.titleElement = makeDiv(parent, "ingame_HUD_PuzzlePlayTitle"); this.titleElement.innerText = "PUZZLE"; - const mode: any = (this.root.gameMode as PuzzlePlayGameMode); - const puzzle: any = mode.puzzle; + const mode = this.root.gameMode as PuzzlePlayGameMode); + const puzzle = mode.puzzle; this.puzzleNameElement = makeDiv(this.titleElement, null, ["name"]); this.puzzleNameElement.innerText = puzzle.meta.title; this.element = makeDiv(parent, "ingame_HUD_PuzzlePlayMetadata"); @@ -47,13 +47,13 @@ export class HUDPuzzlePlayMetadata extends BaseHUDPart { this.element.querySelector(".author span") as HTMLElement).innerText = puzzle.meta.author; } - initialize(): any { } - share(): any { - const mode: any = (this.root.gameMode as PuzzlePlayGameMode); + initialize() { } + share() { + const mode = this.root.gameMode as PuzzlePlayGameMode); mode.sharePuzzle(); } - report(): any { - const mode: any = (this.root.gameMode as PuzzlePlayGameMode); + report() { + const mode = this.root.gameMode as PuzzlePlayGameMode); mode.reportPuzzle(); } } diff --git a/src/ts/game/hud/parts/puzzle_play_settings.ts b/src/ts/game/hud/parts/puzzle_play_settings.ts index 4b05ad48..6f106eef 100644 --- a/src/ts/game/hud/parts/puzzle_play_settings.ts +++ b/src/ts/game/hud/parts/puzzle_play_settings.ts @@ -3,12 +3,12 @@ import { makeDiv } from "../../../core/utils"; import { T } from "../../../translations"; import { StaticMapEntityComponent } from "../../components/static_map_entity"; import { BaseHUDPart } from "../base_hud_part"; -const logger: any = createLogger("puzzle-play"); +const logger = createLogger("puzzle-play"); export class HUDPuzzlePlaySettings extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_PuzzlePlaySettings"); if (this.root.gameMode.getBuildableZones()) { - const bind: any = (selector: any, handler: any): any => this.trackClicks(this.element.querySelector(selector), handler); + const bind = (selector, handler) => this.trackClicks(this.element.querySelector(selector), handler); makeDiv(this.element, null, ["section"], ` @@ -18,13 +18,13 @@ export class HUDPuzzlePlaySettings extends BaseHUDPart { bind("button.resetPuzzle", this.resetPuzzle); } } - clearItems(): any { + clearItems() { this.root.logic.clearAllBeltsAndItems(); } - resetPuzzle(): any { - for (const entity: any of this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent)) { - const staticComp: any = entity.components.StaticMapEntity; - const goalComp: any = entity.components.GoalAcceptor; + resetPuzzle() { + for (const entity of this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent)) { + const staticComp = entity.components.StaticMapEntity; + const goalComp = entity.components.GoalAcceptor; if (goalComp) { goalComp.clear(); } @@ -35,7 +35,7 @@ export class HUDPuzzlePlaySettings extends BaseHUDPart { } this.root.entityMgr.processDestroyList(); } - initialize(): any { + initialize() { this.visible = true; } } diff --git a/src/ts/game/hud/parts/sandbox_controller.ts b/src/ts/game/hud/parts/sandbox_controller.ts index 02a47366..97a15a8f 100644 --- a/src/ts/game/hud/parts/sandbox_controller.ts +++ b/src/ts/game/hud/parts/sandbox_controller.ts @@ -4,7 +4,7 @@ import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; import { enumNotificationType } from "./notifications"; export class HUDSandboxController extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_SandboxController", [], ` Use F6 to toggle this overlay @@ -46,48 +46,48 @@ export class HUDSandboxController extends BaseHUDPart {
`); - const bind: any = (selector: any, handler: any): any => this.trackClicks(this.element.querySelector(selector), handler); + const bind = (selector, handler) => this.trackClicks(this.element.querySelector(selector), handler); bind(".giveBlueprints", this.giveBlueprints); bind(".maxOutAll", this.maxOutAll); - bind(".levelToggle .minus", (): any => this.modifyLevel(-1)); - bind(".levelToggle .plus", (): any => this.modifyLevel(1)); - bind(".upgradesBelt .minus", (): any => this.modifyUpgrade("belt", -1)); - bind(".upgradesBelt .plus", (): any => this.modifyUpgrade("belt", 1)); - bind(".upgradesExtraction .minus", (): any => this.modifyUpgrade("miner", -1)); - bind(".upgradesExtraction .plus", (): any => this.modifyUpgrade("miner", 1)); - bind(".upgradesProcessing .minus", (): any => this.modifyUpgrade("processors", -1)); - bind(".upgradesProcessing .plus", (): any => this.modifyUpgrade("processors", 1)); - bind(".upgradesPainting .minus", (): any => this.modifyUpgrade("painting", -1)); - bind(".upgradesPainting .plus", (): any => this.modifyUpgrade("painting", 1)); + bind(".levelToggle .minus", () => this.modifyLevel(-1)); + bind(".levelToggle .plus", () => this.modifyLevel(1)); + bind(".upgradesBelt .minus", () => this.modifyUpgrade("belt", -1)); + bind(".upgradesBelt .plus", () => this.modifyUpgrade("belt", 1)); + bind(".upgradesExtraction .minus", () => this.modifyUpgrade("miner", -1)); + bind(".upgradesExtraction .plus", () => this.modifyUpgrade("miner", 1)); + bind(".upgradesProcessing .minus", () => this.modifyUpgrade("processors", -1)); + bind(".upgradesProcessing .plus", () => this.modifyUpgrade("processors", 1)); + bind(".upgradesPainting .minus", () => this.modifyUpgrade("painting", -1)); + bind(".upgradesPainting .plus", () => this.modifyUpgrade("painting", 1)); } - giveBlueprints(): any { - const shape: any = this.root.gameMode.getBlueprintShapeKey(); + giveBlueprints() { + const shape = this.root.gameMode.getBlueprintShapeKey(); if (!this.root.hubGoals.storedShapes[shape]) { this.root.hubGoals.storedShapes[shape] = 0; } this.root.hubGoals.storedShapes[shape] += 1e9; } - maxOutAll(): any { + maxOutAll() { this.modifyUpgrade("belt", 100); this.modifyUpgrade("miner", 100); this.modifyUpgrade("processors", 100); this.modifyUpgrade("painting", 100); } - modifyUpgrade(id: any, amount: any): any { - const upgradeTiers: any = this.root.gameMode.getUpgrades()[id]; - const maxLevel: any = upgradeTiers.length; + modifyUpgrade(id, amount) { + const upgradeTiers = this.root.gameMode.getUpgrades()[id]; + const maxLevel = upgradeTiers.length; this.root.hubGoals.upgradeLevels[id] = Math.max(0, Math.min(maxLevel, (this.root.hubGoals.upgradeLevels[id] || 0) + amount)); // Compute improvement - let improvement: any = 1; - for (let i: any = 0; i < this.root.hubGoals.upgradeLevels[id]; ++i) { + let improvement = 1; + for (let i = 0; i < this.root.hubGoals.upgradeLevels[id]; ++i) { improvement += upgradeTiers[i].improvement; } this.root.hubGoals.upgradeImprovements[id] = improvement; this.root.signals.upgradePurchased.dispatch(id); this.root.hud.signals.notification.dispatch("Upgrade '" + id + "' is now at tier " + (this.root.hubGoals.upgradeLevels[id] + 1), enumNotificationType.upgrade); } - modifyLevel(amount: any): any { - const hubGoals: any = this.root.hubGoals; + modifyLevel(amount) { + const hubGoals = this.root.hubGoals; hubGoals.level = Math.max(1, hubGoals.level + amount); hubGoals.computeNextGoal(); // Clear all shapes of this level @@ -97,18 +97,18 @@ export class HUDSandboxController extends BaseHUDPart { } // Compute gained rewards hubGoals.gainedRewards = {}; - const levels: any = this.root.gameMode.getLevelDefinitions(); - for (let i: any = 0; i < hubGoals.level - 1; ++i) { + const levels = this.root.gameMode.getLevelDefinitions(); + for (let i = 0; i < hubGoals.level - 1; ++i) { if (i < levels.length) { - const reward: any = levels[i].reward; + const reward = levels[i].reward; hubGoals.gainedRewards[reward] = (hubGoals.gainedRewards[reward] || 0) + 1; } } this.root.hud.signals.notification.dispatch("Changed level to " + hubGoals.level, enumNotificationType.upgrade); } - initialize(): any { + initialize() { // Allow toggling the controller overlay - this.root.gameState.inputReciever.keydown.add((key: any): any => { + this.root.gameState.inputReciever.keydown.add(key => { if (key.keyCode === 117) { // F6 this.toggle(); @@ -117,10 +117,10 @@ export class HUDSandboxController extends BaseHUDPart { this.visible = false; this.domAttach = new DynamicDomAttach(this.root, this.element); } - toggle(): any { + toggle() { this.visible = !this.visible; } - update(): any { + update() { this.domAttach.update(this.visible); } } diff --git a/src/ts/game/hud/parts/screenshot_exporter.ts b/src/ts/game/hud/parts/screenshot_exporter.ts index 66a06da3..8b12c667 100644 --- a/src/ts/game/hud/parts/screenshot_exporter.ts +++ b/src/ts/game/hud/parts/screenshot_exporter.ts @@ -8,54 +8,54 @@ import { T } from "../../../translations"; import { StaticMapEntityComponent } from "../../components/static_map_entity"; import { KEYMAPPINGS } from "../../key_action_mapper"; import { BaseHUDPart } from "../base_hud_part"; -const logger: any = createLogger("screenshot_exporter"); +const logger = createLogger("screenshot_exporter"); export class HUDScreenshotExporter extends BaseHUDPart { - createElements(): any { } - initialize(): any { + createElements() { } + initialize() { this.root.keyMapper.getBinding(KEYMAPPINGS.ingame.exportScreenshot).add(this.startExport, this); } - startExport(): any { + startExport() { if (!this.root.app.restrictionMgr.getIsExportingScreenshotsPossible()) { this.root.hud.parts.dialogs.showFeatureRestrictionInfo(T.demo.features.exportingBase); return; } - const { ok }: any = this.root.hud.parts.dialogs.showInfo(T.dialogs.exportScreenshotWarning.title, T.dialogs.exportScreenshotWarning.desc, ["cancel:good", "ok:bad"]); + const { ok } = this.root.hud.parts.dialogs.showInfo(T.dialogs.exportScreenshotWarning.title, T.dialogs.exportScreenshotWarning.desc, ["cancel:good", "ok:bad"]); ok.add(this.doExport, this); } - doExport(): any { + doExport() { logger.log("Starting export ..."); // Find extends - const staticEntities: any = this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent); - const minTile: any = new Vector(0, 0); - const maxTile: any = new Vector(0, 0); - for (let i: any = 0; i < staticEntities.length; ++i) { - const bounds: any = staticEntities[i].components.StaticMapEntity.getTileSpaceBounds(); + const staticEntities = this.root.entityMgr.getAllWithComponent(StaticMapEntityComponent); + const minTile = new Vector(0, 0); + const maxTile = new Vector(0, 0); + for (let i = 0; i < staticEntities.length; ++i) { + const bounds = staticEntities[i].components.StaticMapEntity.getTileSpaceBounds(); minTile.x = Math.min(minTile.x, bounds.x); minTile.y = Math.min(minTile.y, bounds.y); maxTile.x = Math.max(maxTile.x, bounds.x + bounds.w); maxTile.y = Math.max(maxTile.y, bounds.y + bounds.h); } - const minChunk: any = minTile.divideScalar(globalConfig.mapChunkSize).floor(); - const maxChunk: any = maxTile.divideScalar(globalConfig.mapChunkSize).ceil(); - const dimensions: any = maxChunk.sub(minChunk); + const minChunk = minTile.divideScalar(globalConfig.mapChunkSize).floor(); + const maxChunk = maxTile.divideScalar(globalConfig.mapChunkSize).ceil(); + const dimensions = maxChunk.sub(minChunk); logger.log("Dimensions:", dimensions); - let chunkSizePixels: any = 128; - const maxDimensions: any = Math.max(dimensions.x, dimensions.y); + let chunkSizePixels = 128; + const maxDimensions = Math.max(dimensions.x, dimensions.y); if (maxDimensions > 128) { chunkSizePixels = Math.max(1, Math.floor(128 * (128 / maxDimensions))); } logger.log("ChunkSizePixels:", chunkSizePixels); - const chunkScale: any = chunkSizePixels / globalConfig.mapChunkWorldSize; + const chunkScale = chunkSizePixels / globalConfig.mapChunkWorldSize; logger.log("Scale:", chunkScale); logger.log("Allocating buffer, if the factory grew too big it will crash here"); - const [canvas, context]: any = makeOffscreenBuffer(dimensions.x * chunkSizePixels, dimensions.y * chunkSizePixels, { + const [canvas, context] = makeOffscreenBuffer(dimensions.x * chunkSizePixels, dimensions.y * chunkSizePixels, { smooth: true, reusable: false, label: "export-buffer", }); logger.log("Got buffer, rendering now ..."); - const visibleRect: any = new Rectangle(minChunk.x * globalConfig.mapChunkWorldSize, minChunk.y * globalConfig.mapChunkWorldSize, dimensions.x * globalConfig.mapChunkWorldSize, dimensions.y * globalConfig.mapChunkWorldSize); - const parameters: any = new DrawParameters({ + const visibleRect = new Rectangle(minChunk.x * globalConfig.mapChunkWorldSize, minChunk.y * globalConfig.mapChunkWorldSize, dimensions.x * globalConfig.mapChunkWorldSize, dimensions.y * globalConfig.mapChunkWorldSize); + const parameters = new DrawParameters({ context, visibleRect, desiredAtlasScale: 0.25, @@ -69,8 +69,8 @@ export class HUDScreenshotExporter extends BaseHUDPart { this.root.map.drawForeground(parameters); // Offer export logger.log("Rendered buffer, exporting ..."); - const image: any = canvas.toDataURL("image/png"); - const link: any = document.createElement("a"); + const image = canvas.toDataURL("image/png"); + const link = document.createElement("a"); link.download = "base.png"; link.href = image; link.click(); diff --git a/src/ts/game/hud/parts/settings_menu.ts b/src/ts/game/hud/parts/settings_menu.ts index f3b57cb9..177cf04d 100644 --- a/src/ts/game/hud/parts/settings_menu.ts +++ b/src/ts/game/hud/parts/settings_menu.ts @@ -7,7 +7,7 @@ import { T } from "../../../translations"; import { StaticMapEntityComponent } from "../../components/static_map_entity"; import { BeltComponent } from "../../components/belt"; export class HUDSettingsMenu extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.background = makeDiv(parent, "ingame_HUD_SettingsMenu", ["ingameDialog"]); this.menuElement = makeDiv(this.background, null, ["menuElement"]); if (this.root.gameMode.hasHub()) { @@ -19,47 +19,47 @@ export class HUDSettingsMenu extends BaseHUDPart { `); } this.buttonContainer = makeDiv(this.menuElement, null, ["buttons"]); - const buttons: any = [ + const buttons = [ { id: "continue", - action: (): any => this.close(), + action: () => this.close(), }, { id: "settings", - action: (): any => this.goToSettings(), + action: () => this.goToSettings(), }, { id: "menu", - action: (): any => this.returnToMenu(), + action: () => this.returnToMenu(), }, ]; - for (let i: any = 0; i < buttons.length; ++i) { - const { action, id }: any = buttons[i]; - const element: any = document.createElement("button"); + for (let i = 0; i < buttons.length; ++i) { + const { action, id } = buttons[i]; + const element = document.createElement("button"); element.classList.add("styledButton"); element.classList.add(id); this.buttonContainer.appendChild(element); this.trackClicks(element, action); } } - isBlockingOverlay(): any { + isBlockingOverlay() { return this.visible; } - returnToMenu(): any { - this.root.app.adProvider.showVideoAd().then((): any => { + returnToMenu() { + this.root.app.adProvider.showVideoAd().then(() => { this.root.gameState.goBackToMenu(); }); } - goToSettings(): any { + goToSettings() { this.root.gameState.goToSettings(); } - shouldPauseGame(): any { + shouldPauseGame() { return this.visible; } - shouldPauseRendering(): any { + shouldPauseRendering() { return this.visible; } - initialize(): any { + initialize() { this.root.keyMapper.getBinding(KEYMAPPINGS.general.back).add(this.show, this); this.domAttach = new DynamicDomAttach(this.root, this.background, { attachClass: "visible", @@ -69,10 +69,10 @@ export class HUDSettingsMenu extends BaseHUDPart { this.keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.close, this); this.close(); } - show(): any { + show() { this.visible = true; this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever); - const totalMinutesPlayed: any = Math.ceil(this.root.time.now() / 60); + const totalMinutesPlayed = Math.ceil(this.root.time.now() / 60); if (this.root.gameMode.hasHub()) { const playtimeElement: HTMLElement = this.statsElement.querySelector(".playtime"); const buildingsPlacedElement: HTMLElement = this.statsElement.querySelector(".buildingsPlaced"); @@ -83,12 +83,12 @@ export class HUDSettingsMenu extends BaseHUDPart { beltsPlacedElement.innerText = formatBigNumberFull(this.root.entityMgr.getAllWithComponent(BeltComponent).length); } } - close(): any { + close() { this.visible = false; this.root.app.inputMgr.makeSureDetached(this.inputReciever); this.update(); } - update(): any { + update() { this.domAttach.update(this.visible); } } diff --git a/src/ts/game/hud/parts/shape_tooltip.ts b/src/ts/game/hud/parts/shape_tooltip.ts index 0330a345..2fa03acc 100644 --- a/src/ts/game/hud/parts/shape_tooltip.ts +++ b/src/ts/game/hud/parts/shape_tooltip.ts @@ -5,21 +5,21 @@ import { KEYMAPPINGS } from "../../key_action_mapper"; import { THEME } from "../../theme"; import { BaseHUDPart } from "../base_hud_part"; export class HUDShapeTooltip extends BaseHUDPart { - createElements(parent: any): any { } - initialize(): any { + createElements(parent) { } + initialize() { this.currentTile = new Vector(0, 0); this.currentEntity = null; this.isPlacingBuilding = false; - this.root.signals.entityQueuedForDestroy.add((): any => { + this.root.signals.entityQueuedForDestroy.add(() => { this.currentEntity = null; }, this); - this.root.hud.signals.selectedPlacementBuildingChanged.add((metaBuilding: any): any => { + this.root.hud.signals.selectedPlacementBuildingChanged.add(metaBuilding => { this.isPlacingBuilding = metaBuilding; }, this); } - isActive(): any { - const hudParts: any = this.root.hud.parts; - const active: any = this.root.app.settings.getSetting("shapeTooltipAlwaysOn") || + isActive() { + const hudParts = this.root.hud.parts; + const active = this.root.app.settings.getSetting("shapeTooltipAlwaysOn") || this.root.keyMapper.getBinding(KEYMAPPINGS.ingame.showShapeTooltip).pressed; // return false if any other placer is active return (active && @@ -28,14 +28,14 @@ export class HUDShapeTooltip extends BaseHUDPart { hudParts.massSelector.selectedUids.size < 1 && !hudParts.blueprintPlacer.currentBlueprint.get()); } - draw(parameters: DrawParameters): any { + draw(parameters: DrawParameters) { if (this.isActive()) { - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (mousePos) { - const tile: any = this.root.camera.screenToWorld(mousePos.copy()).toTileSpace(); + const tile = this.root.camera.screenToWorld(mousePos.copy()).toTileSpace(); if (!tile.equals(this.currentTile)) { this.currentTile = tile; - const entity: any = this.root.map.getLayerContentXY(tile.x, tile.y, this.root.currentLayer); + const entity = this.root.map.getLayerContentXY(tile.x, tile.y, this.root.currentLayer); if (entity && entity.components.ItemProcessor && entity.components.ItemEjector) { this.currentEntity = entity; } @@ -47,14 +47,14 @@ export class HUDShapeTooltip extends BaseHUDPart { if (!this.currentEntity) { return; } - const ejectorComp: any = this.currentEntity.components.ItemEjector; - const staticComp: any = this.currentEntity.components.StaticMapEntity; - const bounds: any = staticComp.getTileSize(); - const totalArea: any = bounds.x * bounds.y; - const maxSlots: any = totalArea < 2 ? 1 : 1e10; - let slotsDrawn: any = 0; - for (let i: any = 0; i < ejectorComp.slots.length; ++i) { - const slot: any = ejectorComp.slots[i]; + const ejectorComp = this.currentEntity.components.ItemEjector; + const staticComp = this.currentEntity.components.StaticMapEntity; + const bounds = staticComp.getTileSize(); + const totalArea = bounds.x * bounds.y; + const maxSlots = totalArea < 2 ? 1 : 1e10; + let slotsDrawn = 0; + for (let i = 0; i < ejectorComp.slots.length; ++i) { + const slot = ejectorComp.slots[i]; if (!slot.lastItem) { continue; } diff --git a/src/ts/game/hud/parts/shape_viewer.ts b/src/ts/game/hud/parts/shape_viewer.ts index 46c91bcd..67ccb308 100644 --- a/src/ts/game/hud/parts/shape_viewer.ts +++ b/src/ts/game/hud/parts/shape_viewer.ts @@ -5,9 +5,9 @@ import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper"; import { ShapeDefinition } from "../../shape_definition"; import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; -const copy: any = require("clipboard-copy"); +const copy = require("clipboard-copy"); export class HUDShapeViewer extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.background = makeDiv(parent, "ingame_HUD_ShapeViewer", ["ingameDialog"]); // DIALOG Inner / Wrapper this.dialogInner = makeDiv(this.background, null, ["dialogInner"]); @@ -23,7 +23,7 @@ export class HUDShapeViewer extends BaseHUDPart { this.copyButton.innerText = T.ingame.shapeViewer.copyKey; this.infoArea.appendChild(this.copyButton); } - initialize(): any { + initialize() { this.root.hud.signals.viewShapeDetailsRequested.add(this.renderForShape, this); this.domAttach = new DynamicDomAttach(this.root, this.background, { attachClass: "visible", @@ -35,13 +35,13 @@ export class HUDShapeViewer extends BaseHUDPart { this.trackClicks(this.copyButton, this.onCopyKeyRequested); this.close(); } - isBlockingOverlay(): any { + isBlockingOverlay() { return this.visible; } /** * Called when the copying of a key was requested */ - onCopyKeyRequested(): any { + onCopyKeyRequested() { if (this.currentShapeKey) { copy(this.currentShapeKey); this.close(); @@ -50,7 +50,7 @@ export class HUDShapeViewer extends BaseHUDPart { /** * Closes the dialog */ - close(): any { + close() { this.visible = false; this.root.app.inputMgr.makeSureDetached(this.inputReciever); this.update(); @@ -58,36 +58,36 @@ export class HUDShapeViewer extends BaseHUDPart { /** * Shows the viewer for a given definition */ - renderForShape(definition: ShapeDefinition): any { + renderForShape(definition: ShapeDefinition) { this.visible = true; this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever); removeAllChildren(this.renderArea); this.currentShapeKey = definition.getHash(); - const layers: any = definition.layers; + const layers = definition.layers; this.contentDiv.setAttribute("data-layers", layers.length); - for (let i: any = layers.length - 1; i >= 0; --i) { - const layerElem: any = makeDiv(this.renderArea, null, ["layer", "layer-" + i]); - let fakeLayers: any = []; - for (let k: any = 0; k < i; ++k) { + for (let i = layers.length - 1; i >= 0; --i) { + const layerElem = makeDiv(this.renderArea, null, ["layer", "layer-" + i]); + let fakeLayers = []; + for (let k = 0; k < i; ++k) { fakeLayers.push([null, null, null, null]); } fakeLayers.push(layers[i]); - const thisLayerOnly: any = new ShapeDefinition({ layers: fakeLayers }); - const thisLayerCanvas: any = thisLayerOnly.generateAsCanvas(160); + const thisLayerOnly = new ShapeDefinition({ layers: fakeLayers }); + const thisLayerCanvas = thisLayerOnly.generateAsCanvas(160); layerElem.appendChild(thisLayerCanvas); - for (let quad: any = 0; quad < 4; ++quad) { - const quadElem: any = makeDiv(layerElem, null, ["quad", "quad-" + quad]); - const contents: any = layers[i][quad]; + for (let quad = 0; quad < 4; ++quad) { + const quadElem = makeDiv(layerElem, null, ["quad", "quad-" + quad]); + const contents = layers[i][quad]; if (contents) { - const colorLabelElem: any = makeDiv(quadElem, null, ["colorLabel"], T.ingame.colors[contents.color]); + const colorLabelElem = makeDiv(quadElem, null, ["colorLabel"], T.ingame.colors[contents.color]); } else { - const emptyLabelElem: any = makeDiv(quadElem, null, ["emptyLabel"], T.ingame.shapeViewer.empty); + const emptyLabelElem = makeDiv(quadElem, null, ["emptyLabel"], T.ingame.shapeViewer.empty); } } } } - update(): any { + update() { this.domAttach.update(this.visible); } } diff --git a/src/ts/game/hud/parts/shop.ts b/src/ts/game/hud/parts/shop.ts index 60458e79..31292d82 100644 --- a/src/ts/game/hud/parts/shop.ts +++ b/src/ts/game/hud/parts/shop.ts @@ -7,7 +7,7 @@ import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper"; import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; export class HUDShop extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.background = makeDiv(parent, "ingame_HUD_Shop", ["ingameDialog"]); // DIALOG Inner / Wrapper this.dialogInner = makeDiv(this.background, null, ["dialogInner"]); @@ -17,14 +17,14 @@ export class HUDShop extends BaseHUDPart { this.contentDiv = makeDiv(this.dialogInner, null, ["content"]); this.upgradeToElements = {}; // Upgrades - for (const upgradeId: any in this.root.gameMode.getUpgrades()) { - const handle: any = {}; + for (const upgradeId in this.root.gameMode.getUpgrades()) { + const handle = {}; handle.requireIndexToElement = []; // Wrapper handle.elem = makeDiv(this.contentDiv, null, ["upgrade"]); handle.elem.setAttribute("data-upgrade-id", upgradeId); // Title - const title: any = makeDiv(handle.elem, null, ["title"], T.shopUpgrades[upgradeId].name); + const title = makeDiv(handle.elem, null, ["title"], T.shopUpgrades[upgradeId].name); // Title > Tier handle.elemTierLabel = makeDiv(title, null, ["tier"]); // Icon @@ -38,24 +38,24 @@ export class HUDShop extends BaseHUDPart { handle.buyButton.classList.add("buy", "styledButton"); handle.buyButton.innerText = T.ingame.shop.buttonUnlock; handle.elem.appendChild(handle.buyButton); - this.trackClicks(handle.buyButton, (): any => this.tryUnlockNextTier(upgradeId)); + this.trackClicks(handle.buyButton, () => this.tryUnlockNextTier(upgradeId)); // Assign handle this.upgradeToElements[upgradeId] = handle; } } - rerenderFull(): any { - for (const upgradeId: any in this.upgradeToElements) { - const handle: any = this.upgradeToElements[upgradeId]; - const upgradeTiers: any = this.root.gameMode.getUpgrades()[upgradeId]; - const currentTier: any = this.root.hubGoals.getUpgradeLevel(upgradeId); - const currentTierMultiplier: any = this.root.hubGoals.upgradeImprovements[upgradeId]; - const tierHandle: any = upgradeTiers[currentTier]; + rerenderFull() { + for (const upgradeId in this.upgradeToElements) { + const handle = this.upgradeToElements[upgradeId]; + const upgradeTiers = this.root.gameMode.getUpgrades()[upgradeId]; + const currentTier = this.root.hubGoals.getUpgradeLevel(upgradeId); + const currentTierMultiplier = this.root.hubGoals.upgradeImprovements[upgradeId]; + const tierHandle = upgradeTiers[currentTier]; // Set tier handle.elemTierLabel.innerText = T.ingame.shop.tier.replace("", getRomanNumber(currentTier + 1)); handle.elemTierLabel.setAttribute("data-tier", currentTier); // Cleanup detectors - for (let i: any = 0; i < handle.requireIndexToElement.length; ++i) { - const requiredHandle: any = handle.requireIndexToElement[i]; + for (let i = 0; i < handle.requireIndexToElement.length; ++i) { + const requiredHandle = handle.requireIndexToElement[i]; requiredHandle.container.remove(); requiredHandle.pinDetector.cleanup(); if (requiredHandle.infoDetector) { @@ -74,42 +74,42 @@ export class HUDShop extends BaseHUDPart { handle.elemDescription.innerText = T.shopUpgrades[upgradeId].description .replace("", currentTierMultiplier.toFixed(2)) .replace("", (currentTierMultiplier + tierHandle.improvement).toFixed(2)); - tierHandle.required.forEach(({ shape, amount }: any): any => { - const container: any = makeDiv(handle.elemRequirements, null, ["requirement"]); - const shapeDef: any = this.root.shapeDefinitionMgr.getShapeFromShortKey(shape); - const shapeCanvas: any = shapeDef.generateAsCanvas(120); + tierHandle.required.forEach(({ shape, amount }) => { + const container = makeDiv(handle.elemRequirements, null, ["requirement"]); + const shapeDef = this.root.shapeDefinitionMgr.getShapeFromShortKey(shape); + const shapeCanvas = shapeDef.generateAsCanvas(120); shapeCanvas.classList.add(); container.appendChild(shapeCanvas); - const progressContainer: any = makeDiv(container, null, ["amount"]); - const progressBar: any = document.createElement("label"); + const progressContainer = makeDiv(container, null, ["amount"]); + const progressBar = document.createElement("label"); progressBar.classList.add("progressBar"); progressContainer.appendChild(progressBar); - const progressLabel: any = document.createElement("label"); + const progressLabel = document.createElement("label"); progressContainer.appendChild(progressLabel); - const pinButton: any = document.createElement("button"); + const pinButton = document.createElement("button"); pinButton.classList.add("pin"); container.appendChild(pinButton); - let infoDetector: any; - const viewInfoButton: any = document.createElement("button"); + let infoDetector; + const viewInfoButton = document.createElement("button"); viewInfoButton.classList.add("showInfo"); container.appendChild(viewInfoButton); infoDetector = new ClickDetector(viewInfoButton, { consumeEvents: true, preventDefault: true, }); - infoDetector.click.add((): any => this.root.hud.signals.viewShapeDetailsRequested.dispatch(shapeDef)); - const currentGoalShape: any = this.root.hubGoals.currentGoal.definition.getHash(); + infoDetector.click.add(() => this.root.hud.signals.viewShapeDetailsRequested.dispatch(shapeDef)); + const currentGoalShape = this.root.hubGoals.currentGoal.definition.getHash(); if (shape === currentGoalShape) { pinButton.classList.add("isGoal"); } else if (this.root.hud.parts.pinnedShapes.isShapePinned(shape)) { pinButton.classList.add("alreadyPinned"); } - const pinDetector: any = new ClickDetector(pinButton, { + const pinDetector = new ClickDetector(pinButton, { consumeEvents: true, preventDefault: true, }); - pinDetector.click.add((): any => { + pinDetector.click.add(() => { if (this.root.hud.parts.pinnedShapes.isShapePinned(shape)) { this.root.hud.signals.shapeUnpinRequested.dispatch(shape); pinButton.classList.add("unpinned"); @@ -133,13 +133,13 @@ export class HUDShop extends BaseHUDPart { }); } } - renderCountsAndStatus(): any { - for (const upgradeId: any in this.upgradeToElements) { - const handle: any = this.upgradeToElements[upgradeId]; - for (let i: any = 0; i < handle.requireIndexToElement.length; ++i) { - const { progressLabel, progressBar, definition, required }: any = handle.requireIndexToElement[i]; - const haveAmount: any = this.root.hubGoals.getShapesStored(definition); - const progress: any = Math.min(haveAmount / required, 1.0); + renderCountsAndStatus() { + for (const upgradeId in this.upgradeToElements) { + const handle = this.upgradeToElements[upgradeId]; + for (let i = 0; i < handle.requireIndexToElement.length; ++i) { + const { progressLabel, progressBar, definition, required } = handle.requireIndexToElement[i]; + const haveAmount = this.root.hubGoals.getShapesStored(definition); + const progress = Math.min(haveAmount / required, 1.0); progressLabel.innerText = formatBigNumber(haveAmount) + " / " + formatBigNumber(required); progressBar.style.width = progress * 100.0 + "%"; progressBar.classList.toggle("complete", progress >= 1.0); @@ -147,7 +147,7 @@ export class HUDShop extends BaseHUDPart { handle.buyButton.classList.toggle("buyable", this.root.hubGoals.canUnlockUpgrade(upgradeId)); } } - initialize(): any { + initialize() { this.domAttach = new DynamicDomAttach(this.root, this.background, { attachClass: "visible", }); @@ -160,12 +160,12 @@ export class HUDShop extends BaseHUDPart { this.rerenderFull(); this.root.signals.upgradePurchased.add(this.rerenderFull, this); } - cleanup(): any { + cleanup() { // Cleanup detectors - for (const upgradeId: any in this.upgradeToElements) { - const handle: any = this.upgradeToElements[upgradeId]; - for (let i: any = 0; i < handle.requireIndexToElement.length; ++i) { - const requiredHandle: any = handle.requireIndexToElement[i]; + for (const upgradeId in this.upgradeToElements) { + const handle = this.upgradeToElements[upgradeId]; + for (let i = 0; i < handle.requireIndexToElement.length; ++i) { + const requiredHandle = handle.requireIndexToElement[i]; requiredHandle.container.remove(); requiredHandle.pinDetector.cleanup(); if (requiredHandle.infoDetector) { @@ -175,28 +175,28 @@ export class HUDShop extends BaseHUDPart { handle.requireIndexToElement = []; } } - show(): any { + show() { this.visible = true; this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever); this.rerenderFull(); } - close(): any { + close() { this.visible = false; this.root.app.inputMgr.makeSureDetached(this.inputReciever); this.update(); } - update(): any { + update() { this.domAttach.update(this.visible); if (this.visible) { this.renderCountsAndStatus(); } } - tryUnlockNextTier(upgradeId: any): any { + tryUnlockNextTier(upgradeId) { if (this.root.hubGoals.tryUnlockUpgrade(upgradeId)) { this.root.app.sound.playUiSound(SOUNDS.unlockUpgrade); } } - isBlockingOverlay(): any { + isBlockingOverlay() { return this.visible; } } diff --git a/src/ts/game/hud/parts/standalone_advantages.ts b/src/ts/game/hud/parts/standalone_advantages.ts index 80ab3df9..8aff25fe 100644 --- a/src/ts/game/hud/parts/standalone_advantages.ts +++ b/src/ts/game/hud/parts/standalone_advantages.ts @@ -6,7 +6,7 @@ import { T } from "../../../translations"; import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; export class HUDStandaloneAdvantages extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.background = makeDiv(parent, "ingame_HUD_StandaloneAdvantages", ["ingameDialog"]); // DIALOG Inner / Wrapper this.dialogInner = makeDiv(this.background, null, ["dialogInner"]); @@ -15,7 +15,7 @@ export class HUDStandaloneAdvantages extends BaseHUDPart { this.contentDiv = makeDiv(this.dialogInner, null, ["content"], `
${Object.entries(T.ingame.standaloneAdvantages.points) - .map(([key, trans]: any): any => ` + .map(([key, trans]) => `
${trans.title}

${trans.desc}

@@ -36,17 +36,17 @@ export class HUDStandaloneAdvantages extends BaseHUDPart {
`); - this.trackClicks(this.contentDiv.querySelector("button.steamLinkButton"), (): any => { + this.trackClicks(this.contentDiv.querySelector("button.steamLinkButton"), () => { openStandaloneLink(this.root.app, "shapez_std_advg"); this.close(); }); - this.trackClicks(this.contentDiv.querySelector("button.otherCloseButton"), (): any => { + this.trackClicks(this.contentDiv.querySelector("button.otherCloseButton"), () => { this.close(); }); - this.trackClicks(this.contentDiv.querySelector(".playtimeDisclaimerDownload"), (): any => { + this.trackClicks(this.contentDiv.querySelector(".playtimeDisclaimerDownload"), () => { this.root.gameState.savegame.updateData(this.root); - const data: any = ReadWriteProxy.serializeObject(this.root.gameState.savegame.currentData); - const filename: any = "shapez-demo-savegame.bin"; + const data = ReadWriteProxy.serializeObject(this.root.gameState.savegame.currentData); + const filename = "shapez-demo-savegame.bin"; generateFileDownload(filename, data); }); } @@ -56,16 +56,16 @@ export class HUDStandaloneAdvantages extends BaseHUDPart { } return 15 * 60; } - shouldPauseGame(): any { + shouldPauseGame() { return this.visible; } - shouldPauseRendering(): any { + shouldPauseRendering() { return this.visible; } - hasBlockingOverlayOpen(): any { + hasBlockingOverlayOpen() { return this.visible; } - initialize(): any { + initialize() { this.domAttach = new DynamicDomAttach(this.root, this.background, { attachClass: "visible", }); @@ -74,14 +74,14 @@ export class HUDStandaloneAdvantages extends BaseHUDPart { // On standalone, show popup instant // wait for next interval this.lastShown = 0; - this.root.signals.gameRestored.add((): any => { + this.root.signals.gameRestored.add(() => { if (this.root.hubGoals.level >= this.root.gameMode.getLevelDefinitions().length - 1 && this.root.app.restrictionMgr.getIsStandaloneMarketingActive()) { this.show(true); } }); } - show(final: any = false): any { + show(final = false) { if (!this.visible) { this.root.app.gameAnalytics.noteMinor("game.std_advg.show"); this.root.app.gameAnalytics.noteMinor("game.std_advg.show-" + (final ? "final" : "nonfinal")); @@ -100,7 +100,7 @@ export class HUDStandaloneAdvantages extends BaseHUDPart { this.title.innerText = T.ingame.standaloneAdvantages.titleEnjoyingDemo; } } - close(): any { + close() { if (this.final) { this.root.gameState.goBackToMenu(); } @@ -110,7 +110,7 @@ export class HUDStandaloneAdvantages extends BaseHUDPart { this.update(); } } - update(): any { + update() { if (!this.visible && this.root.time.now() - this.lastShown > this.showIntervalSeconds) { this.show(); } diff --git a/src/ts/game/hud/parts/statistics.ts b/src/ts/game/hud/parts/statistics.ts index 59734fc8..62f14f09 100644 --- a/src/ts/game/hud/parts/statistics.ts +++ b/src/ts/game/hud/parts/statistics.ts @@ -9,11 +9,11 @@ import { T } from "../../../translations"; /** * Capitalizes the first letter */ -function capitalizeFirstLetter(str: string): any { +function capitalizeFirstLetter(str: string) { return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase(); } export class HUDStatistics extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.background = makeDiv(parent, "ingame_HUD_Statistics", ["ingameDialog"]); // DIALOG Inner / Wrapper this.dialogInner = makeDiv(this.background, null, ["dialogInner"]); @@ -24,27 +24,27 @@ export class HUDStatistics extends BaseHUDPart { this.sourceExplanation = makeDiv(this.dialogInner, null, ["sourceExplanation"]); this.filtersDataSource = makeDiv(this.filterHeader, null, ["filtersDataSource"]); this.filtersDisplayMode = makeDiv(this.filterHeader, null, ["filtersDisplayMode"]); - const dataSources: any = [ + const dataSources = [ enumAnalyticsDataSource.produced, enumAnalyticsDataSource.delivered, enumAnalyticsDataSource.stored, ]; - for (let i: any = 0; i < dataSources.length; ++i) { - const dataSource: any = dataSources[i]; - const button: any = makeButton(this.filtersDataSource, ["mode" + capitalizeFirstLetter(dataSource)], T.ingame.statistics.dataSources[dataSource].title); - this.trackClicks(button, (): any => this.setDataSource(dataSource)); + for (let i = 0; i < dataSources.length; ++i) { + const dataSource = dataSources[i]; + const button = makeButton(this.filtersDataSource, ["mode" + capitalizeFirstLetter(dataSource)], T.ingame.statistics.dataSources[dataSource].title); + this.trackClicks(button, () => this.setDataSource(dataSource)); } - const buttonIterateUnit: any = makeButton(this.filtersDisplayMode, ["displayIterateUnit"]); - const buttonDisplaySorted: any = makeButton(this.filtersDisplayMode, ["displaySorted"]); - const buttonDisplayDetailed: any = makeButton(this.filtersDisplayMode, ["displayDetailed"]); - const buttonDisplayIcons: any = makeButton(this.filtersDisplayMode, ["displayIcons"]); - this.trackClicks(buttonIterateUnit, (): any => this.iterateUnit()); - this.trackClicks(buttonDisplaySorted, (): any => this.toggleSorted()); - this.trackClicks(buttonDisplayIcons, (): any => this.setDisplayMode(enumDisplayMode.icons)); - this.trackClicks(buttonDisplayDetailed, (): any => this.setDisplayMode(enumDisplayMode.detailed)); + const buttonIterateUnit = makeButton(this.filtersDisplayMode, ["displayIterateUnit"]); + const buttonDisplaySorted = makeButton(this.filtersDisplayMode, ["displaySorted"]); + const buttonDisplayDetailed = makeButton(this.filtersDisplayMode, ["displayDetailed"]); + const buttonDisplayIcons = makeButton(this.filtersDisplayMode, ["displayIcons"]); + this.trackClicks(buttonIterateUnit, () => this.iterateUnit()); + this.trackClicks(buttonDisplaySorted, () => this.toggleSorted()); + this.trackClicks(buttonDisplayIcons, () => this.setDisplayMode(enumDisplayMode.icons)); + this.trackClicks(buttonDisplayDetailed, () => this.setDisplayMode(enumDisplayMode.detailed)); this.contentDiv = makeDiv(this.dialogInner, null, ["content"]); } - setDataSource(source: enumAnalyticsDataSource): any { + setDataSource(source: enumAnalyticsDataSource) { this.dataSource = source; this.dialogInner.setAttribute("data-datasource", source); this.sourceExplanation.innerText = T.ingame.statistics.dataSources[source].description; @@ -52,33 +52,33 @@ export class HUDStatistics extends BaseHUDPart { this.rerenderFull(); } } - setDisplayMode(mode: enumDisplayMode): any { + setDisplayMode(mode: enumDisplayMode) { this.displayMode = mode; this.dialogInner.setAttribute("data-displaymode", mode); if (this.visible) { this.rerenderFull(); } } - setSorted(sorted: boolean): any { + setSorted(sorted: boolean) { this.sorted = sorted; this.dialogInner.setAttribute("data-sorted", String(sorted)); if (this.visible) { this.rerenderFull(); } } - toggleSorted(): any { + toggleSorted() { this.setSorted(!this.sorted); } /** * Chooses the next unit */ - iterateUnit(): any { - const units: any = Array.from(Object.keys(statisticsUnitsSeconds)); - const newIndex: any = (units.indexOf(this.currentUnit) + 1) % units.length; + iterateUnit() { + const units = Array.from(Object.keys(statisticsUnitsSeconds)); + const newIndex = (units.indexOf(this.currentUnit) + 1) % units.length; this.currentUnit = units[newIndex]; this.rerenderPartial(); } - initialize(): any { + initialize() { this.domAttach = new DynamicDomAttach(this.root, this.background, { attachClass: "visible", }); @@ -99,30 +99,30 @@ export class HUDStatistics extends BaseHUDPart { this.close(); this.rerenderFull(); } - intersectionCallback(entries: any): any { - for (let i: any = 0; i < entries.length; ++i) { - const entry: any = entries[i]; - const handle: any = this.activeHandles[entry.target.getAttribute("data-shape-key")]; + intersectionCallback(entries) { + for (let i = 0; i < entries.length; ++i) { + const entry = entries[i]; + const handle = this.activeHandles[entry.target.getAttribute("data-shape-key")]; if (handle) { handle.setVisible(entry.intersectionRatio > 0); } } } - isBlockingOverlay(): any { + isBlockingOverlay() { return this.visible; } - show(): any { + show() { this.visible = true; this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever); this.rerenderFull(); this.update(); } - close(): any { + close() { this.visible = false; this.root.app.inputMgr.makeSureDetached(this.inputReciever); this.update(); } - update(): any { + update() { this.domAttach.update(this.visible); if (this.visible) { if (this.root.time.now() - this.lastFullRerender > 1) { @@ -136,22 +136,22 @@ export class HUDStatistics extends BaseHUDPart { /** * Performs a partial rerender, only updating graphs and counts */ - rerenderPartial(): any { - for (const key: any in this.activeHandles) { - const handle: any = this.activeHandles[key]; + rerenderPartial() { + for (const key in this.activeHandles) { + const handle = this.activeHandles[key]; handle.update(this.displayMode, this.dataSource, this.currentUnit); } } /** * Performs a full rerender, regenerating everything */ - rerenderFull(): any { - for (const key: any in this.activeHandles) { + rerenderFull() { + for (const key in this.activeHandles) { this.activeHandles[key].detach(); } removeAllChildren(this.contentDiv); // Now, attach new ones - let entries: any = null; + let entries = null; switch (this.dataSource) { case enumAnalyticsDataSource.stored: { entries = Object.entries(this.root.hubGoals.storedShapes); @@ -163,10 +163,10 @@ export class HUDStatistics extends BaseHUDPart { break; } } - const pinnedShapes: any = this.root.hud.parts.pinnedShapes; - entries.sort((a: any, b: any): any => { - const aPinned: any = pinnedShapes.isShapePinned(a[0]); - const bPinned: any = pinnedShapes.isShapePinned(b[0]); + const pinnedShapes = this.root.hud.parts.pinnedShapes; + entries.sort((a, b) => { + const aPinned = pinnedShapes.isShapePinned(a[0]); + const bPinned = pinnedShapes.isShapePinned(b[0]); if (aPinned !== bPinned) { return aPinned ? -1 : 1; } @@ -176,19 +176,19 @@ export class HUDStatistics extends BaseHUDPart { } return b[1] - a[1]; }); - let rendered: any = new Set(); - for (let i: any = 0; i < Math.min(entries.length, 200); ++i) { - const entry: any = entries[i]; - const shapeKey: any = entry[0]; - let handle: any = this.activeHandles[shapeKey]; + let rendered = new Set(); + for (let i = 0; i < Math.min(entries.length, 200); ++i) { + const entry = entries[i]; + const shapeKey = entry[0]; + let handle = this.activeHandles[shapeKey]; if (!handle) { - const definition: any = this.root.shapeDefinitionMgr.getShapeFromShortKey(shapeKey); + const definition = this.root.shapeDefinitionMgr.getShapeFromShortKey(shapeKey); handle = this.activeHandles[shapeKey] = new HUDShapeStatisticsHandle(this.root, definition, this.intersectionObserver); } rendered.add(shapeKey); handle.attach(this.contentDiv); } - for (const key: any in this.activeHandles) { + for (const key in this.activeHandles) { if (!rendered.has(key)) { this.activeHandles[key].destroy(); delete this.activeHandles[key]; diff --git a/src/ts/game/hud/parts/statistics_handle.ts b/src/ts/game/hud/parts/statistics_handle.ts index 028f5a5a..0a7e881f 100644 --- a/src/ts/game/hud/parts/statistics_handle.ts +++ b/src/ts/game/hud/parts/statistics_handle.ts @@ -6,7 +6,7 @@ import { enumAnalyticsDataSource } from "../../production_analytics"; import { GameRoot } from "../../root"; import { ShapeDefinition } from "../../shape_definition"; /** @enum {string} */ -export const enumDisplayMode: any = { +export const enumDisplayMode = { icons: "icons", detailed: "detailed", }; @@ -31,7 +31,7 @@ export class HUDShapeStatisticsHandle { constructor(root, definition, intersectionObserver) { } - initElement(): any { + initElement() { this.element = document.createElement("div"); this.element.setAttribute("data-shape-key", this.definition.getHash()); this.counter = document.createElement("span"); @@ -41,7 +41,7 @@ export class HUDShapeStatisticsHandle { /** * Sets whether the shape handle is visible currently */ - setVisible(visibility: boolean): any { + setVisible(visibility: boolean) { if (visibility === this.visible) { return; } @@ -59,7 +59,7 @@ export class HUDShapeStatisticsHandle { this.cleanupChildElements(); } } - update(displayMode: enumDisplayMode, dataSource: enumAnalyticsDataSource, unit: string, forced: boolean= = false): any { + update(displayMode: enumDisplayMode, dataSource: enumAnalyticsDataSource, unit: string, forced: boolean= = false) { if (!this.element) { return; } @@ -74,18 +74,18 @@ export class HUDShapeStatisticsHandle { } case enumAnalyticsDataSource.delivered: case enumAnalyticsDataSource.produced: { - let rate: any = this.root.productionAnalytics.getCurrentShapeRateRaw(dataSource, this.definition) / + let rate = this.root.productionAnalytics.getCurrentShapeRateRaw(dataSource, this.definition) / globalConfig.analyticsSliceDurationSeconds; this.counter.innerText = T.ingame.statistics.shapesDisplayUnits[unit].replace("", formatBigNumber(rate * statisticsUnitsSeconds[unit])); break; } } if (displayMode === enumDisplayMode.detailed) { - const graphDpi: any = globalConfig.statisticsGraphDpi; - const w: any = 270; - const h: any = 40; + const graphDpi = globalConfig.statisticsGraphDpi; + const w = 270; + const h = 40; if (!this.graphCanvas) { - const [canvas, context]: any = makeOffscreenBuffer(w * graphDpi, h * graphDpi, { + const [canvas, context] = makeOffscreenBuffer(w * graphDpi, h * graphDpi, { smooth: true, reusable: false, label: "statgraph-" + this.definition.getHash(), @@ -100,11 +100,11 @@ export class HUDShapeStatisticsHandle { this.graphContext.fillStyle = "#bee0db"; this.graphContext.strokeStyle = "#66ccbc"; this.graphContext.lineWidth = 1.5; - const sliceWidth: any = w / (globalConfig.statisticsGraphSlices - 1); - let values: any = []; - let maxValue: any = 1; - for (let i: any = 0; i < globalConfig.statisticsGraphSlices - 2; ++i) { - const value: any = this.root.productionAnalytics.getPastShapeRate(dataSource, this.definition, globalConfig.statisticsGraphSlices - i - 2); + const sliceWidth = w / (globalConfig.statisticsGraphSlices - 1); + let values = []; + let maxValue = 1; + for (let i = 0; i < globalConfig.statisticsGraphSlices - 2; ++i) { + const value = this.root.productionAnalytics.getPastShapeRate(dataSource, this.definition, globalConfig.statisticsGraphSlices - i - 2); if (value > maxValue) { maxValue = value; } @@ -112,9 +112,9 @@ export class HUDShapeStatisticsHandle { } this.graphContext.beginPath(); this.graphContext.moveTo(0.75, h + 5); - for (let i: any = 0; i < values.length; ++i) { - const yValue: any = clamp((1 - values[i] / maxValue) * h, 0.75, h - 0.75); - const x: any = i * sliceWidth; + for (let i = 0; i < values.length; ++i) { + const yValue = clamp((1 - values[i] / maxValue) * h, 0.75, h - 0.75); + const x = i * sliceWidth; if (i === 0) { this.graphContext.lineTo(0.75, yValue); } @@ -139,7 +139,7 @@ export class HUDShapeStatisticsHandle { /** * Attaches the handle */ - attach(parent: HTMLElement): any { + attach(parent: HTMLElement) { if (!this.element) { this.initElement(); } @@ -151,7 +151,7 @@ export class HUDShapeStatisticsHandle { /** * Detaches the handle */ - detach(): any { + detach() { if (this.element && this.element.parentElement) { this.element.parentElement.removeChild(this.element); this.intersectionObserver.unobserve(this.element); @@ -160,7 +160,7 @@ export class HUDShapeStatisticsHandle { /** * Cleans up all child elements */ - cleanupChildElements(): any { + cleanupChildElements() { if (this.shapeCanvas) { this.shapeCanvas.remove(); delete this.shapeCanvas; @@ -174,7 +174,7 @@ export class HUDShapeStatisticsHandle { /** * Destroys the handle */ - destroy(): any { + destroy() { this.cleanupChildElements(); if (this.element) { this.intersectionObserver.unobserve(this.element); diff --git a/src/ts/game/hud/parts/tutorial_hints.ts b/src/ts/game/hud/parts/tutorial_hints.ts index 3187bd14..6c36946d 100644 --- a/src/ts/game/hud/parts/tutorial_hints.ts +++ b/src/ts/game/hud/parts/tutorial_hints.ts @@ -5,9 +5,9 @@ import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper"; import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; import { T } from "../../../translations"; -const tutorialVideos: any = [3, 4, 5, 6, 7, 9, 10, 11]; +const tutorialVideos = [3, 4, 5, 6, 7, 9, 10, 11]; export class HUDPartTutorialHints extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_HUD_TutorialHints", [], `
${T.ingame.tutorialHints.title} @@ -23,10 +23,10 @@ export class HUDPartTutorialHints extends BaseHUDPart { `); this.videoElement = this.element.querySelector("video"); } - shouldPauseGame(): any { + shouldPauseGame() { return this.enlarged; } - initialize(): any { + initialize() { this.trackClicks(this.element.querySelector(".toggleHint"), this.toggleHintEnlarged); this.videoAttach = new DynamicDomAttach(this.root, this.videoElement, { timeToKeepSeconds: 0.3, @@ -39,7 +39,7 @@ export class HUDPartTutorialHints extends BaseHUDPart { this.domAttach = new DynamicDomAttach(this.root, this.element); this.currentShownLevel = new TrackedState(this.updateVideoUrl, this); } - updateVideoUrl(level: any): any { + updateVideoUrl(level) { if (tutorialVideos.indexOf(level) < 0) { this.videoElement.querySelector("source").setAttribute("src", ""); this.videoElement.pause(); @@ -52,13 +52,13 @@ export class HUDPartTutorialHints extends BaseHUDPart { this.videoElement.load(); } } - close(): any { + close() { this.enlarged = false; this.element.classList.remove("enlarged", "noBlur"); this.root.app.inputMgr.makeSureDetached(this.inputReciever); this.update(); } - show(): any { + show() { this.element.classList.add("enlarged", "noBlur"); this.enlarged = true; this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever); @@ -66,13 +66,13 @@ export class HUDPartTutorialHints extends BaseHUDPart { this.videoElement.currentTime = 0; this.videoElement.play(); } - update(): any { + update() { this.videoAttach.update(this.enlarged); this.currentShownLevel.set(this.root.hubGoals.level); - const tutorialVisible: any = tutorialVideos.indexOf(this.root.hubGoals.level) >= 0; + const tutorialVisible = tutorialVideos.indexOf(this.root.hubGoals.level) >= 0; this.domAttach.update(tutorialVisible); } - toggleHintEnlarged(): any { + toggleHintEnlarged() { if (this.enlarged) { this.close(); } diff --git a/src/ts/game/hud/parts/tutorial_video_offer.ts b/src/ts/game/hud/parts/tutorial_video_offer.ts index b05f294b..b2382caa 100644 --- a/src/ts/game/hud/parts/tutorial_video_offer.ts +++ b/src/ts/game/hud/parts/tutorial_video_offer.ts @@ -5,21 +5,21 @@ import { BaseHUDPart } from "../base_hud_part"; * Offers to open the tutorial video after completing a level */ export class HUDTutorialVideoOffer extends BaseHUDPart { - createElements(): any { } - initialize(): any { - this.root.hud.signals.unlockNotificationFinished.add((): any => { - const level: any = this.root.hubGoals.level; - const tutorialVideoLink: any = THIRDPARTY_URLS.levelTutorialVideos[level]; + createElements() { } + initialize() { + this.root.hud.signals.unlockNotificationFinished.add(() => { + const level = this.root.hubGoals.level; + const tutorialVideoLink = THIRDPARTY_URLS.levelTutorialVideos[level]; if (tutorialVideoLink) { - const isForeign: any = this.root.app.settings.getLanguage() !== "en"; - const dialogData: any = isForeign + const isForeign = this.root.app.settings.getLanguage() !== "en"; + const dialogData = isForeign ? T.dialogs.tutorialVideoAvailableForeignLanguage : T.dialogs.tutorialVideoAvailable; - const { ok }: any = this.root.hud.parts.dialogs.showInfo(dialogData.title, dialogData.desc, [ + const { ok } = this.root.hud.parts.dialogs.showInfo(dialogData.title, dialogData.desc, [ "cancel:bad", "ok:good", ]); - ok.add((): any => { + ok.add(() => { this.root.app.platformWrapper.openExternalLink(tutorialVideoLink); }); } diff --git a/src/ts/game/hud/parts/unlock_notification.ts b/src/ts/game/hud/parts/unlock_notification.ts index 5295411a..95d5834b 100644 --- a/src/ts/game/hud/parts/unlock_notification.ts +++ b/src/ts/game/hud/parts/unlock_notification.ts @@ -11,7 +11,7 @@ import { BaseHUDPart } from "../base_hud_part"; import { DynamicDomAttach } from "../dynamic_dom_attach"; import { enumNotificationType } from "./notifications"; export class HUDUnlockNotification extends BaseHUDPart { - initialize(): any { + initialize() { this.visible = false; this.domAttach = new DynamicDomAttach(this.root, this.element, { timeToKeepSeconds: 0, @@ -22,13 +22,13 @@ export class HUDUnlockNotification extends BaseHUDPart { this.buttonShowTimeout = null; this.root.app.gameAnalytics.noteMinor("game.started"); } - shouldPauseGame(): any { + shouldPauseGame() { return !G_IS_STANDALONE && this.visible; } - createElements(parent: any): any { + createElements(parent) { this.inputReciever = new InputReceiver("unlock-notification"); this.element = makeDiv(parent, "ingame_HUD_UnlockNotification", ["noBlur"]); - const dialog: any = makeDiv(this.element, null, ["dialog"]); + const dialog = makeDiv(this.element, null, ["dialog"]); this.elemTitle = makeDiv(dialog, null, ["title"]); this.elemSubTitle = makeDiv(dialog, null, ["subTitle"], T.ingame.levelCompleteNotification.completed); this.elemContents = makeDiv(dialog, null, ["contents"]); @@ -38,9 +38,9 @@ export class HUDUnlockNotification extends BaseHUDPart { dialog.appendChild(this.btnClose); this.trackClicks(this.btnClose, this.requestClose); } - showForLevel(level: number, reward: enumHubGoalRewards): any { + showForLevel(level: number, reward: enumHubGoalRewards) { this.root.soundProxy.playUi(SOUNDS.levelComplete); - const levels: any = this.root.gameMode.getLevelDefinitions(); + const levels = this.root.gameMode.getLevelDefinitions(); // Don't use getIsFreeplay() because we want the freeplay level up to show if (level > levels.length) { this.root.hud.signals.notification.dispatch(T.ingame.notifications.freeplayLevelComplete.replace("", String(level)), enumNotificationType.success); @@ -49,8 +49,8 @@ export class HUDUnlockNotification extends BaseHUDPart { this.root.app.gameAnalytics.noteMinor("game.level.complete-" + level); this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever); this.elemTitle.innerText = T.ingame.levelCompleteNotification.levelTitle.replace("", ("" + level).padStart(2, "0")); - const rewardName: any = T.storyRewards[reward].title; - let html: any = ` + const rewardName = T.storyRewards[reward].title; + let html = `
${T.ingame.levelCompleteNotification.unlockText.replace("", rewardName)}
@@ -61,10 +61,10 @@ export class HUDUnlockNotification extends BaseHUDPart { `; html += "
"; - const gained: any = enumHubGoalRewardsToContentUnlocked[reward]; + const gained = enumHubGoalRewardsToContentUnlocked[reward]; if (gained) { - gained.forEach(([metaBuildingClass, variant]: any): any => { - const metaBuilding: any = gMetaBuildingRegistry.findByClass(metaBuildingClass); + gained.forEach(([metaBuildingClass, variant]) => { + const metaBuilding = gMetaBuildingRegistry.findByClass(metaBuildingClass); html += `
`; }); } @@ -76,24 +76,24 @@ export class HUDUnlockNotification extends BaseHUDPart { } this.element.querySelector("button.close").classList.remove("unlocked"); if (this.root.app.settings.getAllSettings().offerHints) { - this.buttonShowTimeout = setTimeout((): any => this.element.querySelector("button.close").classList.add("unlocked"), G_IS_DEV ? 100 : 1500); + this.buttonShowTimeout = setTimeout(() => this.element.querySelector("button.close").classList.add("unlocked"), G_IS_DEV ? 100 : 1500); } else { this.element.querySelector("button.close").classList.add("unlocked"); } } - cleanup(): any { + cleanup() { this.root.app.inputMgr.makeSureDetached(this.inputReciever); if (this.buttonShowTimeout) { clearTimeout(this.buttonShowTimeout); this.buttonShowTimeout = null; } } - isBlockingOverlay(): any { + isBlockingOverlay() { return this.visible; } - requestClose(): any { - this.root.app.adProvider.showVideoAd().then((): any => { + requestClose() { + this.root.app.adProvider.showVideoAd().then(() => { this.close(); this.root.hud.signals.unlockNotificationFinished.dispatch(); if (this.root.hubGoals.level > this.root.gameMode.getLevelDefinitions().length - 1 && @@ -104,16 +104,16 @@ export class HUDUnlockNotification extends BaseHUDPart { return; } if (this.root.hubGoals.level === 3) { - const { showUpgrades }: any = this.root.hud.parts.dialogs.showInfo(T.dialogs.upgradesIntroduction.title, T.dialogs.upgradesIntroduction.desc, ["showUpgrades:good:timeout"]); - showUpgrades.add((): any => this.root.hud.parts.shop.show()); + const { showUpgrades } = this.root.hud.parts.dialogs.showInfo(T.dialogs.upgradesIntroduction.title, T.dialogs.upgradesIntroduction.desc, ["showUpgrades:good:timeout"]); + showUpgrades.add(() => this.root.hud.parts.shop.show()); } if (this.root.hubGoals.level === 5) { - const { showKeybindings }: any = this.root.hud.parts.dialogs.showInfo(T.dialogs.keybindingsIntroduction.title, T.dialogs.keybindingsIntroduction.desc, ["showKeybindings:misc", "ok:good:timeout"]); - showKeybindings.add((): any => this.root.gameState.goToKeybindings()); + const { showKeybindings } = this.root.hud.parts.dialogs.showInfo(T.dialogs.keybindingsIntroduction.title, T.dialogs.keybindingsIntroduction.desc, ["showKeybindings:misc", "ok:good:timeout"]); + showKeybindings.add(() => this.root.gameState.goToKeybindings()); } }); } - close(): any { + close() { this.root.app.inputMgr.makeSureDetached(this.inputReciever); if (this.buttonShowTimeout) { clearTimeout(this.buttonShowTimeout); @@ -121,7 +121,7 @@ export class HUDUnlockNotification extends BaseHUDPart { } this.visible = false; } - update(): any { + update() { this.domAttach.update(this.visible); if (!this.visible && this.buttonShowTimeout) { clearTimeout(this.buttonShowTimeout); diff --git a/src/ts/game/hud/parts/vignette_overlay.ts b/src/ts/game/hud/parts/vignette_overlay.ts index 92b4e76a..f464f5cd 100644 --- a/src/ts/game/hud/parts/vignette_overlay.ts +++ b/src/ts/game/hud/parts/vignette_overlay.ts @@ -1,8 +1,8 @@ import { BaseHUDPart } from "../base_hud_part"; import { makeDiv } from "../../../core/utils"; export class HUDVignetteOverlay extends BaseHUDPart { - createElements(parent: any): any { + createElements(parent) { this.element = makeDiv(parent, "ingame_VignetteOverlay"); } - initialize(): any { } + initialize() { } } diff --git a/src/ts/game/hud/parts/watermark.ts b/src/ts/game/hud/parts/watermark.ts index 6d4beb1b..ec8da0a9 100644 --- a/src/ts/game/hud/parts/watermark.ts +++ b/src/ts/game/hud/parts/watermark.ts @@ -3,20 +3,20 @@ import { makeDiv } from "../../../core/utils"; import { T } from "../../../translations"; import { BaseHUDPart } from "../base_hud_part"; export class HUDWatermark extends BaseHUDPart { - createElements(parent: any): any { - let linkText: any = T.ingame.watermark.get_on_steam; + createElements(parent) { + let linkText = T.ingame.watermark.get_on_steam; this.linkElement = makeDiv(parent, "ingame_HUD_WatermarkClicker", globalConfig.currentDiscount > 0 ? ["withDiscount"] : [], linkText + (globalConfig.currentDiscount > 0 ? `${T.global.discount.replace("", String(globalConfig.currentDiscount))}` : "")); - this.trackClicks(this.linkElement, (): any => { + this.trackClicks(this.linkElement, () => { openStandaloneLink(this.root.app, "shapez_watermark"); }); } - initialize(): any { } - update(): any { } - drawOverlays(parameters: import("../../../core/draw_utils").DrawParameters): any { - const w: any = this.root.gameWidth; + initialize() { } + update() { } + drawOverlays(parameters: import("../../../core/draw_utils").DrawParameters) { + const w = this.root.gameWidth; parameters.context.fillStyle = "rgba(20, 30, 40, 0.25)"; parameters.context.font = "bold " + this.root.app.getEffectiveUiScale() * 40 + "px GameFont"; parameters.context.textAlign = "center"; diff --git a/src/ts/game/hud/parts/waypoints.ts b/src/ts/game/hud/parts/waypoints.ts index ec6727d8..acf8ffe2 100644 --- a/src/ts/game/hud/parts/waypoints.ts +++ b/src/ts/game/hud/parts/waypoints.ts @@ -32,12 +32,12 @@ export type Waypoint = { /** * Used when a shape icon is rendered instead */ -const MAX_LABEL_LENGTH: any = 71; +const MAX_LABEL_LENGTH = 71; export class HUDWaypoints extends BaseHUDPart { /** * Creates the overview of waypoints */ - createElements(parent: HTMLElement): any { + createElements(parent: HTMLElement) { // Create the helper box on the lower right when zooming out if (this.root.app.settings.getAllSettings().offerHints) { this.hintElement = makeDiv(parent, "ingame_HUD_Waypoints_Hint", [], ` @@ -53,7 +53,7 @@ export class HUDWaypoints extends BaseHUDPart { /** * Serializes the waypoints */ - serialize(): any { + serialize() { return { waypoints: this.waypoints, }; @@ -63,7 +63,7 @@ export class HUDWaypoints extends BaseHUDPart { */ deserialize(data: { waypoints: Array; - }): any { + }) { if (!data || !data.waypoints || !Array.isArray(data.waypoints)) { return "Invalid waypoints data"; } @@ -73,7 +73,7 @@ export class HUDWaypoints extends BaseHUDPart { /** * Initializes everything */ - initialize(): any { + initialize() { // Cache the sprite for the waypoints this.waypointSprites = { regular: Loader.getSprite("sprites/misc/waypoint.png"), @@ -100,7 +100,7 @@ export class HUDWaypoints extends BaseHUDPart { this.root.camera.downPreHandler.add(this.onMouseDown, this); this.root.keyMapper .getBinding(KEYMAPPINGS.navigation.createMarker) - .add((): any => this.requestSaveMarker({})); + .add(() => this.requestSaveMarker({})); /** * Stores at how much opacity the markers should be rendered on the map. * This is interpolated over multiple frames so we have some sort of fade effect @@ -108,7 +108,7 @@ export class HUDWaypoints extends BaseHUDPart { this.currentMarkerOpacity = 1; this.currentCompassOpacity = 0; // Create buffer which is used to indicate the hub direction - const [canvas, context]: any = makeOffscreenBuffer(48, 48, { + const [canvas, context] = makeOffscreenBuffer(48, 48, { smooth: true, reusable: false, label: "waypoints-compass", @@ -139,35 +139,35 @@ export class HUDWaypoints extends BaseHUDPart { /** * Returns how big the text should be rendered */ - getTextScale(): any { + getTextScale() { return this.getWaypointUiScale() * 12; } /** * Returns the scale for rendering waypoints */ - getWaypointUiScale(): any { + getWaypointUiScale() { return this.root.app.getEffectiveUiScale(); } /** * Re-renders the waypoint list to account for changes */ - rerenderWaypointList(): any { + rerenderWaypointList() { removeAllChildren(this.waypointsListElement); this.cleanupClickDetectors(); - for (let i: any = 0; i < this.waypoints.length; ++i) { - const waypoint: any = this.waypoints[i]; - const label: any = this.getWaypointLabel(waypoint); - const element: any = makeDiv(this.waypointsListElement, null, [ + for (let i = 0; i < this.waypoints.length; ++i) { + const waypoint = this.waypoints[i]; + const label = this.getWaypointLabel(waypoint); + const element = makeDiv(this.waypointsListElement, null, [ "waypoint", "layer--" + waypoint.layer, ]); if (ShapeDefinition.isValidShortKey(label)) { - const canvas: any = this.getWaypointCanvas(waypoint); + const canvas = this.getWaypointCanvas(waypoint); /** * Create a clone of the cached canvas, as calling appendElement when a canvas is * already in the document will move the existing canvas to the new position. */ - const [newCanvas, context]: any = makeOffscreenBuffer(48, 48, { + const [newCanvas, context] = makeOffscreenBuffer(48, 48, { smooth: true, label: label + "-waypoint-" + i, }); @@ -179,15 +179,15 @@ export class HUDWaypoints extends BaseHUDPart { element.innerText = label; } if (this.isWaypointDeletable(waypoint)) { - const editButton: any = makeDiv(element, null, ["editButton"]); - this.trackClicks(editButton, (): any => this.requestSaveMarker({ waypoint })); + const editButton = makeDiv(element, null, ["editButton"]); + this.trackClicks(editButton, () => this.requestSaveMarker({ waypoint })); } if (!waypoint.label) { // This must be the hub label element.classList.add("hub"); element.insertBefore(this.compassBuffer.canvas, element.childNodes[0]); } - this.trackClicks(element, (): any => this.moveToWaypoint(waypoint), { + this.trackClicks(element, () => this.moveToWaypoint(waypoint), { targetOnly: true, }); } @@ -195,7 +195,7 @@ export class HUDWaypoints extends BaseHUDPart { /** * Moves the camera to a given waypoint */ - moveToWaypoint(waypoint: Waypoint): any { + moveToWaypoint(waypoint: Waypoint) { this.root.currentLayer = waypoint.layer; this.root.camera.setDesiredCenter(new Vector(waypoint.center.x, waypoint.center.y)); this.root.camera.setDesiredZoom(waypoint.zoomLevel); @@ -203,7 +203,7 @@ export class HUDWaypoints extends BaseHUDPart { /** * Deletes a waypoint from the list */ - deleteWaypoint(waypoint: Waypoint): any { + deleteWaypoint(waypoint: Waypoint) { arrayDeleteValue(this.waypoints, waypoint); this.rerenderWaypointList(); } @@ -212,13 +212,13 @@ export class HUDWaypoints extends BaseHUDPart { * {} */ getWaypointCanvas(waypoint: Waypoint): HTMLCanvasElement { - const key: any = waypoint.label; + const key = waypoint.label; if (this.cachedKeyToCanvas[key]) { return this.cachedKeyToCanvas[key]; } assert(ShapeDefinition.isValidShortKey(key), "Invalid short key: " + key); - const definition: any = this.root.shapeDefinitionMgr.getShapeFromShortKey(key); - const preRendered: any = definition.generateAsCanvas(48); + const definition = this.root.shapeDefinitionMgr.getShapeFromShortKey(key); + const preRendered = definition.generateAsCanvas(48); return (this.cachedKeyToCanvas[key] = preRendered); } /** @@ -228,16 +228,16 @@ export class HUDWaypoints extends BaseHUDPart { requestSaveMarker({ worldPos = null, waypoint = null }: { worldPos: Vector=; waypoint: Waypoint=; - }): any { + }) { // Construct dialog with input field - const markerNameInput: any = new FormElementInput({ + const markerNameInput = new FormElementInput({ id: "markerName", label: null, placeholder: "", defaultValue: waypoint ? waypoint.label : "", - validator: (val: any): any => val.length > 0 && (val.length < MAX_LABEL_LENGTH || ShapeDefinition.isValidShortKey(val)), + validator: val => val.length > 0 && (val.length < MAX_LABEL_LENGTH || ShapeDefinition.isValidShortKey(val)), }); - const dialog: any = new DialogWithForm({ + const dialog = new DialogWithForm({ app: this.root.app, title: waypoint ? T.dialogs.createMarker.titleEdit : T.dialogs.createMarker.title, desc: fillInLinkIntoTranslation(T.dialogs.createMarker.desc, THIRDPARTY_URLS.shapeViewer), @@ -247,19 +247,19 @@ export class HUDWaypoints extends BaseHUDPart { this.root.hud.parts.dialogs.internalShowDialog(dialog); // Edit marker if (waypoint) { - dialog.buttonSignals.ok.add((): any => { + dialog.buttonSignals.ok.add(() => { // Actually rename the waypoint this.renameWaypoint(waypoint, markerNameInput.getValue()); }); - dialog.buttonSignals.delete.add((): any => { + dialog.buttonSignals.delete.add(() => { // Actually delete the waypoint this.deleteWaypoint(waypoint); }); } else { // Compute where to create the marker - const center: any = worldPos || this.root.camera.center; - dialog.buttonSignals.ok.add((): any => { + const center = worldPos || this.root.camera.center; + dialog.buttonSignals.ok.add(() => { // Show info that you can have only N markers in the demo, // actually show this *after* entering the name so you want the // standalone even more (I'm evil :P) @@ -275,7 +275,7 @@ export class HUDWaypoints extends BaseHUDPart { /** * Adds a new waypoint at the given location with the given label */ - addWaypoint(label: string, position: Vector): any { + addWaypoint(label: string, position: Vector) { this.waypoints.push({ label, center: { x: position.x, y: position.y }, @@ -293,7 +293,7 @@ export class HUDWaypoints extends BaseHUDPart { /** * Renames a waypoint with the given label */ - renameWaypoint(waypoint: Waypoint, label: string): any { + renameWaypoint(waypoint: Waypoint, label: string) { waypoint.label = label; this.sortWaypoints(); // Show notification about renamed @@ -304,7 +304,7 @@ export class HUDWaypoints extends BaseHUDPart { /** * Called every frame to update stuff */ - update(): any { + update() { if (this.domAttach) { this.domAttach.update(this.root.camera.getIsMapOverlayActive()); } @@ -312,8 +312,8 @@ export class HUDWaypoints extends BaseHUDPart { /** * Sort waypoints by name */ - sortWaypoints(): any { - this.waypoints.sort((a: any, b: any): any => { + sortWaypoints() { + this.waypoints.sort((a, b) => { if (!a.label) { return -1; } @@ -357,11 +357,11 @@ export class HUDWaypoints extends BaseHUDPart { return null; } // Find parameters - const scale: any = this.getWaypointUiScale(); - const screenPos: any = this.root.camera.worldToScreen(new Vector(waypoint.center.x, waypoint.center.y)); + const scale = this.getWaypointUiScale(); + const screenPos = this.root.camera.worldToScreen(new Vector(waypoint.center.x, waypoint.center.y)); // Distinguish between text and item waypoints -> Figure out parameters - const originalLabel: any = this.getWaypointLabel(waypoint); - let text: any, item: any, textWidth: any; + const originalLabel = this.getWaypointLabel(waypoint); + let text, item, textWidth; if (ShapeDefinition.isValidShortKey(originalLabel)) { // If the label is actually a key, render the shape icon item = this.root.shapeDefinitionMgr.getShapeItemFromShortKey(originalLabel); @@ -385,13 +385,13 @@ export class HUDWaypoints extends BaseHUDPart { * {} */ findCurrentIntersectedWaypoint(): Waypoint | null { - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (!mousePos) { return; } - for (let i: any = 0; i < this.waypoints.length; ++i) { - const waypoint: any = this.waypoints[i]; - const params: any = this.getWaypointScreenParams(waypoint); + for (let i = 0; i < this.waypoints.length; ++i) { + const waypoint = this.waypoints[i]; + const params = this.getWaypointScreenParams(waypoint); if (params && params.screenBounds.containsPoint(mousePos.x, mousePos.y)) { return waypoint; } @@ -400,8 +400,8 @@ export class HUDWaypoints extends BaseHUDPart { /** * Mouse-Down handler */ - onMouseDown(pos: Vector, button: enumMouseButton): any { - const waypoint: any = this.findCurrentIntersectedWaypoint(); + onMouseDown(pos: Vector, button: enumMouseButton) { + const waypoint = this.findCurrentIntersectedWaypoint(); if (waypoint) { if (button === enumMouseButton.left) { this.root.soundProxy.playUiClick(); @@ -422,7 +422,7 @@ export class HUDWaypoints extends BaseHUDPart { // Allow right click to create a marker if (button === enumMouseButton.right) { if (this.root.camera.getIsMapOverlayActive()) { - const worldPos: any = this.root.camera.screenToWorld(pos); + const worldPos = this.root.camera.screenToWorld(pos); this.requestSaveMarker({ worldPos }); return STOP_PROPAGATION; } @@ -432,21 +432,21 @@ export class HUDWaypoints extends BaseHUDPart { /** * Rerenders the compass */ - rerenderWaypointsCompass(): any { - const dims: any = 48; - const indicatorSize: any = 30; - const cameraPos: any = this.root.camera.center; - const context: any = this.compassBuffer.context; + rerenderWaypointsCompass() { + const dims = 48; + const indicatorSize = 30; + const cameraPos = this.root.camera.center; + const context = this.compassBuffer.context; context.clearRect(0, 0, dims, dims); - const distanceToHub: any = cameraPos.length(); - const compassVisible: any = distanceToHub > (10 * globalConfig.tileSize) / this.root.camera.zoomLevel; - const targetCompassAlpha: any = compassVisible ? 1 : 0; + const distanceToHub = cameraPos.length(); + const compassVisible = distanceToHub > (10 * globalConfig.tileSize) / this.root.camera.zoomLevel; + const targetCompassAlpha = compassVisible ? 1 : 0; // Fade the compas in / out this.currentCompassOpacity = lerp(this.currentCompassOpacity, targetCompassAlpha, 0.08); // Render the compass if (this.currentCompassOpacity > 0.01) { context.globalAlpha = this.currentCompassOpacity; - const angle: any = cameraPos.angle() + Math.radians(45) + Math.PI / 2; + const angle = cameraPos.angle() + Math.radians(45) + Math.PI / 2; context.translate(dims / 2, dims / 2); context.rotate(angle); this.directionIndicatorSprite.drawCentered(context, 0, 0, indicatorSize); @@ -455,7 +455,7 @@ export class HUDWaypoints extends BaseHUDPart { context.globalAlpha = 1; } // Render the regualr icon - const iconOpacity: any = 1 - this.currentCompassOpacity; + const iconOpacity = 1 - this.currentCompassOpacity; if (iconOpacity > 0.01) { context.globalAlpha = iconOpacity; this.waypointSprites.regular.drawCentered(context, dims / 2, dims / 2, dims * 0.7); @@ -465,9 +465,9 @@ export class HUDWaypoints extends BaseHUDPart { /** * Draws the waypoints on the map */ - drawOverlays(parameters: DrawParameters): any { - const mousePos: any = this.root.app.mousePosition; - const desiredOpacity: any = this.root.camera.getIsMapOverlayActive() ? 1 : 0; + drawOverlays(parameters: DrawParameters) { + const mousePos = this.root.app.mousePosition; + const desiredOpacity = this.root.camera.getIsMapOverlayActive() ? 1 : 0; this.currentMarkerOpacity = lerp(this.currentMarkerOpacity, desiredOpacity, 0.08); this.rerenderWaypointsCompass(); // Don't render with low opacity @@ -475,15 +475,15 @@ export class HUDWaypoints extends BaseHUDPart { return; } // Determine rendering scale - const scale: any = this.getWaypointUiScale(); + const scale = this.getWaypointUiScale(); // Set the font size - const textSize: any = this.getTextScale(); + const textSize = this.getTextScale(); parameters.context.font = "bold " + textSize + "px GameFont"; parameters.context.textBaseline = "middle"; // Loop over all waypoints - for (let i: any = 0; i < this.waypoints.length; ++i) { - const waypoint: any = this.waypoints[i]; - const waypointData: any = this.getWaypointScreenParams(waypoint); + for (let i = 0; i < this.waypoints.length; ++i) { + const waypoint = this.waypoints[i]; + const waypointData = this.getWaypointScreenParams(waypoint); if (!waypointData) { // Not relevant continue; @@ -492,9 +492,9 @@ export class HUDWaypoints extends BaseHUDPart { // Out of screen continue; } - const bounds: any = waypointData.screenBounds; - const contentPaddingX: any = 7 * scale; - const isSelected: any = mousePos && bounds.containsPoint(mousePos.x, mousePos.y); + const bounds = waypointData.screenBounds; + const contentPaddingX = 7 * scale; + const isSelected = mousePos && bounds.containsPoint(mousePos.x, mousePos.y); // Render the background rectangle parameters.context.globalAlpha = this.currentMarkerOpacity * (isSelected ? 1 : 0.7); parameters.context.fillStyle = "rgba(255, 255, 255, 0.7)"; @@ -502,8 +502,8 @@ export class HUDWaypoints extends BaseHUDPart { parameters.context.fill(); // Render the text if (waypointData.item) { - const canvas: any = this.getWaypointCanvas(waypoint); - const itemSize: any = 14 * scale; + const canvas = this.getWaypointCanvas(waypoint); + const itemSize = 14 * scale; parameters.context.drawImage(canvas, bounds.x + contentPaddingX + 6 * scale, bounds.y + bounds.h / 2 - itemSize / 2, itemSize, itemSize); } else if (waypointData.text) { diff --git a/src/ts/game/hud/parts/wire_info.ts b/src/ts/game/hud/parts/wire_info.ts index 0190536e..597fc089 100644 --- a/src/ts/game/hud/parts/wire_info.ts +++ b/src/ts/game/hud/parts/wire_info.ts @@ -5,23 +5,23 @@ import { THEME } from "../../theme"; import { BaseHUDPart } from "../base_hud_part"; import { Loader } from "../../../core/loader"; export class HUDWireInfo extends BaseHUDPart { - initialize(): any { + initialize() { this.spriteEmpty = Loader.getSprite("sprites/wires/network_empty.png"); this.spriteConflict = Loader.getSprite("sprites/wires/network_conflict.png"); } - drawOverlays(parameters: import("../../../core/draw_utils").DrawParameters): any { + drawOverlays(parameters: import("../../../core/draw_utils").DrawParameters) { if (this.root.currentLayer !== "wires") { // Not in the wires layer return; } - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (!mousePos) { // No mouse return; } - const worldPos: any = this.root.camera.screenToWorld(mousePos); - const tile: any = worldPos.toTileSpace(); - const entity: any = this.root.map.getLayerContentXY(tile.x, tile.y, "wires"); + const worldPos = this.root.camera.screenToWorld(mousePos); + const tile = worldPos.toTileSpace(); + const entity = this.root.map.getLayerContentXY(tile.x, tile.y, "wires"); if (!entity) { // No entity return; @@ -31,7 +31,7 @@ export class HUDWireInfo extends BaseHUDPart { // Detailed intersection check return; } - const networks: any = this.root.logic.getEntityWireNetworks(entity, tile); + const networks = this.root.logic.getEntityWireNetworks(entity, tile); if (networks === null) { // This entity will never be able to be connected return; @@ -40,12 +40,12 @@ export class HUDWireInfo extends BaseHUDPart { // No network at all return; } - for (let i: any = 0; i < networks.length; ++i) { - const network: any = networks[i]; + for (let i = 0; i < networks.length; ++i) { + const network = networks[i]; this.drawHighlightedNetwork(parameters, network); } if (networks.length === 1) { - const network: any = networks[0]; + const network = networks[0]; if (network.valueConflict) { this.spriteConflict.draw(parameters.context, mousePos.x + 15, mousePos.y - 10, 60, 60); } @@ -57,12 +57,12 @@ export class HUDWireInfo extends BaseHUDPart { } } } - drawHighlightedNetwork(parameters: import("../../../core/draw_utils").DrawParameters, network: WireNetwork): any { + drawHighlightedNetwork(parameters: import("../../../core/draw_utils").DrawParameters, network: WireNetwork) { parameters.context.globalAlpha = 0.5; - for (let i: any = 0; i < network.wires.length; ++i) { - const wire: any = network.wires[i]; - const staticComp: any = wire.components.StaticMapEntity; - const screenTile: any = this.root.camera.worldToScreen(staticComp.origin.toWorldSpace()); + for (let i = 0; i < network.wires.length; ++i) { + const wire = network.wires[i]; + const staticComp = wire.components.StaticMapEntity; + const screenTile = this.root.camera.worldToScreen(staticComp.origin.toWorldSpace()); MapChunkView.drawSingleWiresOverviewTile({ context: parameters.context, x: screenTile.x, @@ -72,10 +72,10 @@ export class HUDWireInfo extends BaseHUDPart { overrideColor: THEME.map.wires.highlightColor, }); } - for (let i: any = 0; i < network.tunnels.length; ++i) { - const tunnel: any = network.tunnels[i]; - const staticComp: any = tunnel.components.StaticMapEntity; - const screenTile: any = this.root.camera.worldToScreen(staticComp.origin.toWorldSpace()); + for (let i = 0; i < network.tunnels.length; ++i) { + const tunnel = network.tunnels[i]; + const staticComp = tunnel.components.StaticMapEntity; + const screenTile = this.root.camera.worldToScreen(staticComp.origin.toWorldSpace()); MapChunkView.drawSingleWiresOverviewTile({ context: parameters.context, x: screenTile.x, diff --git a/src/ts/game/hud/parts/wires_overlay.ts b/src/ts/game/hud/parts/wires_overlay.ts index 24696e6b..cc6c6fbb 100644 --- a/src/ts/game/hud/parts/wires_overlay.ts +++ b/src/ts/game/hud/parts/wires_overlay.ts @@ -7,11 +7,11 @@ import { SOUNDS } from "../../../platform/sound"; import { KEYMAPPINGS } from "../../key_action_mapper"; import { enumHubGoalRewards } from "../../tutorial_goals"; import { BaseHUDPart } from "../base_hud_part"; -const copy: any = require("clipboard-copy"); -const wiresBackgroundDpi: any = 4; +const copy = require("clipboard-copy"); +const wiresBackgroundDpi = 4; export class HUDWiresOverlay extends BaseHUDPart { - createElements(parent: any): any { } - initialize(): any { + createElements(parent) { } + initialize() { // Probably not the best location, but the one which makes most sense this.root.keyMapper.getBinding(KEYMAPPINGS.ingame.switchLayers).add(this.switchLayers, this); this.root.keyMapper.getBinding(KEYMAPPINGS.placement.copyWireValue).add(this.copyWireValue, this); @@ -21,7 +21,7 @@ export class HUDWiresOverlay extends BaseHUDPart { /** * Switches between layers */ - switchLayers(): any { + switchLayers() { if (!this.root.gameMode.getSupportsWires()) { return; } @@ -39,10 +39,10 @@ export class HUDWiresOverlay extends BaseHUDPart { /** * Generates the background pattern for the wires overlay */ - generateTilePattern(): any { - const overlayTile: any = Loader.getSprite("sprites/wires/overlay_tile.png"); - const dims: any = globalConfig.tileSize * wiresBackgroundDpi; - const [canvas, context]: any = makeOffscreenBuffer(dims, dims, { + generateTilePattern() { + const overlayTile = Loader.getSprite("sprites/wires/overlay_tile.png"); + const dims = globalConfig.tileSize * wiresBackgroundDpi; + const [canvas, context] = makeOffscreenBuffer(dims, dims, { smooth: false, reusable: false, label: "wires-tile-pattern", @@ -51,8 +51,8 @@ export class HUDWiresOverlay extends BaseHUDPart { overlayTile.draw(context, 0, 0, dims, dims); this.tilePatternCanvas = canvas; } - update(): any { - const desiredAlpha: any = this.root.currentLayer === "wires" ? 1.0 : 0.0; + update() { + const desiredAlpha = this.root.currentLayer === "wires" ? 1.0 : 0.0; // On low performance, skip the fade if (this.root.entityMgr.entities.length > 5000 || this.root.dynamicTickrate.averageFps < 50) { this.currentAlpha = desiredAlpha; @@ -64,22 +64,22 @@ export class HUDWiresOverlay extends BaseHUDPart { /** * Copies the wires value below the cursor */ - copyWireValue(): any { + copyWireValue() { if (this.root.currentLayer !== "wires") { return; } - const mousePos: any = this.root.app.mousePosition; + const mousePos = this.root.app.mousePosition; if (!mousePos) { return; } - const tile: any = this.root.camera.screenToWorld(mousePos).toTileSpace(); - const contents: any = this.root.map.getLayerContentXY(tile.x, tile.y, "wires"); + const tile = this.root.camera.screenToWorld(mousePos).toTileSpace(); + const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "wires"); if (!contents) { return; } - let value: any = null; + let value = null; if (contents.components.Wire) { - const network: any = contents.components.Wire.linkedNetwork; + const network = contents.components.Wire.linkedNetwork; if (network && network.hasValue()) { value = network.currentValue; } @@ -96,17 +96,17 @@ export class HUDWiresOverlay extends BaseHUDPart { this.root.soundProxy.playUiError(); } } - draw(parameters: DrawParameters): any { + draw(parameters: DrawParameters) { if (this.currentAlpha < 0.02) { return; } - const hasTileGrid: any = !this.root.app.settings.getAllSettings().disableTileGrid; + const hasTileGrid = !this.root.app.settings.getAllSettings().disableTileGrid; if (hasTileGrid && !this.cachedPatternBackground) { this.cachedPatternBackground = parameters.context.createPattern(this.tilePatternCanvas, "repeat"); } - const bounds: any = parameters.visibleRect; + const bounds = parameters.visibleRect; parameters.context.globalAlpha = this.currentAlpha; - const scaleFactor: any = 1 / wiresBackgroundDpi; + const scaleFactor = 1 / wiresBackgroundDpi; parameters.context.globalCompositeOperation = "overlay"; parameters.context.fillStyle = "rgba(50, 200, 150, 1)"; parameters.context.fillRect(bounds.x, bounds.y, bounds.w, bounds.h); diff --git a/src/ts/game/hud/parts/wires_toolbar.ts b/src/ts/game/hud/parts/wires_toolbar.ts index 99d99136..375cd64e 100644 --- a/src/ts/game/hud/parts/wires_toolbar.ts +++ b/src/ts/game/hud/parts/wires_toolbar.ts @@ -33,7 +33,7 @@ export class HUDWiresToolbar extends HUDBaseToolbar { MetaFilterBuilding, MetaDisplayBuilding, ], - visibilityCondition: (): any => !this.root.camera.getIsMapOverlayActive() && this.root.currentLayer === "wires", + visibilityCondition: () => !this.root.camera.getIsMapOverlayActive() && this.root.currentLayer === "wires", htmlElementId: "ingame_HUD_wires_toolbar", layer: "wires", }); diff --git a/src/ts/game/hud/trailer_maker.ts b/src/ts/game/hud/trailer_maker.ts index b3a757c0..4cc4f636 100644 --- a/src/ts/game/hud/trailer_maker.ts +++ b/src/ts/game/hud/trailer_maker.ts @@ -4,7 +4,7 @@ import { Vector, mixVector } from "../../core/vector"; import { lerp } from "../../core/utils"; /* dev:start */ import trailerPoints from "./trailer_points"; -const tickrate: any = 1 / 165; +const tickrate = 1 / 165; export class TrailerMaker { public root = root; public markers = []; @@ -13,7 +13,7 @@ export class TrailerMaker { public currentPlaybackZoom = 3; constructor(root) { - window.addEventListener("keydown", (ev: any): any => { + window.addEventListener("keydown", ev => { if (ev.key === "j") { console.log("Record"); this.markers.push({ @@ -25,8 +25,8 @@ export class TrailerMaker { } else if (ev.key === "k") { console.log("Export"); - const json: any = JSON.stringify(this.markers); - const handle: any = window.open("about:blank"); + const json = JSON.stringify(this.markers); + const handle = window.open("about:blank"); handle.document.write(json); } else if (ev.key === "u") { @@ -35,7 +35,7 @@ export class TrailerMaker { return; } console.log("Playback"); - this.playbackMarkers = trailerPoints.map((p: any): any => Object.assign({}, p)); + this.playbackMarkers = trailerPoints.map(p => Object.assign({}, p)); this.playbackMarkers.unshift(this.playbackMarkers[0]); this.currentPlaybackOrigin = Vector.fromSerializedObject(this.playbackMarkers[0].pos); this.currentPlaybackZoom = this.playbackMarkers[0].zoom; @@ -66,20 +66,20 @@ export class TrailerMaker { } }); } - update(): any { + update() { if (this.playbackMarkers && this.playbackMarkers.length > 0) { - const nextMarker: any = this.playbackMarkers[0]; + const nextMarker = this.playbackMarkers[0]; if (!nextMarker.startTime) { console.log("Starting to approach", nextMarker.pos); nextMarker.startTime = performance.now() / 1000.0; } - const speed: any = globalConfig.tileSize * + const speed = globalConfig.tileSize * globalConfig.beltSpeedItemsPerSecond * globalConfig.itemSpacingOnBelts; // let time = // this.currentPlaybackOrigin.distance(Vector.fromSerializedObject(nextMarker.pos)) / speed; - const time: any = nextMarker.time; - const progress: any = (performance.now() / 1000.0 - nextMarker.startTime) / time; + const time = nextMarker.time; + const progress = (performance.now() / 1000.0 - nextMarker.startTime) / time; if (progress > 1.0) { if (nextMarker.wait > 0) { nextMarker.wait -= tickrate; @@ -92,10 +92,10 @@ export class TrailerMaker { } return; } - const targetPos: any = Vector.fromSerializedObject(nextMarker.pos); - const targetZoom: any = nextMarker.zoom; - const pos: any = mixVector(this.currentPlaybackOrigin, targetPos, progress); - const zoom: any = lerp(this.currentPlaybackZoom, targetZoom, progress); + const targetPos = Vector.fromSerializedObject(nextMarker.pos); + const targetZoom = nextMarker.zoom; + const pos = mixVector(this.currentPlaybackOrigin, targetPos, progress); + const zoom = lerp(this.currentPlaybackZoom, targetZoom, progress); this.root.camera.zoomLevel = zoom; this.root.camera.center = pos; } diff --git a/src/ts/game/item_registry.ts b/src/ts/game/item_registry.ts index 33122b28..8b7b208b 100644 --- a/src/ts/game/item_registry.ts +++ b/src/ts/game/item_registry.ts @@ -2,7 +2,7 @@ import { gItemRegistry } from "../core/global_registries"; import { ShapeItem } from "./items/shape_item"; import { ColorItem } from "./items/color_item"; import { BooleanItem } from "./items/boolean_item"; -export function initItemRegistry(): any { +export function initItemRegistry() { gItemRegistry.register(ShapeItem); gItemRegistry.register(ColorItem); gItemRegistry.register(BooleanItem); diff --git a/src/ts/game/item_resolver.ts b/src/ts/game/item_resolver.ts index fef4f88f..a91b3d7f 100644 --- a/src/ts/game/item_resolver.ts +++ b/src/ts/game/item_resolver.ts @@ -3,16 +3,16 @@ import { gItemRegistry } from "../core/global_registries"; import { BooleanItem, BOOL_TRUE_SINGLETON, BOOL_FALSE_SINGLETON } from "./items/boolean_item"; import { ShapeItem } from "./items/shape_item"; import { ColorItem, COLOR_ITEM_SINGLETONS } from "./items/color_item"; -export const MODS_ADDITIONAL_ITEMS: any = {}; +export const MODS_ADDITIONAL_ITEMS = {}; /** * Resolves items so we share instances */ export function itemResolverSingleton(root: import("../savegame/savegame_serializer").GameRoot, data: { $: string; data: any; -}): any { - const itemType: any = data.$; - const itemData: any = data.data; +}) { + const itemType = data.$; + const itemData = data.data; if (MODS_ADDITIONAL_ITEMS[itemType]) { return MODS_ADDITIONAL_ITEMS[itemType](itemData, root); } @@ -31,4 +31,4 @@ export function itemResolverSingleton(root: import("../savegame/savegame_seriali } } } -export const typeItemSingleton: any = types.obj(gItemRegistry, itemResolverSingleton); +export const typeItemSingleton = types.obj(gItemRegistry, itemResolverSingleton); diff --git a/src/ts/game/items/boolean_item.ts b/src/ts/game/items/boolean_item.ts index a53f26f4..53158f6c 100644 --- a/src/ts/game/items/boolean_item.ts +++ b/src/ts/game/items/boolean_item.ts @@ -4,16 +4,16 @@ import { types } from "../../savegame/serialization"; import { BaseItem } from "../base_item"; import { globalConfig } from "../../core/config"; export class BooleanItem extends BaseItem { - static getId(): any { + static getId() { return "boolean_item"; } - static getSchema(): any { + static getSchema() { return types.uint; } - serialize(): any { + serialize() { return this.value; } - deserialize(data: any): any { + deserialize(data) { this.value = data; } /** {} **/ @@ -31,11 +31,11 @@ export class BooleanItem extends BaseItem { constructor(value) { super(); } - equalsImpl(other: BaseItem): any { + equalsImpl(other: BaseItem) { return this.value === other as BooleanItem).value; } - drawItemCenteredImpl(x: number, y: number, parameters: DrawParameters, diameter: number = globalConfig.defaultItemDiameter): any { - let sprite: any; + drawItemCenteredImpl(x: number, y: number, parameters: DrawParameters, diameter: number = globalConfig.defaultItemDiameter) { + let sprite; if (this.value) { sprite = Loader.getSprite("sprites/wires/boolean_true.png"); } @@ -47,8 +47,8 @@ export class BooleanItem extends BaseItem { /** * Draws the item to a canvas */ - drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number): any { - let sprite: any; + drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number) { + let sprite; if (this.value) { sprite = Loader.getSprite("sprites/wires/boolean_true.png"); } @@ -58,8 +58,8 @@ export class BooleanItem extends BaseItem { sprite.drawCentered(context, size / 2, size / 2, size); } } -export const BOOL_FALSE_SINGLETON: any = new BooleanItem(0); -export const BOOL_TRUE_SINGLETON: any = new BooleanItem(1); +export const BOOL_FALSE_SINGLETON = new BooleanItem(0); +export const BOOL_TRUE_SINGLETON = new BooleanItem(1); /** * Returns whether the item is Boolean and TRUE * {} diff --git a/src/ts/game/items/color_item.ts b/src/ts/game/items/color_item.ts index 1a7f2a50..c32bdae1 100644 --- a/src/ts/game/items/color_item.ts +++ b/src/ts/game/items/color_item.ts @@ -6,16 +6,16 @@ import { BaseItem } from "../base_item"; import { enumColors } from "../colors"; import { THEME } from "../theme"; export class ColorItem extends BaseItem { - static getId(): any { + static getId() { return "color"; } - static getSchema(): any { + static getSchema() { return types.enum(enumColors); } - serialize(): any { + serialize() { return this.color; } - deserialize(data: any): any { + deserialize(data) { this.color = data; } /** {} **/ @@ -28,7 +28,7 @@ export class ColorItem extends BaseItem { getAsCopyableKey(): string { return this.color; } - equalsImpl(other: BaseItem): any { + equalsImpl(other: BaseItem) { return this.color === other as ColorItem).color; } public color = color; @@ -36,20 +36,20 @@ export class ColorItem extends BaseItem { constructor(color) { super(); } - getBackgroundColorAsResource(): any { + getBackgroundColorAsResource() { return THEME.map.resources[this.color]; } /** * Draws the item to a canvas */ - drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number): any { + drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number) { if (!this.cachedSprite) { this.cachedSprite = Loader.getSprite("sprites/colors/" + this.color + ".png"); } this.cachedSprite.drawCentered(context, size / 2, size / 2, size); } - drawItemCenteredClipped(x: number, y: number, parameters: DrawParameters, diameter: number = globalConfig.defaultItemDiameter): any { - const realDiameter: any = diameter * 0.6; + drawItemCenteredClipped(x: number, y: number, parameters: DrawParameters, diameter: number = globalConfig.defaultItemDiameter) { + const realDiameter = diameter * 0.6; if (!this.cachedSprite) { this.cachedSprite = Loader.getSprite("sprites/colors/" + this.color + ".png"); } @@ -62,6 +62,6 @@ export class ColorItem extends BaseItem { export const COLOR_ITEM_SINGLETONS: { [idx: enumColors]: ColorItem; } = {}; -for (const color: any in enumColors) { +for (const color in enumColors) { COLOR_ITEM_SINGLETONS[color] = new ColorItem(color); } diff --git a/src/ts/game/items/shape_item.ts b/src/ts/game/items/shape_item.ts index 416133c9..aac4df29 100644 --- a/src/ts/game/items/shape_item.ts +++ b/src/ts/game/items/shape_item.ts @@ -5,16 +5,16 @@ import { ShapeDefinition } from "../shape_definition"; import { THEME } from "../theme"; import { globalConfig } from "../../core/config"; export class ShapeItem extends BaseItem { - static getId(): any { + static getId() { return "shape"; } - static getSchema(): any { + static getSchema() { return types.string; } - serialize(): any { + serialize() { return this.definition.getHash(); } - deserialize(data: any): any { + deserialize(data) { this.definition = ShapeDefinition.fromShortKey(data); } /** {} **/ @@ -27,7 +27,7 @@ export class ShapeItem extends BaseItem { getAsCopyableKey(): string { return this.definition.getHash(); } - equalsImpl(other: BaseItem): any { + equalsImpl(other: BaseItem) { return this.definition.getHash() === other as ShapeItem).definition.getHash(); } public definition = definition; @@ -35,16 +35,16 @@ export class ShapeItem extends BaseItem { constructor(definition) { super(); } - getBackgroundColorAsResource(): any { + getBackgroundColorAsResource() { return THEME.map.resources.shape; } /** * Draws the item to a canvas */ - drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number): any { + drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number) { this.definition.drawFullSizeOnCanvas(context, size); } - drawItemCenteredImpl(x: number, y: number, parameters: DrawParameters, diameter: number= = globalConfig.defaultItemDiameter): any { + drawItemCenteredImpl(x: number, y: number, parameters: DrawParameters, diameter: number= = globalConfig.defaultItemDiameter) { this.definition.drawCentered(x, y, parameters, diameter); } } diff --git a/src/ts/game/key_action_mapper.ts b/src/ts/game/key_action_mapper.ts index b7245e3c..4cf2ba94 100644 --- a/src/ts/game/key_action_mapper.ts +++ b/src/ts/game/key_action_mapper.ts @@ -6,10 +6,10 @@ import type { Application } from "../application"; import { Signal, STOP_PROPAGATION } from "../core/signal"; import { IS_MOBILE } from "../core/config"; import { T } from "../translations"; -export function keyToKeyCode(str: any): any { +export function keyToKeyCode(str) { return str.toUpperCase().charCodeAt(0); } -export const KEYCODES: any = { +export const KEYCODES = { Tab: 9, Enter: 13, Shift: 16, @@ -37,7 +37,7 @@ export const KEYCODES: any = { Plus: 187, Minus: 189, }; -export const KEYMAPPINGS: any = { +export const KEYMAPPINGS = { // Make sure mods come first so they can override everything mods: {}, general: { @@ -129,14 +129,14 @@ export const KEYMAPPINGS: any = { }, }; // Assign ids -for (const categoryId: any in KEYMAPPINGS) { - for (const mappingId: any in KEYMAPPINGS[categoryId]) { +for (const categoryId in KEYMAPPINGS) { + for (const mappingId in KEYMAPPINGS[categoryId]) { KEYMAPPINGS[categoryId][mappingId].id = mappingId; } } -export const KEYCODE_LMB: any = 1; -export const KEYCODE_MMB: any = 2; -export const KEYCODE_RMB: any = 3; +export const KEYCODE_LMB = 1; +export const KEYCODE_MMB = 2; +export const KEYCODE_RMB = 3; /** * Returns a keycode -> string * {} @@ -308,7 +308,7 @@ export class Keybinding { // Check if the key is down if (this.app.inputMgr.keysDown.has(this.keyCode)) { // Check if it is the top reciever - const reciever: any = this.keyMapper.inputReceiver; + const reciever = this.keyMapper.inputReceiver; return this.app.inputMgr.getTopReciever() === reciever; } return false; @@ -316,13 +316,13 @@ export class Keybinding { /** * Adds an event listener */ - add(receiver: function():void, scope: object= = null): any { + add(receiver: function():void, scope: object= = null) { this.signal.add(receiver, scope); } /** * Adds an event listener */ - addToTop(receiver: function():void, scope: object= = null): any { + addToTop(receiver: function():void, scope: object= = null) { this.signal.addToTop(receiver, scope); } /** @@ -332,7 +332,7 @@ export class Keybinding { if (IS_MOBILE) { return null; } - const spacer: any = document.createElement("code"); + const spacer = document.createElement("code"); spacer.classList.add("keybinding"); spacer.innerHTML = getStringForKeyCode(this.keyCode); elem.appendChild(spacer); @@ -341,13 +341,13 @@ export class Keybinding { /** * Returns the key code as a nice string */ - getKeyCodeString(): any { + getKeyCodeString() { return getStringForKeyCode(this.keyCode); } /** * Remvoes all signal receivers */ - clearSignalReceivers(): any { + clearSignalReceivers() { this.signal.removeAll(); } } @@ -361,10 +361,10 @@ export class KeyActionMapper { constructor(root, inputReciever) { inputReciever.keydown.add(this.handleKeydown, this); inputReciever.keyup.add(this.handleKeyup, this); - const overrides: any = root.app.settings.getKeybindingOverrides(); - for (const category: any in KEYMAPPINGS) { - for (const key: any in KEYMAPPINGS[category]) { - let payload: any = Object.assign({}, KEYMAPPINGS[category][key]); + const overrides = root.app.settings.getKeybindingOverrides(); + for (const category in KEYMAPPINGS) { + for (const key in KEYMAPPINGS[category]) { + let payload = Object.assign({}, KEYMAPPINGS[category][key]); if (overrides[key]) { payload.keyCode = overrides[key]; } @@ -385,8 +385,8 @@ export class KeyActionMapper { * {} */ getKeybindingsStartingWith(pattern: string): Array { - let result: any = []; - for (const key: any in this.keybindings) { + let result = []; + for (const key in this.keybindings) { if (key.startsWith(pattern)) { result.push(this.keybindings[key]); } @@ -396,21 +396,21 @@ export class KeyActionMapper { /** * Forwards the given events to the other mapper (used in tooltips) */ - forward(receiver: KeyActionMapper, bindings: Array): any { - for (let i: any = 0; i < bindings.length; ++i) { - const key: any = bindings[i]; - this.keybindings[key].signal.add((...args: any): any => receiver.keybindings[key].signal.dispatch(...args)); + forward(receiver: KeyActionMapper, bindings: Array) { + for (let i = 0; i < bindings.length; ++i) { + const key = bindings[i]; + this.keybindings[key].signal.add((...args) => receiver.keybindings[key].signal.dispatch(...args)); } } - cleanup(): any { - for (const key: any in this.keybindings) { + cleanup() { + for (const key in this.keybindings) { this.keybindings[key].signal.removeAll(); } } - onPageBlur(): any { + onPageBlur() { // Reset all down states // Find mapping - for (const key: any in this.keybindings) { + for (const key in this.keybindings) { const binding: Keybinding = this.keybindings[key]; } } @@ -423,10 +423,10 @@ export class KeyActionMapper { alt: boolean; ctrl: boolean; initial: boolean=; - }): any { - let stop: any = false; + }) { + let stop = false; // Find mapping - for (const key: any in this.keybindings) { + for (const key in this.keybindings) { const binding: Keybinding = this.keybindings[key]; if (binding.keyCode === keyCode && (initial || binding.repeated)) { if (binding.modifiers.shift && !shift) { @@ -455,7 +455,7 @@ export class KeyActionMapper { keyCode: number; shift: boolean; alt: boolean; - }): any { + }) { // Empty } /** @@ -466,7 +466,7 @@ export class KeyActionMapper { keyCode: number; }): Keybinding { // @ts-ignore - const id: any = binding.id; + const id = binding.id; assert(id, "Not a valid keybinding: " + JSON.stringify(binding)); assert(this.keybindings[id], "Keybinding " + id + " not known!"); return this.keybindings[id]; diff --git a/src/ts/game/logic.ts b/src/ts/game/logic.ts index 92ea2329..816c1976 100644 --- a/src/ts/game/logic.ts +++ b/src/ts/game/logic.ts @@ -11,7 +11,7 @@ import { CHUNK_OVERLAY_RES } from "./map_chunk_view"; import { MetaBuilding } from "./meta_building"; import { GameRoot } from "./root"; import { WireNetwork } from "./systems/wire"; -const logger: any = createLogger("ingame/logic"); +const logger = createLogger("ingame/logic"); export type EjectorsAffectingTile = Array<{ entity: Entity; slot: import("./components/item_ejector").ItemEjectorSlot; @@ -45,18 +45,18 @@ export class GameLogic { offset: Vector=; }): boolean { // Compute area of the building - const rect: any = entity.components.StaticMapEntity.getTileSpaceBounds(); + const rect = entity.components.StaticMapEntity.getTileSpaceBounds(); if (offset) { rect.x += offset.x; rect.y += offset.y; } // Check the whole area of the building - for (let x: any = rect.x; x < rect.x + rect.w; ++x) { - for (let y: any = rect.y; y < rect.y + rect.h; ++y) { + for (let x = rect.x; x < rect.x + rect.w; ++x) { + for (let y = rect.y; y < rect.y + rect.h; ++y) { // Check if there is any direct collision - const otherEntity: any = this.root.map.getLayerContentXY(x, y, entity.layer); + const otherEntity = this.root.map.getLayerContentXY(x, y, entity.layer); if (otherEntity) { - const staticComp: any = otherEntity.components.StaticMapEntity; + const staticComp = otherEntity.components.StaticMapEntity; if (!allowReplaceBuildings || !staticComp .getMetaBuilding() @@ -69,8 +69,8 @@ export class GameLogic { } // Perform additional placement checks if (this.root.gameMode.getIsEditor()) { - const toolbar: any = this.root.hud.parts.buildingsToolbar; - const id: any = entity.components.StaticMapEntity.getMetaBuilding().getId(); + const toolbar = this.root.hud.parts.buildingsToolbar; + const id = entity.components.StaticMapEntity.getMetaBuilding().getId(); if (toolbar.buildingHandles[id].puzzleLocked) { return false; } @@ -92,7 +92,7 @@ export class GameLogic { variant: string; building: MetaBuilding; }): Entity { - const entity: any = building.createEntity({ + const entity = building.createEntity({ root: this.root, origin, rotation, @@ -112,15 +112,15 @@ export class GameLogic { * Removes all entities with a RemovableMapEntityComponent which need to get * removed before placing this entity */ - freeEntityAreaBeforeBuild(entity: Entity): any { - const staticComp: any = entity.components.StaticMapEntity; - const rect: any = staticComp.getTileSpaceBounds(); + freeEntityAreaBeforeBuild(entity: Entity) { + const staticComp = entity.components.StaticMapEntity; + const rect = staticComp.getTileSpaceBounds(); // Remove any removeable colliding entities on the same layer - for (let x: any = rect.x; x < rect.x + rect.w; ++x) { - for (let y: any = rect.y; y < rect.y + rect.h; ++y) { - const contents: any = this.root.map.getLayerContentXY(x, y, entity.layer); + for (let x = rect.x; x < rect.x + rect.w; ++x) { + for (let y = rect.y; y < rect.y + rect.h; ++y) { + const contents = this.root.map.getLayerContentXY(x, y, entity.layer); if (contents) { - const staticComp: any = contents.components.StaticMapEntity; + const staticComp = contents.components.StaticMapEntity; assertAlways(staticComp .getMetaBuilding() .getIsReplaceable(staticComp.getVariant(), staticComp.getRotationVariant()), "Tried to replace non-repleaceable entity"); @@ -136,13 +136,13 @@ export class GameLogic { /** * Performs a bulk operation, not updating caches in the meantime */ - performBulkOperation(operation: function): any { + performBulkOperation(operation: function) { logger.warn("Running bulk operation ..."); assert(!this.root.bulkOperationRunning, "Can not run two bulk operations twice"); this.root.bulkOperationRunning = true; - const now: any = performance.now(); - const returnValue: any = operation(); - const duration: any = performance.now() - now; + const now = performance.now(); + const returnValue = operation(); + const duration = performance.now() - now; logger.log("Done in", round2Digits(duration), "ms"); assert(this.root.bulkOperationRunning, "Bulk operation = false while bulk operation was running"); this.root.bulkOperationRunning = false; @@ -152,13 +152,13 @@ export class GameLogic { /** * Performs a immutable operation, causing no recalculations */ - performImmutableOperation(operation: function): any { + performImmutableOperation(operation: function) { logger.warn("Running immutable operation ..."); assert(!this.root.immutableOperationRunning, "Can not run two immutalbe operations twice"); this.root.immutableOperationRunning = true; - const now: any = performance.now(); - const returnValue: any = operation(); - const duration: any = performance.now() - now; + const now = performance.now(); + const returnValue = operation(); + const duration = performance.now() - now; logger.log("Done in", round2Digits(duration), "ms"); assert(this.root.immutableOperationRunning, "Immutable operation = false while immutable operation was running"); this.root.immutableOperationRunning = false; @@ -168,14 +168,14 @@ export class GameLogic { /** * Returns whether the given building can get removed */ - canDeleteBuilding(building: Entity): any { - const staticComp: any = building.components.StaticMapEntity; + canDeleteBuilding(building: Entity) { + const staticComp = building.components.StaticMapEntity; return staticComp.getMetaBuilding().getIsRemovable(this.root); } /** * Tries to delete the given building */ - tryDeleteBuilding(building: Entity): any { + tryDeleteBuilding(building: Entity) { if (!this.canDeleteBuilding(building)) { return false; } @@ -192,26 +192,26 @@ export class GameLogic { wireVariant: enumWireVariant; tile: Vector; edge: enumDirection; - }): any { - const offset: any = enumDirectionToVector[edge]; - const targetTile: any = tile.add(offset); + }) { + const offset = enumDirectionToVector[edge]; + const targetTile = tile.add(offset); // Search for relevant pins - const pinEntities: any = this.root.map.getLayersContentsMultipleXY(targetTile.x, targetTile.y); + const pinEntities = this.root.map.getLayersContentsMultipleXY(targetTile.x, targetTile.y); // Go over all entities which could have a pin - for (let i: any = 0; i < pinEntities.length; ++i) { - const pinEntity: any = pinEntities[i]; - const pinComp: any = pinEntity.components.WiredPins; - const staticComp: any = pinEntity.components.StaticMapEntity; + for (let i = 0; i < pinEntities.length; ++i) { + const pinEntity = pinEntities[i]; + const pinComp = pinEntity.components.WiredPins; + const staticComp = pinEntity.components.StaticMapEntity; // Skip those who don't have pins if (!pinComp) { continue; } // Go over all pins - const pins: any = pinComp.slots; - for (let k: any = 0; k < pinComp.slots.length; ++k) { - const pinSlot: any = pins[k]; - const pinLocation: any = staticComp.localTileToWorld(pinSlot.pos); - const pinDirection: any = staticComp.localDirectionToWorld(pinSlot.direction); + const pins = pinComp.slots; + for (let k = 0; k < pinComp.slots.length; ++k) { + const pinSlot = pins[k]; + const pinLocation = staticComp.localTileToWorld(pinSlot.pos); + const pinDirection = staticComp.localDirectionToWorld(pinSlot.direction); // Check if the pin has the right location if (!pinLocation.equals(targetTile)) { continue; @@ -225,18 +225,18 @@ export class GameLogic { } } // Now check if there's a connectable entity on the wires layer - const targetEntity: any = this.root.map.getTileContent(targetTile, "wires"); + const targetEntity = this.root.map.getTileContent(targetTile, "wires"); if (!targetEntity) { return false; } - const targetStaticComp: any = targetEntity.components.StaticMapEntity; + const targetStaticComp = targetEntity.components.StaticMapEntity; // Check if its a crossing - const wireTunnelComp: any = targetEntity.components.WireTunnel; + const wireTunnelComp = targetEntity.components.WireTunnel; if (wireTunnelComp) { return true; } // Check if its a wire - const wiresComp: any = targetEntity.components.Wire; + const wiresComp = targetEntity.components.Wire; if (!wiresComp) { return false; } @@ -248,29 +248,29 @@ export class GameLogic { * {} Null if the entity is never able to be connected at the given tile */ getEntityWireNetworks(entity: Entity, tile: Vector): Array | null { - let canConnectAtAll: any = false; + let canConnectAtAll = false; const networks: Set = new Set(); - const staticComp: any = entity.components.StaticMapEntity; - const wireComp: any = entity.components.Wire; + const staticComp = entity.components.StaticMapEntity; + const wireComp = entity.components.Wire; if (wireComp) { canConnectAtAll = true; if (wireComp.linkedNetwork) { networks.add(wireComp.linkedNetwork); } } - const tunnelComp: any = entity.components.WireTunnel; + const tunnelComp = entity.components.WireTunnel; if (tunnelComp) { canConnectAtAll = true; - for (let i: any = 0; i < tunnelComp.linkedNetworks.length; ++i) { + for (let i = 0; i < tunnelComp.linkedNetworks.length; ++i) { networks.add(tunnelComp.linkedNetworks[i]); } } - const pinsComp: any = entity.components.WiredPins; + const pinsComp = entity.components.WiredPins; if (pinsComp) { - const slots: any = pinsComp.slots; - for (let i: any = 0; i < slots.length; ++i) { - const slot: any = slots[i]; - const slotLocalPos: any = staticComp.localTileToWorld(slot.pos); + const slots = pinsComp.slots; + for (let i = 0; i < slots.length; ++i) { + const slot = slots[i]; + const slotLocalPos = staticComp.localTileToWorld(slot.pos); if (slotLocalPos.equals(tile)) { canConnectAtAll = true; if (slot.linkedNetwork) { @@ -287,20 +287,20 @@ export class GameLogic { /** * Returns if the entities tile *and* his overlay matrix is intersected */ - getIsEntityIntersectedWithMatrix(entity: Entity, worldPos: Vector): any { - const staticComp: any = entity.components.StaticMapEntity; - const tile: any = worldPos.toTileSpace(); + getIsEntityIntersectedWithMatrix(entity: Entity, worldPos: Vector) { + const staticComp = entity.components.StaticMapEntity; + const tile = worldPos.toTileSpace(); if (!staticComp.getTileSpaceBounds().containsPoint(tile.x, tile.y)) { // No intersection at all return; } - const data: any = getBuildingDataFromCode(staticComp.code); - const overlayMatrix: any = data.metaInstance.getSpecialOverlayRenderMatrix(staticComp.rotation, data.rotationVariant, data.variant, entity); + const data = getBuildingDataFromCode(staticComp.code); + const overlayMatrix = data.metaInstance.getSpecialOverlayRenderMatrix(staticComp.rotation, data.rotationVariant, data.variant, entity); // Always the same if (!overlayMatrix) { return true; } - const localPosition: any = worldPos + const localPosition = worldPos .divideScalar(globalConfig.tileSize) .modScalar(1) .multiplyScalar(CHUNK_OVERLAY_RES) @@ -315,19 +315,19 @@ export class GameLogic { let ejectors: EjectorsAffectingTile = []; let acceptors: AcceptorsAffectingTile = []; // Well .. please ignore this code! :D - for (let dx: any = -1; dx <= 1; ++dx) { - for (let dy: any = -1; dy <= 1; ++dy) { + for (let dx = -1; dx <= 1; ++dx) { + for (let dy = -1; dy <= 1; ++dy) { if (Math.abs(dx) + Math.abs(dy) !== 1) { continue; } - const entity: any = this.root.map.getLayerContentXY(tile.x + dx, tile.y + dy, "regular"); + const entity = this.root.map.getLayerContentXY(tile.x + dx, tile.y + dy, "regular"); if (entity) { let ejectorSlots: Array = []; let acceptorSlots: Array = []; - const staticComp: any = entity.components.StaticMapEntity; - const itemEjector: any = entity.components.ItemEjector; - const itemAcceptor: any = entity.components.ItemAcceptor; - const beltComp: any = entity.components.Belt; + const staticComp = entity.components.StaticMapEntity; + const itemEjector = entity.components.ItemEjector; + const itemAcceptor = entity.components.ItemAcceptor; + const beltComp = entity.components.Belt; if (itemEjector) { ejectorSlots = itemEjector.slots.slice(); } @@ -335,16 +335,16 @@ export class GameLogic { acceptorSlots = itemAcceptor.slots.slice(); } if (beltComp) { - const fakeEjectorSlot: any = beltComp.getFakeEjectorSlot(); - const fakeAcceptorSlot: any = beltComp.getFakeAcceptorSlot(); + const fakeEjectorSlot = beltComp.getFakeEjectorSlot(); + const fakeAcceptorSlot = beltComp.getFakeAcceptorSlot(); ejectorSlots.push(fakeEjectorSlot); acceptorSlots.push(fakeAcceptorSlot); } - for (let ejectorSlot: any = 0; ejectorSlot < ejectorSlots.length; ++ejectorSlot) { - const slot: any = ejectorSlots[ejectorSlot]; - const wsTile: any = staticComp.localTileToWorld(slot.pos); - const wsDirection: any = staticComp.localDirectionToWorld(slot.direction); - const targetTile: any = wsTile.add(enumDirectionToVector[wsDirection]); + for (let ejectorSlot = 0; ejectorSlot < ejectorSlots.length; ++ejectorSlot) { + const slot = ejectorSlots[ejectorSlot]; + const wsTile = staticComp.localTileToWorld(slot.pos); + const wsDirection = staticComp.localDirectionToWorld(slot.direction); + const targetTile = wsTile.add(enumDirectionToVector[wsDirection]); if (targetTile.equals(tile)) { ejectors.push({ entity, @@ -354,12 +354,12 @@ export class GameLogic { }); } } - for (let acceptorSlot: any = 0; acceptorSlot < acceptorSlots.length; ++acceptorSlot) { - const slot: any = acceptorSlots[acceptorSlot]; - const wsTile: any = staticComp.localTileToWorld(slot.pos); - const direction: any = slot.direction; - const wsDirection: any = staticComp.localDirectionToWorld(direction); - const sourceTile: any = wsTile.add(enumDirectionToVector[wsDirection]); + for (let acceptorSlot = 0; acceptorSlot < acceptorSlots.length; ++acceptorSlot) { + const slot = acceptorSlots[acceptorSlot]; + const wsTile = staticComp.localTileToWorld(slot.pos); + const direction = slot.direction; + const wsDirection = staticComp.localDirectionToWorld(direction); + const sourceTile = wsTile.add(enumDirectionToVector[wsDirection]); if (sourceTile.equals(tile)) { acceptors.push({ entity, @@ -377,9 +377,9 @@ export class GameLogic { /** * Clears all belts and items */ - clearAllBeltsAndItems(): any { - for (const entity: any of this.root.entityMgr.entities) { - for (const component: any of Object.values(entity.components)) { + clearAllBeltsAndItems() { + for (const entity of this.root.entityMgr.entities) { + for (const component of Object.values(entity.components)) { component as Component).clear(); } } diff --git a/src/ts/game/map.ts b/src/ts/game/map.ts index c05e6829..bdbf6fb3 100644 --- a/src/ts/game/map.ts +++ b/src/ts/game/map.ts @@ -7,10 +7,10 @@ import { MapChunkAggregate } from "./map_chunk_aggregate"; import { MapChunkView } from "./map_chunk_view"; import { GameRoot } from "./root"; export class BaseMap extends BasicSerializableObject { - static getId(): any { + static getId() { return "Map"; } - static getSchema(): any { + static getSchema() { return { seed: types.uint, }; @@ -26,14 +26,14 @@ export class BaseMap extends BasicSerializableObject { /** * Returns the given chunk by index */ - getChunk(chunkX: number, chunkY: number, createIfNotExistent: any = false): any { - const chunkIdentifier: any = chunkX + "|" + chunkY; - let storedChunk: any; + getChunk(chunkX: number, chunkY: number, createIfNotExistent = false) { + const chunkIdentifier = chunkX + "|" + chunkY; + let storedChunk; if ((storedChunk = this.chunksById.get(chunkIdentifier))) { return storedChunk; } if (createIfNotExistent) { - const instance: any = new MapChunkView(this.root, chunkX, chunkY); + const instance = new MapChunkView(this.root, chunkX, chunkY); this.chunksById.set(chunkIdentifier, instance); return instance; } @@ -42,22 +42,22 @@ export class BaseMap extends BasicSerializableObject { /** * Returns the chunk aggregate containing a given chunk */ - getAggregateForChunk(chunkX: number, chunkY: number, createIfNotExistent: any = false): any { - const aggX: any = Math.floor(chunkX / globalConfig.chunkAggregateSize); - const aggY: any = Math.floor(chunkY / globalConfig.chunkAggregateSize); + getAggregateForChunk(chunkX: number, chunkY: number, createIfNotExistent = false) { + const aggX = Math.floor(chunkX / globalConfig.chunkAggregateSize); + const aggY = Math.floor(chunkY / globalConfig.chunkAggregateSize); return this.getAggregate(aggX, aggY, createIfNotExistent); } /** * Returns the given chunk aggregate by index */ - getAggregate(aggX: number, aggY: number, createIfNotExistent: any = false): any { - const aggIdentifier: any = aggX + "|" + aggY; - let storedAggregate: any; + getAggregate(aggX: number, aggY: number, createIfNotExistent = false) { + const aggIdentifier = aggX + "|" + aggY; + let storedAggregate; if ((storedAggregate = this.aggregatesById.get(aggIdentifier))) { return storedAggregate; } if (createIfNotExistent) { - const instance: any = new MapChunkAggregate(this.root, aggX, aggY); + const instance = new MapChunkAggregate(this.root, aggX, aggY); this.aggregatesById.set(aggIdentifier, instance); return instance; } @@ -68,8 +68,8 @@ export class BaseMap extends BasicSerializableObject { * {} */ getOrCreateChunkAtTile(tileX: number, tileY: number): MapChunkView { - const chunkX: any = Math.floor(tileX / globalConfig.mapChunkSize); - const chunkY: any = Math.floor(tileY / globalConfig.mapChunkSize); + const chunkX = Math.floor(tileX / globalConfig.mapChunkSize); + const chunkY = Math.floor(tileY / globalConfig.mapChunkSize); return this.getChunk(chunkX, chunkY, true); } /** @@ -77,8 +77,8 @@ export class BaseMap extends BasicSerializableObject { * {} */ getChunkAtTileOrNull(tileX: number, tileY: number): ?MapChunkView { - const chunkX: any = Math.floor(tileX / globalConfig.mapChunkSize); - const chunkY: any = Math.floor(tileY / globalConfig.mapChunkSize); + const chunkX = Math.floor(tileX / globalConfig.mapChunkSize); + const chunkY = Math.floor(tileY / globalConfig.mapChunkSize); return this.getChunk(chunkX, chunkY, false); } /** @@ -99,7 +99,7 @@ export class BaseMap extends BasicSerializableObject { if (G_IS_DEV) { this.internalCheckTile(tile); } - const chunk: any = this.getChunkAtTileOrNull(tile.x, tile.y); + const chunk = this.getChunkAtTileOrNull(tile.x, tile.y); return chunk && chunk.getLayerContentFromWorldCoords(tile.x, tile.y, layer); } /** @@ -114,7 +114,7 @@ export class BaseMap extends BasicSerializableObject { * {} Entity or null */ getLayerContentXY(x: number, y: number, layer: Layer): Entity { - const chunk: any = this.getChunkAtTileOrNull(x, y); + const chunk = this.getChunkAtTileOrNull(x, y); return chunk && chunk.getLayerContentFromWorldCoords(x, y, layer); } /** @@ -122,7 +122,7 @@ export class BaseMap extends BasicSerializableObject { * {} Entity or null */ getLayersContentsMultipleXY(x: number, y: number): Array { - const chunk: any = this.getChunkAtTileOrNull(x, y); + const chunk = this.getChunkAtTileOrNull(x, y); if (!chunk) { return []; } @@ -136,7 +136,7 @@ export class BaseMap extends BasicSerializableObject { if (G_IS_DEV) { this.internalCheckTile(tile); } - const chunk: any = this.getChunkAtTileOrNull(tile.x, tile.y); + const chunk = this.getChunkAtTileOrNull(tile.x, tile.y); return chunk && chunk.getLayerContentFromWorldCoords(tile.x, tile.y, layer) != null; } /** @@ -144,31 +144,31 @@ export class BaseMap extends BasicSerializableObject { * {} */ isTileUsedXY(x: number, y: number, layer: Layer): boolean { - const chunk: any = this.getChunkAtTileOrNull(x, y); + const chunk = this.getChunkAtTileOrNull(x, y); return chunk && chunk.getLayerContentFromWorldCoords(x, y, layer) != null; } /** * Sets the tiles content */ - setTileContent(tile: Vector, entity: Entity): any { + setTileContent(tile: Vector, entity: Entity) { if (G_IS_DEV) { this.internalCheckTile(tile); } this.getOrCreateChunkAtTile(tile.x, tile.y).setLayerContentFromWorldCords(tile.x, tile.y, entity, entity.layer); - const staticComponent: any = entity.components.StaticMapEntity; + const staticComponent = entity.components.StaticMapEntity; assert(staticComponent, "Can only place static map entities in tiles"); } /** * Places an entity with the StaticMapEntity component */ - placeStaticEntity(entity: Entity): any { + placeStaticEntity(entity: Entity) { assert(entity.components.StaticMapEntity, "Entity is not static"); - const staticComp: any = entity.components.StaticMapEntity; - const rect: any = staticComp.getTileSpaceBounds(); - for (let dx: any = 0; dx < rect.w; ++dx) { - for (let dy: any = 0; dy < rect.h; ++dy) { - const x: any = rect.x + dx; - const y: any = rect.y + dy; + const staticComp = entity.components.StaticMapEntity; + const rect = staticComp.getTileSpaceBounds(); + for (let dx = 0; dx < rect.w; ++dx) { + for (let dy = 0; dy < rect.h; ++dy) { + const x = rect.x + dx; + const y = rect.y + dy; this.getOrCreateChunkAtTile(x, y).setLayerContentFromWorldCords(x, y, entity, entity.layer); } } @@ -176,14 +176,14 @@ export class BaseMap extends BasicSerializableObject { /** * Removes an entity with the StaticMapEntity component */ - removeStaticEntity(entity: Entity): any { + removeStaticEntity(entity: Entity) { assert(entity.components.StaticMapEntity, "Entity is not static"); - const staticComp: any = entity.components.StaticMapEntity; - const rect: any = staticComp.getTileSpaceBounds(); - for (let dx: any = 0; dx < rect.w; ++dx) { - for (let dy: any = 0; dy < rect.h; ++dy) { - const x: any = rect.x + dx; - const y: any = rect.y + dy; + const staticComp = entity.components.StaticMapEntity; + const rect = staticComp.getTileSpaceBounds(); + for (let dx = 0; dx < rect.w; ++dx) { + for (let dy = 0; dy < rect.h; ++dy) { + const x = rect.x + dx; + const y = rect.y + dy; this.getOrCreateChunkAtTile(x, y).setLayerContentFromWorldCords(x, y, null, entity.layer); } } @@ -192,7 +192,7 @@ export class BaseMap extends BasicSerializableObject { /** * Checks a given tile for validty */ - internalCheckTile(tile: Vector): any { + internalCheckTile(tile: Vector) { assert(tile instanceof Vector, "tile is not a vector: " + tile); assert(tile.x % 1 === 0, "Tile X is not a valid integer: " + tile.x); assert(tile.y % 1 === 0, "Tile Y is not a valid integer: " + tile.y); diff --git a/src/ts/game/map_chunk.ts b/src/ts/game/map_chunk.ts index 2a243774..edf56f08 100644 --- a/src/ts/game/map_chunk.ts +++ b/src/ts/game/map_chunk.ts @@ -10,7 +10,7 @@ import { COLOR_ITEM_SINGLETONS } from "./items/color_item"; import { GameRoot } from "./root"; import { enumSubShape } from "./shape_definition"; import { Rectangle } from "../core/rectangle"; -const logger: any = createLogger("map_chunk"); +const logger = createLogger("map_chunk"); export const MODS_ADDITIONAL_SHAPE_MAP_WEIGHTS: { [idx: string]: (distanceToOriginInChunks: number) => number; } = {}; @@ -42,38 +42,38 @@ export class MapChunk { /** * Generates a patch filled with the given item */ - internalGeneratePatch(rng: RandomNumberGenerator, patchSize: number, item: BaseItem, overrideX: number= = null, overrideY: number= = null): any { - const border: any = Math.ceil(patchSize / 2 + 3); + internalGeneratePatch(rng: RandomNumberGenerator, patchSize: number, item: BaseItem, overrideX: number= = null, overrideY: number= = null) { + const border = Math.ceil(patchSize / 2 + 3); // Find a position within the chunk which is not blocked - let patchX: any = rng.nextIntRange(border, globalConfig.mapChunkSize - border - 1); - let patchY: any = rng.nextIntRange(border, globalConfig.mapChunkSize - border - 1); + let patchX = rng.nextIntRange(border, globalConfig.mapChunkSize - border - 1); + let patchY = rng.nextIntRange(border, globalConfig.mapChunkSize - border - 1); if (overrideX !== null) { patchX = overrideX; } if (overrideY !== null) { patchY = overrideY; } - const avgPos: any = new Vector(0, 0); - let patchesDrawn: any = 0; + const avgPos = new Vector(0, 0); + let patchesDrawn = 0; // Each patch consists of multiple circles - const numCircles: any = patchSize; - for (let i: any = 0; i <= numCircles; ++i) { + const numCircles = patchSize; + for (let i = 0; i <= numCircles; ++i) { // Determine circle parameters - const circleRadius: any = Math.min(1 + i, patchSize); - const circleRadiusSquare: any = circleRadius * circleRadius; - const circleOffsetRadius: any = (numCircles - i) / 2 + 2; + const circleRadius = Math.min(1 + i, patchSize); + const circleRadiusSquare = circleRadius * circleRadius; + const circleOffsetRadius = (numCircles - i) / 2 + 2; // We draw an elipsis actually - const circleScaleX: any = rng.nextRange(0.9, 1.1); - const circleScaleY: any = rng.nextRange(0.9, 1.1); - const circleX: any = patchX + rng.nextIntRange(-circleOffsetRadius, circleOffsetRadius); - const circleY: any = patchY + rng.nextIntRange(-circleOffsetRadius, circleOffsetRadius); - for (let dx: any = -circleRadius * circleScaleX - 2; dx <= circleRadius * circleScaleX + 2; ++dx) { - for (let dy: any = -circleRadius * circleScaleY - 2; dy <= circleRadius * circleScaleY + 2; ++dy) { - const x: any = Math.round(circleX + dx); - const y: any = Math.round(circleY + dy); + const circleScaleX = rng.nextRange(0.9, 1.1); + const circleScaleY = rng.nextRange(0.9, 1.1); + const circleX = patchX + rng.nextIntRange(-circleOffsetRadius, circleOffsetRadius); + const circleY = patchY + rng.nextIntRange(-circleOffsetRadius, circleOffsetRadius); + for (let dx = -circleRadius * circleScaleX - 2; dx <= circleRadius * circleScaleX + 2; ++dx) { + for (let dy = -circleRadius * circleScaleY - 2; dy <= circleRadius * circleScaleY + 2; ++dy) { + const x = Math.round(circleX + dx); + const y = Math.round(circleY + dy); if (x >= 0 && x < globalConfig.mapChunkSize && y >= 0 && y <= globalConfig.mapChunkSize) { - const originalDx: any = dx / circleScaleX; - const originalDy: any = dy / circleScaleY; + const originalDx = dx / circleScaleX; + const originalDy = dy / circleScaleY; if (originalDx * originalDx + originalDy * originalDy <= circleRadiusSquare) { if (!this.lowerLayer[x][y]) { this.lowerLayer[x][y] = item; @@ -98,9 +98,9 @@ export class MapChunk { /** * Generates a color patch */ - internalGenerateColorPatch(rng: RandomNumberGenerator, colorPatchSize: number, distanceToOriginInChunks: number): any { + internalGenerateColorPatch(rng: RandomNumberGenerator, colorPatchSize: number, distanceToOriginInChunks: number) { // First, determine available colors - let availableColors: any = [enumColors.red, enumColors.green]; + let availableColors = [enumColors.red, enumColors.green]; if (distanceToOriginInChunks > 2) { availableColors.push(enumColors.blue); } @@ -109,14 +109,14 @@ export class MapChunk { /** * Generates a shape patch */ - internalGenerateShapePatch(rng: RandomNumberGenerator, shapePatchSize: number, distanceToOriginInChunks: number): any { + internalGenerateShapePatch(rng: RandomNumberGenerator, shapePatchSize: number, distanceToOriginInChunks: number) { let subShapes: [ enumSubShape, enumSubShape, enumSubShape, enumSubShape ] = null; - let weights: any = {}; + let weights = {}; // Later there is a mix of everything weights = { [enumSubShape.rect]: 100, @@ -124,7 +124,7 @@ export class MapChunk { [enumSubShape.star]: Math.round(20 + clamp(distanceToOriginInChunks, 0, 30)), [enumSubShape.windmill]: Math.round(6 + clamp(distanceToOriginInChunks / 2, 0, 20)), }; - for (const key: any in MODS_ADDITIONAL_SHAPE_MAP_WEIGHTS) { + for (const key in MODS_ADDITIONAL_SHAPE_MAP_WEIGHTS) { weights[key] = MODS_ADDITIONAL_SHAPE_MAP_WEIGHTS[key](distanceToOriginInChunks); } if (distanceToOriginInChunks < 7) { @@ -134,13 +134,13 @@ export class MapChunk { } if (distanceToOriginInChunks < 10) { // Initial chunk patches always have the same shape - const subShape: any = this.internalGenerateRandomSubShape(rng, weights); + const subShape = this.internalGenerateRandomSubShape(rng, weights); subShapes = [subShape, subShape, subShape, subShape]; } else if (distanceToOriginInChunks < 15) { // Later patches can also have mixed ones - const subShapeA: any = this.internalGenerateRandomSubShape(rng, weights); - const subShapeB: any = this.internalGenerateRandomSubShape(rng, weights); + const subShapeA = this.internalGenerateRandomSubShape(rng, weights); + const subShapeB = this.internalGenerateRandomSubShape(rng, weights); subShapes = [subShapeA, subShapeA, subShapeB, subShapeB]; } else { @@ -153,8 +153,8 @@ export class MapChunk { ]; } // Makes sure windmills never spawn as whole - let windmillCount: any = 0; - for (let i: any = 0; i < subShapes.length; ++i) { + let windmillCount = 0; + for (let i = 0; i < subShapes.length; ++i) { if (subShapes[i] === enumSubShape.windmill) { ++windmillCount; } @@ -163,7 +163,7 @@ export class MapChunk { subShapes[0] = enumSubShape.rect; subShapes[1] = enumSubShape.rect; } - const definition: any = this.root.shapeDefinitionMgr.getDefinitionFromSimpleShapes(subShapes); + const definition = this.root.shapeDefinitionMgr.getDefinitionFromSimpleShapes(subShapes); this.internalGeneratePatch(rng, shapePatchSize, this.root.shapeDefinitionMgr.getShapeItemFromDefinition(definition)); } /** @@ -174,11 +174,11 @@ export class MapChunk { [idx: enumSubShape]: number; }): enumSubShape { // @ts-ignore - const sum: any = Object.values(weights).reduce((a: any, b: any): any => a + b, 0); - const chosenNumber: any = rng.nextIntRange(0, sum - 1); - let accumulated: any = 0; - for (const key: any in weights) { - const weight: any = weights[key]; + const sum = Object.values(weights).reduce((a, b) => a + b, 0); + const chosenNumber = rng.nextIntRange(0, sum - 1); + let accumulated = 0; + for (const key in weights) { + const weight = weights[key]; if (accumulated + weight > chosenNumber) { return key; } @@ -190,30 +190,30 @@ export class MapChunk { /** * Generates the lower layer "terrain" */ - generateLowerLayer(): any { - const rng: any = new RandomNumberGenerator(this.x + "|" + this.y + "|" + this.root.map.seed); + generateLowerLayer() { + const rng = new RandomNumberGenerator(this.x + "|" + this.y + "|" + this.root.map.seed); if (this.generatePredefined(rng)) { return; } - const chunkCenter: any = new Vector(this.x, this.y).addScalar(0.5); - const distanceToOriginInChunks: any = Math.round(chunkCenter.length()); + const chunkCenter = new Vector(this.x, this.y).addScalar(0.5); + const distanceToOriginInChunks = Math.round(chunkCenter.length()); this.generatePatches({ rng, chunkCenter, distanceToOriginInChunks }); } generatePatches({ rng, chunkCenter, distanceToOriginInChunks }: { rng: RandomNumberGenerator; chunkCenter: Vector; distanceToOriginInChunks: number; - }): any { + }) { // Determine how likely it is that there is a color patch - const colorPatchChance: any = 0.9 - clamp(distanceToOriginInChunks / 25, 0, 1) * 0.5; + const colorPatchChance = 0.9 - clamp(distanceToOriginInChunks / 25, 0, 1) * 0.5; if (rng.next() < colorPatchChance / 4) { - const colorPatchSize: any = Math.max(2, Math.round(1 + clamp(distanceToOriginInChunks / 8, 0, 4))); + const colorPatchSize = Math.max(2, Math.round(1 + clamp(distanceToOriginInChunks / 8, 0, 4))); this.internalGenerateColorPatch(rng, colorPatchSize, distanceToOriginInChunks); } // Determine how likely it is that there is a shape patch - const shapePatchChance: any = 0.9 - clamp(distanceToOriginInChunks / 25, 0, 1) * 0.5; + const shapePatchChance = 0.9 - clamp(distanceToOriginInChunks / 25, 0, 1) * 0.5; if (rng.next() < shapePatchChance / 4) { - const shapePatchSize: any = Math.max(2, Math.round(1 + clamp(distanceToOriginInChunks / 8, 0, 4))); + const shapePatchSize = Math.max(2, Math.round(1 + clamp(distanceToOriginInChunks / 8, 0, 4))); this.internalGenerateShapePatch(rng, shapePatchSize, distanceToOriginInChunks); } } @@ -228,12 +228,12 @@ export class MapChunk { return true; } if (this.x === -1 && this.y === 0) { - const item: any = this.root.shapeDefinitionMgr.getShapeItemFromShortKey("CuCuCuCu"); + const item = this.root.shapeDefinitionMgr.getShapeItemFromShortKey("CuCuCuCu"); this.internalGeneratePatch(rng, 2, item, globalConfig.mapChunkSize - 9, 7); return true; } if (this.x === 0 && this.y === -1) { - const item: any = this.root.shapeDefinitionMgr.getShapeItemFromShortKey("RuRuRuRu"); + const item = this.root.shapeDefinitionMgr.getShapeItemFromShortKey("RuRuRuRu"); this.internalGeneratePatch(rng, 2, item, 5, globalConfig.mapChunkSize - 7); return true; } @@ -242,7 +242,7 @@ export class MapChunk { return true; } if (this.x === 5 && this.y === -2) { - const item: any = this.root.shapeDefinitionMgr.getShapeItemFromShortKey("SuSuSuSu"); + const item = this.root.shapeDefinitionMgr.getShapeItemFromShortKey("SuSuSuSu"); this.internalGeneratePatch(rng, 2, item, 5, globalConfig.mapChunkSize - 7); return true; } @@ -253,8 +253,8 @@ export class MapChunk { * {} */ getLowerLayerFromWorldCoords(worldX: number, worldY: number): BaseItem= { - const localX: any = worldX - this.tileX; - const localY: any = worldY - this.tileY; + const localX = worldX - this.tileX; + const localY = worldY - this.tileY; assert(localX >= 0, "Local X is < 0"); assert(localY >= 0, "Local Y is < 0"); assert(localX < globalConfig.mapChunkSize, "Local X is >= chunk size"); @@ -266,8 +266,8 @@ export class MapChunk { * {} */ getTileContentFromWorldCoords(worldX: number, worldY: number): Entity= { - const localX: any = worldX - this.tileX; - const localY: any = worldY - this.tileY; + const localX = worldX - this.tileX; + const localY = worldY - this.tileY; assert(localX >= 0, "Local X is < 0"); assert(localY >= 0, "Local Y is < 0"); assert(localX < globalConfig.mapChunkSize, "Local X is >= chunk size"); @@ -279,8 +279,8 @@ export class MapChunk { * {} */ getLayerContentFromWorldCoords(worldX: number, worldY: number, layer: Layer): Entity= { - const localX: any = worldX - this.tileX; - const localY: any = worldY - this.tileY; + const localX = worldX - this.tileX; + const localY = worldY - this.tileY; assert(localX >= 0, "Local X is < 0"); assert(localY >= 0, "Local Y is < 0"); assert(localX < globalConfig.mapChunkSize, "Local X is >= chunk size"); @@ -297,15 +297,15 @@ export class MapChunk { * {} */ getLayersContentsMultipleFromWorldCoords(worldX: number, worldY: number): Array { - const localX: any = worldX - this.tileX; - const localY: any = worldY - this.tileY; + const localX = worldX - this.tileX; + const localY = worldY - this.tileY; assert(localX >= 0, "Local X is < 0"); assert(localY >= 0, "Local Y is < 0"); assert(localX < globalConfig.mapChunkSize, "Local X is >= chunk size"); assert(localY < globalConfig.mapChunkSize, "Local Y is >= chunk size"); - const regularContent: any = this.contents[localX][localY]; - const wireContent: any = this.wireContents[localX][localY]; - const result: any = []; + const regularContent = this.contents[localX][localY]; + const wireContent = this.wireContents[localX][localY]; + const result = []; if (regularContent) { result.push(regularContent); } @@ -328,14 +328,14 @@ export class MapChunk { /** * Sets the chunks contents */ - setLayerContentFromWorldCords(tileX: number, tileY: number, contents: Entity, layer: Layer): any { - const localX: any = tileX - this.tileX; - const localY: any = tileY - this.tileY; + setLayerContentFromWorldCords(tileX: number, tileY: number, contents: Entity, layer: Layer) { + const localX = tileX - this.tileX; + const localY = tileY - this.tileY; assert(localX >= 0, "Local X is < 0"); assert(localY >= 0, "Local Y is < 0"); assert(localX < globalConfig.mapChunkSize, "Local X is >= chunk size"); assert(localY < globalConfig.mapChunkSize, "Local Y is >= chunk size"); - let oldContents: any; + let oldContents; if (layer === "regular") { oldContents = this.contents[localX][localY]; } diff --git a/src/ts/game/map_chunk_aggregate.ts b/src/ts/game/map_chunk_aggregate.ts index d6c2f736..f9ce01da 100644 --- a/src/ts/game/map_chunk_aggregate.ts +++ b/src/ts/game/map_chunk_aggregate.ts @@ -18,9 +18,9 @@ export class MapChunkAggregate { /** * Marks this chunk as dirty, rerendering all caches */ - markDirty(chunkX: number, chunkY: number): any { - const relX: any = safeModulo(chunkX, globalConfig.chunkAggregateSize); - const relY: any = safeModulo(chunkY, globalConfig.chunkAggregateSize); + markDirty(chunkX: number, chunkY: number) { + const relX = safeModulo(chunkX, globalConfig.chunkAggregateSize); + const relY = safeModulo(chunkY, globalConfig.chunkAggregateSize); this.dirtyList[relY * globalConfig.chunkAggregateSize + relX] = true; if (this.dirty) { return; @@ -29,20 +29,20 @@ export class MapChunkAggregate { ++this.renderIteration; this.renderKey = this.x + "/" + this.y + "@" + this.renderIteration; } - generateOverlayBuffer(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number): any { - const prevKey: any = this.x + "/" + this.y + "@" + (this.renderIteration - 1); - const prevBuffer: any = this.root.buffers.getForKeyOrNullNoUpdate({ + generateOverlayBuffer(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number) { + const prevKey = this.x + "/" + this.y + "@" + (this.renderIteration - 1); + const prevBuffer = this.root.buffers.getForKeyOrNullNoUpdate({ key: "agg@" + this.root.currentLayer, subKey: prevKey, }); - const overlaySize: any = globalConfig.mapChunkSize * CHUNK_OVERLAY_RES; - let onlyDirty: any = false; + const overlaySize = globalConfig.mapChunkSize * CHUNK_OVERLAY_RES; + let onlyDirty = false; if (prevBuffer) { context.drawImage(prevBuffer, 0, 0); onlyDirty = true; } - for (let x: any = 0; x < globalConfig.chunkAggregateSize; x++) { - for (let y: any = 0; y < globalConfig.chunkAggregateSize; y++) { + for (let x = 0; x < globalConfig.chunkAggregateSize; x++) { + for (let y = 0; y < globalConfig.chunkAggregateSize; y++) { if (onlyDirty && !this.dirtyList[globalConfig.chunkAggregateSize * y + x]) continue; this.root.map @@ -56,9 +56,9 @@ export class MapChunkAggregate { /** * Overlay */ - drawOverlay(parameters: DrawParameters): any { - const aggregateOverlaySize: any = globalConfig.mapChunkSize * globalConfig.chunkAggregateSize * CHUNK_OVERLAY_RES; - const sprite: any = this.root.buffers.getForKey({ + drawOverlay(parameters: DrawParameters) { + const aggregateOverlaySize = globalConfig.mapChunkSize * globalConfig.chunkAggregateSize * CHUNK_OVERLAY_RES; + const sprite = this.root.buffers.getForKey({ key: "agg@" + this.root.currentLayer, subKey: this.renderKey, w: aggregateOverlaySize, @@ -66,8 +66,8 @@ export class MapChunkAggregate { dpi: 1, redrawMethod: this.generateOverlayBuffer.bind(this), }); - const dims: any = globalConfig.mapChunkWorldSize * globalConfig.chunkAggregateSize; - const extrude: any = 0.05; + const dims = globalConfig.mapChunkWorldSize * globalConfig.chunkAggregateSize; + const extrude = 0.05; // Draw chunk "pixel" art parameters.context.imageSmoothingEnabled = false; drawSpriteClipped({ @@ -81,14 +81,14 @@ export class MapChunkAggregate { originalH: aggregateOverlaySize, }); parameters.context.imageSmoothingEnabled = true; - const resourcesScale: any = this.root.app.settings.getAllSettings().mapResourcesScale; + const resourcesScale = this.root.app.settings.getAllSettings().mapResourcesScale; // Draw patch items if (this.root.currentLayer === "regular" && resourcesScale > 0.05 && this.root.camera.zoomLevel > 0.1) { - const diameter: any = (70 / Math.pow(parameters.zoomLevel, 0.35)) * (0.2 + 2 * resourcesScale); - for (let x: any = 0; x < globalConfig.chunkAggregateSize; x++) { - for (let y: any = 0; y < globalConfig.chunkAggregateSize; y++) { + const diameter = (70 / Math.pow(parameters.zoomLevel, 0.35)) * (0.2 + 2 * resourcesScale); + for (let x = 0; x < globalConfig.chunkAggregateSize; x++) { + for (let y = 0; y < globalConfig.chunkAggregateSize; y++) { this.root.map .getChunk(this.x * globalConfig.chunkAggregateSize + x, this.y * globalConfig.chunkAggregateSize + y, true) .drawOverlayPatches(parameters, this.x * dims + x * globalConfig.mapChunkWorldSize, this.y * dims + y * globalConfig.mapChunkWorldSize, diameter); diff --git a/src/ts/game/map_chunk_view.ts b/src/ts/game/map_chunk_view.ts index 0e426791..163be2a1 100644 --- a/src/ts/game/map_chunk_view.ts +++ b/src/ts/game/map_chunk_view.ts @@ -5,8 +5,8 @@ import { Entity } from "./entity"; import { MapChunk } from "./map_chunk"; import { GameRoot } from "./root"; import { THEME } from "./theme"; -export const CHUNK_OVERLAY_RES: any = 3; -export const MOD_CHUNK_DRAW_HOOKS: any = { +export const CHUNK_OVERLAY_RES = 3; +export const MOD_CHUNK_DRAW_HOOKS = { backgroundLayerBefore: [], backgroundLayerAfter: [], foregroundDynamicBefore: [], @@ -24,7 +24,7 @@ export class MapChunkView extends MapChunk { /** * Marks this chunk as dirty, rerendering all caches */ - markDirty(): any { + markDirty() { ++this.renderIteration; this.renderKey = this.x + "/" + this.y + "@" + this.renderIteration; this.root.map.getAggregateForChunk(this.x, this.y, true).markDirty(this.x, this.y); @@ -32,9 +32,9 @@ export class MapChunkView extends MapChunk { /** * Draws the background layer */ - drawBackgroundLayer(parameters: DrawParameters): any { - const systems: any = this.root.systemMgr.systems; - MOD_CHUNK_DRAW_HOOKS.backgroundLayerBefore.forEach((systemId: any): any => systems[systemId].drawChunk(parameters, this)); + drawBackgroundLayer(parameters: DrawParameters) { + const systems = this.root.systemMgr.systems; + MOD_CHUNK_DRAW_HOOKS.backgroundLayerBefore.forEach(systemId => systems[systemId].drawChunk(parameters, this)); if (systems.zone) { systems.zone.drawChunk(parameters, this); } @@ -43,25 +43,25 @@ export class MapChunkView extends MapChunk { } systems.beltUnderlays.drawChunk(parameters, this); systems.belt.drawChunk(parameters, this); - MOD_CHUNK_DRAW_HOOKS.backgroundLayerAfter.forEach((systemId: any): any => systems[systemId].drawChunk(parameters, this)); + MOD_CHUNK_DRAW_HOOKS.backgroundLayerAfter.forEach(systemId => systems[systemId].drawChunk(parameters, this)); } /** * Draws the dynamic foreground layer */ - drawForegroundDynamicLayer(parameters: DrawParameters): any { - const systems: any = this.root.systemMgr.systems; - MOD_CHUNK_DRAW_HOOKS.foregroundDynamicBefore.forEach((systemId: any): any => systems[systemId].drawChunk(parameters, this)); + drawForegroundDynamicLayer(parameters: DrawParameters) { + const systems = this.root.systemMgr.systems; + MOD_CHUNK_DRAW_HOOKS.foregroundDynamicBefore.forEach(systemId => systems[systemId].drawChunk(parameters, this)); systems.itemEjector.drawChunk(parameters, this); systems.itemAcceptor.drawChunk(parameters, this); systems.miner.drawChunk(parameters, this); - MOD_CHUNK_DRAW_HOOKS.foregroundDynamicAfter.forEach((systemId: any): any => systems[systemId].drawChunk(parameters, this)); + MOD_CHUNK_DRAW_HOOKS.foregroundDynamicAfter.forEach(systemId => systems[systemId].drawChunk(parameters, this)); } /** * Draws the static foreground layer */ - drawForegroundStaticLayer(parameters: DrawParameters): any { - const systems: any = this.root.systemMgr.systems; - MOD_CHUNK_DRAW_HOOKS.staticBefore.forEach((systemId: any): any => systems[systemId].drawChunk(parameters, this)); + drawForegroundStaticLayer(parameters: DrawParameters) { + const systems = this.root.systemMgr.systems; + MOD_CHUNK_DRAW_HOOKS.staticBefore.forEach(systemId => systems[systemId].drawChunk(parameters, this)); systems.staticMapEntities.drawChunk(parameters, this); systems.lever.drawChunk(parameters, this); systems.display.drawChunk(parameters, this); @@ -69,19 +69,19 @@ export class MapChunkView extends MapChunk { systems.constantProducer.drawChunk(parameters, this); systems.goalAcceptor.drawChunk(parameters, this); systems.itemProcessorOverlays.drawChunk(parameters, this); - MOD_CHUNK_DRAW_HOOKS.staticAfter.forEach((systemId: any): any => systems[systemId].drawChunk(parameters, this)); + MOD_CHUNK_DRAW_HOOKS.staticAfter.forEach(systemId => systems[systemId].drawChunk(parameters, this)); } - drawOverlayPatches(parameters: DrawParameters, xoffs: number, yoffs: number, diameter: number): any { - for (let i: any = 0; i < this.patches.length; ++i) { - const patch: any = this.patches[i]; + drawOverlayPatches(parameters: DrawParameters, xoffs: number, yoffs: number, diameter: number) { + for (let i = 0; i < this.patches.length; ++i) { + const patch = this.patches[i]; if (patch.item.getItemType() === "shape") { - const destX: any = xoffs + patch.pos.x * globalConfig.tileSize; - const destY: any = yoffs + patch.pos.y * globalConfig.tileSize; + const destX = xoffs + patch.pos.x * globalConfig.tileSize; + const destY = yoffs + patch.pos.y * globalConfig.tileSize; patch.item.drawItemCenteredClipped(destX, destY, parameters, diameter); } } } - generateOverlayBuffer(context: CanvasRenderingContext2D, w: number, h: number, xoffs: number=, yoffs: number=): any { + generateOverlayBuffer(context: CanvasRenderingContext2D, w: number, h: number, xoffs: number=, yoffs: number=) { context.fillStyle = this.containedEntities.length > 0 ? THEME.map.chunkOverview.filled @@ -92,27 +92,27 @@ export class MapChunkView extends MapChunk { context.fillRect(xoffs, yoffs, w, 1); context.fillRect(xoffs, yoffs + 1, 1, h); } - for (let x: any = 0; x < globalConfig.mapChunkSize; ++x) { - const lowerArray: any = this.lowerLayer[x]; - const upperArray: any = this.contents[x]; - for (let y: any = 0; y < globalConfig.mapChunkSize; ++y) { - const upperContent: any = upperArray[y]; + for (let x = 0; x < globalConfig.mapChunkSize; ++x) { + const lowerArray = this.lowerLayer[x]; + const upperArray = this.contents[x]; + for (let y = 0; y < globalConfig.mapChunkSize; ++y) { + const upperContent = upperArray[y]; if (upperContent) { - const staticComp: any = upperContent.components.StaticMapEntity; - const data: any = getBuildingDataFromCode(staticComp.code); - const metaBuilding: any = data.metaInstance; - const overlayMatrix: any = metaBuilding.getSpecialOverlayRenderMatrix(staticComp.rotation, data.rotationVariant, data.variant, upperContent); + const staticComp = upperContent.components.StaticMapEntity; + const data = getBuildingDataFromCode(staticComp.code); + const metaBuilding = data.metaInstance; + const overlayMatrix = metaBuilding.getSpecialOverlayRenderMatrix(staticComp.rotation, data.rotationVariant, data.variant, upperContent); if (overlayMatrix) { // Draw lower content first since it "shines" through - const lowerContent: any = lowerArray[y]; + const lowerContent = lowerArray[y]; if (lowerContent) { context.fillStyle = lowerContent.getBackgroundColorAsResource(); context.fillRect(xoffs + x * CHUNK_OVERLAY_RES, yoffs + y * CHUNK_OVERLAY_RES, CHUNK_OVERLAY_RES, CHUNK_OVERLAY_RES); } context.fillStyle = metaBuilding.getSilhouetteColor(data.variant, data.rotationVariant); - for (let dx: any = 0; dx < 3; ++dx) { - for (let dy: any = 0; dy < 3; ++dy) { - const isFilled: any = overlayMatrix[dx + dy * 3]; + for (let dx = 0; dx < 3; ++dx) { + for (let dy = 0; dy < 3; ++dy) { + const isFilled = overlayMatrix[dx + dy * 3]; if (isFilled) { context.fillRect(xoffs + x * CHUNK_OVERLAY_RES + dx, yoffs + y * CHUNK_OVERLAY_RES + dy, 1, 1); } @@ -126,7 +126,7 @@ export class MapChunkView extends MapChunk { continue; } } - const lowerContent: any = lowerArray[y]; + const lowerContent = lowerArray[y]; if (lowerContent) { context.fillStyle = lowerContent.getBackgroundColorAsResource(); context.fillRect(xoffs + x * CHUNK_OVERLAY_RES, yoffs + y * CHUNK_OVERLAY_RES, CHUNK_OVERLAY_RES, CHUNK_OVERLAY_RES); @@ -137,10 +137,10 @@ export class MapChunkView extends MapChunk { // Draw wires overlay context.fillStyle = THEME.map.wires.overlayColor; context.fillRect(xoffs, yoffs, w, h); - for (let x: any = 0; x < globalConfig.mapChunkSize; ++x) { - const wiresArray: any = this.wireContents[x]; - for (let y: any = 0; y < globalConfig.mapChunkSize; ++y) { - const content: any = wiresArray[y]; + for (let x = 0; x < globalConfig.mapChunkSize; ++x) { + const wiresArray = this.wireContents[x]; + for (let y = 0; y < globalConfig.mapChunkSize; ++y) { + const content = wiresArray[y]; if (!content) { continue; } @@ -162,17 +162,17 @@ export class MapChunkView extends MapChunk { entity: Entity; tileSizePixels: number; overrideColor: string=; - }): any { - const staticComp: any = entity.components.StaticMapEntity; - const data: any = getBuildingDataFromCode(staticComp.code); - const metaBuilding: any = data.metaInstance; - const overlayMatrix: any = metaBuilding.getSpecialOverlayRenderMatrix(staticComp.rotation, data.rotationVariant, data.variant, entity); + }) { + const staticComp = entity.components.StaticMapEntity; + const data = getBuildingDataFromCode(staticComp.code); + const metaBuilding = data.metaInstance; + const overlayMatrix = metaBuilding.getSpecialOverlayRenderMatrix(staticComp.rotation, data.rotationVariant, data.variant, entity); context.fillStyle = overrideColor || metaBuilding.getSilhouetteColor(data.variant, data.rotationVariant); if (overlayMatrix) { - for (let dx: any = 0; dx < 3; ++dx) { - for (let dy: any = 0; dy < 3; ++dy) { - const isFilled: any = overlayMatrix[dx + dy * 3]; + for (let dx = 0; dx < 3; ++dx) { + for (let dy = 0; dy < 3; ++dy) { + const isFilled = overlayMatrix[dx + dy * 3]; if (isFilled) { context.fillRect(x + (dx * tileSizePixels) / CHUNK_OVERLAY_RES, y + (dy * tileSizePixels) / CHUNK_OVERLAY_RES, tileSizePixels / CHUNK_OVERLAY_RES, tileSizePixels / CHUNK_OVERLAY_RES); } @@ -186,8 +186,8 @@ export class MapChunkView extends MapChunk { /** * Draws the wires layer */ - drawWiresForegroundLayer(parameters: DrawParameters): any { - const systems: any = this.root.systemMgr.systems; + drawWiresForegroundLayer(parameters: DrawParameters) { + const systems = this.root.systemMgr.systems; systems.wire.drawChunk(parameters, this); systems.staticMapEntities.drawWiresChunk(parameters, this); systems.wiredPins.drawChunk(parameters, this); diff --git a/src/ts/game/map_view.ts b/src/ts/game/map_view.ts index 71803234..5826b95a 100644 --- a/src/ts/game/map_view.ts +++ b/src/ts/game/map_view.ts @@ -28,8 +28,8 @@ export class MapView extends BaseMap { this.root.signals.entityDestroyed.add(this.onEntityChanged, this); this.root.signals.entityChanged.add(this.onEntityChanged, this); } - cleanup(): any { - for (const key: any in this.cachedBackgroundCanvases) { + cleanup() { + for (const key in this.cachedBackgroundCanvases) { freeCanvas(this.cachedBackgroundCanvases[key]); this.cachedBackgroundCanvases[key] = null; } @@ -37,12 +37,12 @@ export class MapView extends BaseMap { /** * Called when an entity was added, removed or changed */ - onEntityChanged(entity: Entity): any { - const staticComp: any = entity.components.StaticMapEntity; + onEntityChanged(entity: Entity) { + const staticComp = entity.components.StaticMapEntity; if (staticComp) { - const rect: any = staticComp.getTileSpaceBounds(); - for (let x: any = rect.x; x <= rect.right(); ++x) { - for (let y: any = rect.y; y <= rect.bottom(); ++y) { + const rect = staticComp.getTileSpaceBounds(); + for (let x = rect.x; x <= rect.right(); ++x) { + for (let y = rect.y; y <= rect.bottom(); ++y) { this.root.map.getOrCreateChunkAtTile(x, y).markDirty(); } } @@ -51,29 +51,29 @@ export class MapView extends BaseMap { /** * Draws all static entities like buildings etc. */ - drawStaticEntityDebugOverlays(drawParameters: DrawParameters): any { + drawStaticEntityDebugOverlays(drawParameters: DrawParameters) { if (G_IS_DEV && (globalConfig.debug.showAcceptorEjectors || globalConfig.debug.showEntityBounds)) { - const cullRange: any = drawParameters.visibleRect.toTileCullRectangle(); - const top: any = cullRange.top(); - const right: any = cullRange.right(); - const bottom: any = cullRange.bottom(); - const left: any = cullRange.left(); - const border: any = 1; - const minY: any = top - border; - const maxY: any = bottom + border; - const minX: any = left - border; - const maxX: any = right + border - 1; + const cullRange = drawParameters.visibleRect.toTileCullRectangle(); + const top = cullRange.top(); + const right = cullRange.right(); + const bottom = cullRange.bottom(); + const left = cullRange.left(); + const border = 1; + const minY = top - border; + const maxY = bottom + border; + const minX = left - border; + const maxX = right + border - 1; // Render y from top down for proper blending - for (let y: any = minY; y <= maxY; ++y) { - for (let x: any = minX; x <= maxX; ++x) { + for (let y = minY; y <= maxY; ++y) { + for (let x = minX; x <= maxX; ++x) { // const content = this.tiles[x][y]; - const chunk: any = this.getChunkAtTileOrNull(x, y); + const chunk = this.getChunkAtTileOrNull(x, y); if (!chunk) { continue; } - const content: any = chunk.getTileContentFromWorldCoords(x, y); + const content = chunk.getTileContentFromWorldCoords(x, y); if (content) { - let isBorder: any = x <= left - 1 || x >= right + 1 || y <= top - 1 || y >= bottom + 1; + let isBorder = x <= left - 1 || x >= right + 1 || y <= top - 1 || y >= bottom + 1; if (!isBorder) { content.drawDebugOverlays(drawParameters); } @@ -85,19 +85,19 @@ export class MapView extends BaseMap { /** * Initializes all canvases used for background rendering */ - internalInitializeCachedBackgroundCanvases(): any { - for (const key: any in this.cachedBackgroundCanvases) { + internalInitializeCachedBackgroundCanvases() { + for (const key in this.cachedBackgroundCanvases) { // Background canvas - const dims: any = globalConfig.tileSize; - const dpi: any = this.backgroundCacheDPI; - const [canvas, context]: any = makeOffscreenBuffer(dims * dpi, dims * dpi, { + const dims = globalConfig.tileSize; + const dpi = this.backgroundCacheDPI; + const [canvas, context] = makeOffscreenBuffer(dims * dpi, dims * dpi, { smooth: false, label: "map-cached-bg", }); context.scale(dpi, dpi); context.fillStyle = THEME.map.background; context.fillRect(0, 0, dims, dims); - const borderWidth: any = THEME.map.gridLineWidth; + const borderWidth = THEME.map.gridLineWidth; context.fillStyle = THEME.map["grid" + key[0].toUpperCase() + key.substring(1)] || "red"; context.fillRect(0, 0, dims, borderWidth); context.fillRect(0, borderWidth, borderWidth, dims); @@ -109,32 +109,32 @@ export class MapView extends BaseMap { /** * Draws the maps foreground */ - drawForeground(parameters: DrawParameters): any { + drawForeground(parameters: DrawParameters) { this.drawVisibleChunks(parameters, MapChunkView.prototype.drawForegroundDynamicLayer); this.drawVisibleChunks(parameters, MapChunkView.prototype.drawForegroundStaticLayer); } /** * Calls a given method on all given chunks */ - drawVisibleChunks(parameters: DrawParameters, method: function): any { - const cullRange: any = parameters.visibleRect.allScaled(1 / globalConfig.tileSize); - const top: any = cullRange.top(); - const right: any = cullRange.right(); - const bottom: any = cullRange.bottom(); - const left: any = cullRange.left(); - const border: any = 0; - const minY: any = top - border; - const maxY: any = bottom + border; - const minX: any = left - border; - const maxX: any = right + border; - const chunkStartX: any = Math.floor(minX / globalConfig.mapChunkSize); - const chunkStartY: any = Math.floor(minY / globalConfig.mapChunkSize); - const chunkEndX: any = Math.floor(maxX / globalConfig.mapChunkSize); - const chunkEndY: any = Math.floor(maxY / globalConfig.mapChunkSize); + drawVisibleChunks(parameters: DrawParameters, method: function) { + const cullRange = parameters.visibleRect.allScaled(1 / globalConfig.tileSize); + const top = cullRange.top(); + const right = cullRange.right(); + const bottom = cullRange.bottom(); + const left = cullRange.left(); + const border = 0; + const minY = top - border; + const maxY = bottom + border; + const minX = left - border; + const maxX = right + border; + const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize); + const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize); + const chunkEndX = Math.floor(maxX / globalConfig.mapChunkSize); + const chunkEndY = Math.floor(maxY / globalConfig.mapChunkSize); // Render y from top down for proper blending - for (let chunkX: any = chunkStartX; chunkX <= chunkEndX; ++chunkX) { - for (let chunkY: any = chunkStartY; chunkY <= chunkEndY; ++chunkY) { - const chunk: any = this.root.map.getChunk(chunkX, chunkY, true); + for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) { + for (let chunkY = chunkStartY; chunkY <= chunkEndY; ++chunkY) { + const chunk = this.root.map.getChunk(chunkX, chunkY, true); method.call(chunk, parameters); } } @@ -142,26 +142,26 @@ export class MapView extends BaseMap { /** * Calls a given method on all given chunks */ - drawVisibleAggregates(parameters: DrawParameters, method: function): any { - const cullRange: any = parameters.visibleRect.allScaled(1 / globalConfig.tileSize); - const top: any = cullRange.top(); - const right: any = cullRange.right(); - const bottom: any = cullRange.bottom(); - const left: any = cullRange.left(); - const border: any = 0; - const minY: any = top - border; - const maxY: any = bottom + border; - const minX: any = left - border; - const maxX: any = right + border; - const aggregateTiles: any = globalConfig.chunkAggregateSize * globalConfig.mapChunkSize; - const aggStartX: any = Math.floor(minX / aggregateTiles); - const aggStartY: any = Math.floor(minY / aggregateTiles); - const aggEndX: any = Math.floor(maxX / aggregateTiles); - const aggEndY: any = Math.floor(maxY / aggregateTiles); + drawVisibleAggregates(parameters: DrawParameters, method: function) { + const cullRange = parameters.visibleRect.allScaled(1 / globalConfig.tileSize); + const top = cullRange.top(); + const right = cullRange.right(); + const bottom = cullRange.bottom(); + const left = cullRange.left(); + const border = 0; + const minY = top - border; + const maxY = bottom + border; + const minX = left - border; + const maxX = right + border; + const aggregateTiles = globalConfig.chunkAggregateSize * globalConfig.mapChunkSize; + const aggStartX = Math.floor(minX / aggregateTiles); + const aggStartY = Math.floor(minY / aggregateTiles); + const aggEndX = Math.floor(maxX / aggregateTiles); + const aggEndY = Math.floor(maxY / aggregateTiles); // Render y from top down for proper blending - for (let aggX: any = aggStartX; aggX <= aggEndX; ++aggX) { - for (let aggY: any = aggStartY; aggY <= aggEndY; ++aggY) { - const aggregate: any = this.root.map.getAggregate(aggX, aggY, true); + for (let aggX = aggStartX; aggX <= aggEndX; ++aggX) { + for (let aggY = aggStartY; aggY <= aggEndY; ++aggY) { + const aggregate = this.root.map.getAggregate(aggX, aggY, true); method.call(aggregate, parameters); } } @@ -169,24 +169,24 @@ export class MapView extends BaseMap { /** * Draws the wires foreground */ - drawWiresForegroundLayer(parameters: DrawParameters): any { + drawWiresForegroundLayer(parameters: DrawParameters) { this.drawVisibleChunks(parameters, MapChunkView.prototype.drawWiresForegroundLayer); } /** * Draws the map overlay */ - drawOverlay(parameters: DrawParameters): any { + drawOverlay(parameters: DrawParameters) { this.drawVisibleAggregates(parameters, MapChunkAggregate.prototype.drawOverlay); } /** * Draws the map background */ - drawBackground(parameters: DrawParameters): any { + drawBackground(parameters: DrawParameters) { // Render tile grid if (!this.root.app.settings.getAllSettings().disableTileGrid || !this.root.gameMode.hasResources()) { - const dpi: any = this.backgroundCacheDPI; + const dpi = this.backgroundCacheDPI; parameters.context.scale(1 / dpi, 1 / dpi); - let key: any = "regular"; + let key = "regular"; // Disabled rn because it can be really annoying // eslint-disable-next-line no-constant-condition if (this.root.hud.parts.buildingPlacer.currentMetaBuilding.get() && false) { diff --git a/src/ts/game/meta_building.ts b/src/ts/game/meta_building.ts index 129e4a89..6e383785 100644 --- a/src/ts/game/meta_building.ts +++ b/src/ts/game/meta_building.ts @@ -6,7 +6,7 @@ import { StaticMapEntityComponent } from "./components/static_map_entity"; import { Entity } from "./entity"; import { GameRoot } from "./root"; import { getCodeFromBuildingData } from "./building_codes"; -export const defaultBuildingVariant: any = "default"; +export const defaultBuildingVariant = "default"; export class MetaBuilding { public id = id; @@ -28,7 +28,7 @@ export class MetaBuilding { /** * Returns the id of this building */ - getId(): any { + getId() { return this.id; } /** @@ -41,19 +41,19 @@ export class MetaBuilding { /** * Should return the dimensions of the building */ - getDimensions(variant: any = defaultBuildingVariant): any { + getDimensions(variant = defaultBuildingVariant) { return new Vector(1, 1); } /** * Returns whether the building has the direction lock switch available */ - getHasDirectionLockAvailable(variant: string): any { + getHasDirectionLockAvailable(variant: string) { return false; } /** * Whether to stay in placement mode after having placed a building */ - getStayInPlacementMode(): any { + getStayInPlacementMode() { return false; } /** @@ -76,26 +76,26 @@ export class MetaBuilding { /** * Returns whether this building can get replaced */ - getIsReplaceable(variant: string, rotationVariant: number): any { + getIsReplaceable(variant: string, rotationVariant: number) { return false; } /** * Whether to flip the orientation after a building has been placed - useful * for tunnels. */ - getFlipOrientationAfterPlacement(): any { + getFlipOrientationAfterPlacement() { return false; } /** * Whether to show a preview of the wires layer when placing the building */ - getShowWiresLayerPreview(): any { + getShowWiresLayerPreview() { return false; } /** * Whether to rotate automatically in the dragging direction while placing */ - getRotateAutomaticallyWhilePlacing(variant: string): any { + getRotateAutomaticallyWhilePlacing(variant: string) { return false; } /** @@ -112,14 +112,14 @@ export class MetaBuilding { getPlacementSound(): string { return SOUNDS.placeBuilding; } - getAvailableVariants(root: GameRoot): any { + getAvailableVariants(root: GameRoot) { return [defaultBuildingVariant]; } /** * Returns a preview sprite * {} */ - getPreviewSprite(rotationVariant: any = 0, variant: any = defaultBuildingVariant): AtlasSprite { + getPreviewSprite(rotationVariant = 0, variant = defaultBuildingVariant): AtlasSprite { return Loader.getSprite("sprites/buildings/" + this.id + (variant === defaultBuildingVariant ? "" : "-" + variant) + @@ -129,7 +129,7 @@ export class MetaBuilding { * Returns a sprite for blueprints * {} */ - getBlueprintSprite(rotationVariant: any = 0, variant: any = defaultBuildingVariant): AtlasSprite { + getBlueprintSprite(rotationVariant = 0, variant = defaultBuildingVariant): AtlasSprite { return Loader.getSprite("sprites/blueprints/" + this.id + (variant === defaultBuildingVariant ? "" : "-" + variant) + @@ -145,13 +145,13 @@ export class MetaBuilding { /** * Returns whether this building is unlocked for the given game */ - getIsUnlocked(root: GameRoot): any { + getIsUnlocked(root: GameRoot) { return true; } /** * Should return a silhouette color for the map overview or null if not set */ - getSilhouetteColor(variant: string, rotationVariant: number): any { + getSilhouetteColor(variant: string, rotationVariant: number) { return null; } /** @@ -171,8 +171,8 @@ export class MetaBuilding { originalRotation: number; rotationVariant: number; variant: string; - }): any { - const entity: any = new Entity(root); + }) { + const entity = new Entity(root); entity.layer = this.getLayer(); entity.addComponent(new StaticMapEntityComponent({ origin: new Vector(origin.x, origin.y), @@ -224,13 +224,13 @@ export class MetaBuilding { /** * Should update the entity to match the given variants */ - updateVariants(entity: Entity, rotationVariant: number, variant: string): any { } + updateVariants(entity: Entity, rotationVariant: number, variant: string) { } // PRIVATE INTERFACE /** * Should setup the entity components * @abstract */ - setupEntityComponents(entity: Entity, root: GameRoot): any { + setupEntityComponents(entity: Entity, root: GameRoot) { abstract; } } diff --git a/src/ts/game/meta_building_registry.ts b/src/ts/game/meta_building_registry.ts index 419b56a4..c811513a 100644 --- a/src/ts/game/meta_building_registry.ts +++ b/src/ts/game/meta_building_registry.ts @@ -32,16 +32,16 @@ import { MetaWireTunnelBuilding } from "./buildings/wire_tunnel"; import { buildBuildingCodeCache, gBuildingVariants, registerBuildingVariant } from "./building_codes"; import { KEYMAPPINGS } from "./key_action_mapper"; import { defaultBuildingVariant, MetaBuilding } from "./meta_building"; -const logger: any = createLogger("building_registry"); -export function registerBuildingVariants(metaBuilding: typeof MetaBuilding): any { +const logger = createLogger("building_registry"); +export function registerBuildingVariants(metaBuilding: typeof MetaBuilding) { gMetaBuildingRegistry.register(metaBuilding); - const combinations: any = metaBuilding.getAllVariantCombinations(); - combinations.forEach((combination: any): any => { + const combinations = metaBuilding.getAllVariantCombinations(); + combinations.forEach(combination => { registerBuildingVariant(combination.internalId, metaBuilding, combination.variant || defaultBuildingVariant, combination.rotationVariant || 0); }); } -export function initMetaBuildingRegistry(): any { - const buildings: any = [ +export function initMetaBuildingRegistry() { + const buildings = [ MetaBalancerBuilding, MetaMinerBuilding, MetaCutterBuilding, @@ -74,8 +74,8 @@ export function initMetaBuildingRegistry(): any { buildings.forEach(registerBuildingVariants); // Check for valid keycodes if (G_IS_DEV) { - gMetaBuildingRegistry.entries.forEach((metaBuilding: any): any => { - const id: any = metaBuilding.getId(); + gMetaBuildingRegistry.entries.forEach(metaBuilding => { + const id = metaBuilding.getId(); if (!["hub"].includes(id)) { if (!KEYMAPPINGS.buildings[id]) { console.error("Building " + id + " has no keybinding assigned! Add it to key_action_mapper.js"); @@ -95,10 +95,10 @@ export function initMetaBuildingRegistry(): any { /** * Once all sprites are loaded, propagates the cache */ -export function initSpriteCache(): any { +export function initSpriteCache() { logger.log("Propagating sprite cache"); - for (const key: any in gBuildingVariants) { - const variant: any = gBuildingVariants[key]; + for (const key in gBuildingVariants) { + const variant = gBuildingVariants[key]; variant.sprite = variant.metaInstance.getSprite(variant.rotationVariant, variant.variant); variant.blueprintSprite = variant.metaInstance.getBlueprintSprite(variant.rotationVariant, variant.variant); variant.silhouetteColor = variant.metaInstance.getSilhouetteColor(variant.variant, variant.rotationVariant); diff --git a/src/ts/game/modes/levels.ts b/src/ts/game/modes/levels.ts index de4cad14..e4bd1470 100644 --- a/src/ts/game/modes/levels.ts +++ b/src/ts/game/modes/levels.ts @@ -3,7 +3,7 @@ import type { Application } from "../../application"; /* typehints:end */ import { WEB_STEAM_SSO_AUTHENTICATED } from "../../core/steam_sso"; import { enumHubGoalRewards } from "../tutorial_goals"; -export const finalGameShape: any = "RuCw--Cw:----Ru--"; +export const finalGameShape = "RuCw--Cw:----Ru--"; //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /** @@ -55,8 +55,8 @@ const * @param {Application} app * @returns */ -const WEB_DEMO_LEVELS: any = (app: Application): any => { - const levels: any = [ +const WEB_DEMO_LEVELS = (app: Application) => { + const levels = [ // 1 // Circle { @@ -120,7 +120,7 @@ const WEB_DEMO_LEVELS: any = (app: Application): any => { }; //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// -const STEAM_DEMO_LEVELS: any = (): any => [ +const STEAM_DEMO_LEVELS = () => [ // 1 // Circle { @@ -183,7 +183,7 @@ const STEAM_DEMO_LEVELS: any = (): any => [ ]; //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// -const STANDALONE_LEVELS: any = (): any => [ +const STANDALONE_LEVELS = () => [ // 1 // Circle { @@ -365,7 +365,7 @@ const STANDALONE_LEVELS: any = (): any => [ /** * Generates the level definitions */ -export function generateLevelsForVariant(app: any): any { +export function generateLevelsForVariant(app) { if (G_IS_STANDALONE || WEB_STEAM_SSO_AUTHENTICATED) { return STANDALONE_LEVELS(); } diff --git a/src/ts/game/modes/puzzle.ts b/src/ts/game/modes/puzzle.ts index 3c1305d3..642520c9 100644 --- a/src/ts/game/modes/puzzle.ts +++ b/src/ts/game/modes/puzzle.ts @@ -8,7 +8,7 @@ import { HUDPuzzleBackToMenu } from "../hud/parts/puzzle_back_to_menu"; import { HUDPuzzleDLCLogo } from "../hud/parts/puzzle_dlc_logo"; import { HUDMassSelector } from "../hud/parts/mass_selector"; export class PuzzleGameMode extends GameMode { - static getType(): any { + static getType() { return enumGameModeTypes.puzzle; } /** {} */ @@ -28,52 +28,52 @@ export class PuzzleGameMode extends GameMode { constructor(root) { super(root); - const data: any = this.getSaveData(); + const data = this.getSaveData(); } - isBuildingExcluded(building: typeof import("../meta_building").MetaBuilding): any { + isBuildingExcluded(building: typeof import("../meta_building").MetaBuilding) { return this.hiddenBuildings.indexOf(building) >= 0; } - getSaveData(): any { - const save: any = this.root.savegame.getCurrentDump(); + getSaveData() { + const save = this.root.savegame.getCurrentDump(); if (!save) { return {}; } return save.gameMode.data; } - getCameraBounds(): any { + getCameraBounds() { return Rectangle.centered(this.zoneWidth + 20, this.zoneHeight + 20); } - getBuildableZones(): any { + getBuildableZones() { return [Rectangle.centered(this.zoneWidth, this.zoneHeight)]; } - hasHub(): any { + hasHub() { return false; } - hasResources(): any { + hasResources() { return false; } - getMinimumZoom(): any { + getMinimumZoom() { return 1; } - getMaximumZoom(): any { + getMaximumZoom() { return 4; } - getIsSaveable(): any { + getIsSaveable() { return false; } - getHasFreeCopyPaste(): any { + getHasFreeCopyPaste() { return true; } - throughputDoesNotMatter(): any { + throughputDoesNotMatter() { return true; } - getSupportsWires(): any { + getSupportsWires() { return false; } - getFixedTickrate(): any { + getFixedTickrate() { return 300; } - getIsDeterministic(): any { + getIsDeterministic() { return true; } /** {} */ diff --git a/src/ts/game/modes/puzzle_edit.ts b/src/ts/game/modes/puzzle_edit.ts index eb1d4042..ebb45146 100644 --- a/src/ts/game/modes/puzzle_edit.ts +++ b/src/ts/game/modes/puzzle_edit.ts @@ -23,10 +23,10 @@ import { HUDPuzzleEditorReview } from "../hud/parts/puzzle_editor_review"; import { HUDPuzzleEditorSettings } from "../hud/parts/puzzle_editor_settings"; import { HUDConstantSignalEdit } from "../hud/parts/constant_signal_edit"; export class PuzzleEditGameMode extends PuzzleGameMode { - static getId(): any { + static getId() { return enumGameModeIds.puzzleEdit; } - static getSchema(): any { + static getSchema() { return {}; } public hiddenBuildings = [ @@ -54,7 +54,7 @@ export class PuzzleEditGameMode extends PuzzleGameMode { this.additionalHudParts.puzzleEditorSettings = HUDPuzzleEditorSettings; this.additionalHudParts.constantSignalEdit = HUDConstantSignalEdit; } - getIsEditor(): any { + getIsEditor() { return true; } } diff --git a/src/ts/game/modes/puzzle_play.ts b/src/ts/game/modes/puzzle_play.ts index bc3c39b4..c8dc3b2d 100644 --- a/src/ts/game/modes/puzzle_play.ts +++ b/src/ts/game/modes/puzzle_play.ts @@ -30,10 +30,10 @@ import { MetaBlockBuilding } from "../buildings/block"; import { MetaBuilding } from "../meta_building"; import { gMetaBuildingRegistry } from "../../core/global_registries"; import { HUDPuzzleNextPuzzle } from "../hud/parts/next_puzzle"; -const logger: any = createLogger("puzzle-play"); -const copy: any = require("clipboard-copy"); +const logger = createLogger("puzzle-play"); +const copy = require("clipboard-copy"); export class PuzzlePlayGameMode extends PuzzleGameMode { - static getId(): any { + static getId() { return enumGameModeIds.puzzlePlay; } public hiddenBuildings = excludedBuildings; @@ -65,14 +65,14 @@ export class PuzzlePlayGameMode extends PuzzleGameMode { ]; if (puzzle.game.excludedBuildings) { const puzzleHidden: any = puzzle.game.excludedBuildings - .map((id: any): any => { + .map(id => { if (!gMetaBuildingRegistry.hasId(id)) { return; } return gMetaBuildingRegistry.findById(id).constructor; }) - .filter((x: any): any => !!x); + .filter(x => !!x); excludedBuildings = excludedBuildings.concat(puzzleHidden); } this.additionalHudParts.puzzlePlayMetadata = HUDPuzzlePlayMetadata; @@ -83,15 +83,15 @@ export class PuzzlePlayGameMode extends PuzzleGameMode { this.additionalHudParts.puzzleNext = HUDPuzzleNextPuzzle; } } - loadPuzzle(): any { - let errorText: any; + loadPuzzle() { + let errorText; logger.log("Loading puzzle", this.puzzle); try { this.zoneWidth = this.puzzle.game.bounds.w; this.zoneHeight = this.puzzle.game.bounds.h; errorText = new PuzzleSerializer().deserializePuzzle(this.root, this.puzzle.game); } - catch (ex: any) { + catch (ex) { errorText = ex.message || ex; } if (errorText) { @@ -108,42 +108,42 @@ export class PuzzlePlayGameMode extends PuzzleGameMode { // signals.ok.add(() => this.root.gameState.moveToState("PuzzleMenuState")); } } - trackCompleted(liked: boolean, time: number): any { - const closeLoading: any = this.root.hud.parts.dialogs.showLoadingDialog(); + trackCompleted(liked: boolean, time: number) { + const closeLoading = this.root.hud.parts.dialogs.showLoadingDialog(); return this.root.app.clientApi .apiCompletePuzzle(this.puzzle.meta.id, { time, liked, }) - .catch((err: any): any => { + .catch(err => { logger.warn("Failed to complete puzzle:", err); }) - .then((): any => { + .then(() => { closeLoading(); }); } - sharePuzzle(): any { + sharePuzzle() { copy(this.puzzle.meta.shortKey); this.root.hud.parts.dialogs.showInfo(T.dialogs.puzzleShare.title, T.dialogs.puzzleShare.desc.replace("", this.puzzle.meta.shortKey)); } - reportPuzzle(): any { - const { optionSelected }: any = this.root.hud.parts.dialogs.showOptionChooser(T.dialogs.puzzleReport.title, { + reportPuzzle() { + const { optionSelected } = this.root.hud.parts.dialogs.showOptionChooser(T.dialogs.puzzleReport.title, { options: [ { value: "profane", text: T.dialogs.puzzleReport.options.profane }, { value: "unsolvable", text: T.dialogs.puzzleReport.options.unsolvable }, { value: "trolling", text: T.dialogs.puzzleReport.options.trolling }, ], }); - return new Promise((resolve: any): any => { - optionSelected.add((option: any): any => { - const closeLoading: any = this.root.hud.parts.dialogs.showLoadingDialog(); - this.root.app.clientApi.apiReportPuzzle(this.puzzle.meta.id, option).then((): any => { + return new Promise(resolve => { + optionSelected.add(option => { + const closeLoading = this.root.hud.parts.dialogs.showLoadingDialog(); + this.root.app.clientApi.apiReportPuzzle(this.puzzle.meta.id, option).then(() => { closeLoading(); - const { ok }: any = this.root.hud.parts.dialogs.showInfo(T.dialogs.puzzleReportComplete.title, T.dialogs.puzzleReportComplete.desc); + const { ok } = this.root.hud.parts.dialogs.showInfo(T.dialogs.puzzleReportComplete.title, T.dialogs.puzzleReportComplete.desc); ok.add(resolve); - }, (err: any): any => { + }, err => { closeLoading(); - const { ok }: any = this.root.hud.parts.dialogs.showInfo(T.dialogs.puzzleReportError.title, T.dialogs.puzzleReportError.desc + " " + err); + const { ok } = this.root.hud.parts.dialogs.showInfo(T.dialogs.puzzleReportError.title, T.dialogs.puzzleReportError.desc + " " + err); }); }); }); diff --git a/src/ts/game/modes/regular.ts b/src/ts/game/modes/regular.ts index f7dad97a..d5f6eccd 100644 --- a/src/ts/game/modes/regular.ts +++ b/src/ts/game/modes/regular.ts @@ -57,22 +57,22 @@ export type LevelDefinition = { -export const rocketShape: any = "CbCuCbCu:Sr------:--CrSrCr:CwCwCwCw"; -const preparementShape: any = "CpRpCp--:SwSwSwSw"; +export const rocketShape = "CbCuCbCu:Sr------:--CrSrCr:CwCwCwCw"; +const preparementShape = "CpRpCp--:SwSwSwSw"; // Tiers need % of the previous tier as requirement too -const tierGrowth: any = 2.5; -const upgradesCache: any = {}; +const tierGrowth = 2.5; +const upgradesCache = {}; /** * Generates all upgrades * {} */ -function generateUpgrades(limitedVersion: any = false, difficulty: any = 1): Object { +function generateUpgrades(limitedVersion = false, difficulty = 1): Object { if (upgradesCache[limitedVersion]) { return upgradesCache[limitedVersion]; } - const fixedImprovements: any = [0.5, 0.5, 1, 1, 2, 1, 1]; - const numEndgameUpgrades: any = limitedVersion ? 0 : 1000 - fixedImprovements.length - 1; - function generateInfiniteUnlocks(): any { - return new Array(numEndgameUpgrades).fill(null).map((_: any, i: any): any => ({ + const fixedImprovements = [0.5, 0.5, 1, 1, 2, 1, 1]; + const numEndgameUpgrades = limitedVersion ? 0 : 1000 - fixedImprovements.length - 1; + function generateInfiniteUnlocks() { + return new Array(numEndgameUpgrades).fill(null).map((_, i) => ({ required: [ { shape: preparementShape, amount: 30000 + i * 10000 }, { shape: finalGameShape, amount: 20000 + i * 5000 }, @@ -82,7 +82,7 @@ function generateUpgrades(limitedVersion: any = false, difficulty: any = 1): Obj })); } // Fill in endgame upgrades - for (let i: any = 0; i < numEndgameUpgrades; ++i) { + for (let i = 0; i < numEndgameUpgrades; ++i) { if (i < 20) { fixedImprovements.push(0.1); } @@ -96,7 +96,7 @@ function generateUpgrades(limitedVersion: any = false, difficulty: any = 1): Obj fixedImprovements.push(0.0125); } } - const upgrades: any = { + const upgrades = { belt: [ { required: [{ shape: "CuCuCuCu", amount: 30 }], @@ -225,18 +225,18 @@ function generateUpgrades(limitedVersion: any = false, difficulty: any = 1): Obj ], }; // Automatically generate tier levels - for (const upgradeId: any in upgrades) { - const upgradeTiers: any = upgrades[upgradeId]; - let currentTierRequirements: any = []; - for (let i: any = 0; i < upgradeTiers.length; ++i) { - const tierHandle: any = upgradeTiers[i]; + for (const upgradeId in upgrades) { + const upgradeTiers = upgrades[upgradeId]; + let currentTierRequirements = []; + for (let i = 0; i < upgradeTiers.length; ++i) { + const tierHandle = upgradeTiers[i]; tierHandle.improvement = fixedImprovements[i]; - tierHandle.required.forEach((required: any): any => { + tierHandle.required.forEach(required => { required.amount = Math.round(required.amount * difficulty); }); - const originalRequired: any = tierHandle.required.slice(); - for (let k: any = currentTierRequirements.length - 1; k >= 0; --k) { - const oldTierRequirement: any = currentTierRequirements[k]; + const originalRequired = tierHandle.required.slice(); + for (let k = currentTierRequirements.length - 1; k >= 0; --k) { + const oldTierRequirement = currentTierRequirements[k]; if (!tierHandle.excludePrevious) { tierHandle.required.unshift({ shape: oldTierRequirement.shape, @@ -244,11 +244,11 @@ function generateUpgrades(limitedVersion: any = false, difficulty: any = 1): Obj }); } } - currentTierRequirements.push(...originalRequired.map((req: any): any => ({ + currentTierRequirements.push(...originalRequired.map(req => ({ amount: req.amount, shape: req.shape, }))); - currentTierRequirements.forEach((tier: any): any => { + currentTierRequirements.forEach(tier => { tier.amount = findNiceIntegerValue(tier.amount * tierGrowth); }); } @@ -256,13 +256,13 @@ function generateUpgrades(limitedVersion: any = false, difficulty: any = 1): Obj MOD_SIGNALS.modifyUpgrades.dispatch(upgrades); // VALIDATE if (G_IS_DEV) { - for (const upgradeId: any in upgrades) { - upgrades[upgradeId].forEach((tier: any): any => { - tier.required.forEach(({ shape }: any): any => { + for (const upgradeId in upgrades) { + upgrades[upgradeId].forEach(tier => { + tier.required.forEach(({ shape }) => { try { ShapeDefinition.fromShortKey(shape); } - catch (ex: any) { + catch (ex) { throw new Error("Invalid upgrade goal: '" + ex + "' for shape" + shape); } }); @@ -272,22 +272,22 @@ function generateUpgrades(limitedVersion: any = false, difficulty: any = 1): Obj upgradesCache[limitedVersion] = upgrades; return upgrades; } -let levelDefinitionsCache: any = null; +let levelDefinitionsCache = null; /** * Generates the level definitions */ -export function generateLevelDefinitions(app: any): any { +export function generateLevelDefinitions(app) { if (levelDefinitionsCache) { return levelDefinitionsCache; } - const levelDefinitions: any = generateLevelsForVariant(app); + const levelDefinitions = generateLevelsForVariant(app); MOD_SIGNALS.modifyLevelDefinitions.dispatch(levelDefinitions); if (G_IS_DEV) { - levelDefinitions.forEach(({ shape }: any): any => { + levelDefinitions.forEach(({ shape }) => { try { ShapeDefinition.fromShortKey(shape); } - catch (ex: any) { + catch (ex) { throw new Error("Invalid tutorial goal: '" + ex + "' for shape" + shape); } }); @@ -296,10 +296,10 @@ export function generateLevelDefinitions(app: any): any { return levelDefinitions; } export class RegularGameMode extends GameMode { - static getId(): any { + static getId() { return enumGameModeIds.regular; } - static getType(): any { + static getType() { return enumGameModeTypes.default; } public additionalHudParts = { diff --git a/src/ts/game/production_analytics.ts b/src/ts/game/production_analytics.ts index 4c34060d..c320b3a2 100644 --- a/src/ts/game/production_analytics.ts +++ b/src/ts/game/production_analytics.ts @@ -5,13 +5,13 @@ import { BaseItem } from "./base_item"; import { ShapeItem } from "./items/shape_item"; import { BasicSerializableObject } from "../savegame/serialization"; /** @enum {string} */ -export const enumAnalyticsDataSource: any = { +export const enumAnalyticsDataSource = { produced: "produced", stored: "stored", delivered: "delivered", }; export class ProductionAnalytics extends BasicSerializableObject { - static getId(): any { + static getId() { return "ProductionAnalytics"; } public root = root; @@ -24,30 +24,30 @@ export class ProductionAnalytics extends BasicSerializableObject { constructor(root) { super(); - for (let i: any = 0; i < globalConfig.statisticsGraphSlices; ++i) { + for (let i = 0; i < globalConfig.statisticsGraphSlices; ++i) { this.startNewSlice(); } this.root.signals.shapeDelivered.add(this.onShapeDelivered, this); this.root.signals.itemProduced.add(this.onItemProduced, this); } - onShapeDelivered(definition: ShapeDefinition): any { - const key: any = definition.getHash(); - const entry: any = this.history[enumAnalyticsDataSource.delivered]; + onShapeDelivered(definition: ShapeDefinition) { + const key = definition.getHash(); + const entry = this.history[enumAnalyticsDataSource.delivered]; entry[entry.length - 1][key] = (entry[entry.length - 1][key] || 0) + 1; } - onItemProduced(item: BaseItem): any { + onItemProduced(item: BaseItem) { if (item.getItemType() === "shape") { - const definition: any = (item as ShapeItem).definition; - const key: any = definition.getHash(); - const entry: any = this.history[enumAnalyticsDataSource.produced]; + const definition = item as ShapeItem).definition; + const key = definition.getHash(); + const entry = this.history[enumAnalyticsDataSource.produced]; entry[entry.length - 1][key] = (entry[entry.length - 1][key] || 0) + 1; } } /** * Starts a new time slice */ - startNewSlice(): any { - for (const key: any in this.history) { + startNewSlice() { + for (const key in this.history) { if (key === enumAnalyticsDataSource.stored) { // Copy stored data this.history[key].push(Object.assign({}, this.root.hubGoals.storedShapes)); @@ -63,35 +63,35 @@ export class ProductionAnalytics extends BasicSerializableObject { /** * Returns the current rate of a given shape */ - getCurrentShapeRateRaw(dataSource: enumAnalyticsDataSource, definition: ShapeDefinition): any { - const slices: any = this.history[dataSource]; + getCurrentShapeRateRaw(dataSource: enumAnalyticsDataSource, definition: ShapeDefinition) { + const slices = this.history[dataSource]; return slices[slices.length - 2][definition.getHash()] || 0; } /** * Returns the rate of a given shape, frames ago */ - getPastShapeRate(dataSource: enumAnalyticsDataSource, definition: ShapeDefinition, historyOffset: number): any { + getPastShapeRate(dataSource: enumAnalyticsDataSource, definition: ShapeDefinition, historyOffset: number) { assertAlways(historyOffset >= 0 && historyOffset < globalConfig.statisticsGraphSlices - 1, "Invalid slice offset: " + historyOffset); - const slices: any = this.history[dataSource]; + const slices = this.history[dataSource]; return slices[slices.length - 2 - historyOffset][definition.getHash()] || 0; } /** * Returns the rates of all shapes */ - getCurrentShapeRatesRaw(dataSource: enumAnalyticsDataSource): any { - const slices: any = this.history[dataSource]; + getCurrentShapeRatesRaw(dataSource: enumAnalyticsDataSource) { + const slices = this.history[dataSource]; // First, copy current slice - const baseValues: any = Object.assign({}, slices[slices.length - 2]); + const baseValues = Object.assign({}, slices[slices.length - 2]); // Add past values - for (let i: any = 0; i < 10; ++i) { - const pastValues: any = slices[slices.length - i - 3]; - for (const key: any in pastValues) { + for (let i = 0; i < 10; ++i) { + const pastValues = slices[slices.length - i - 3]; + for (const key in pastValues) { baseValues[key] = baseValues[key] || 0; } } return baseValues; } - update(): any { + update() { if (this.root.time.now() - this.lastAnalyticsSlice > globalConfig.analyticsSliceDurationSeconds) { this.lastAnalyticsSlice = this.root.time.now(); this.startNewSlice(); diff --git a/src/ts/game/root.ts b/src/ts/game/root.ts index eaad311e..c08c9d99 100644 --- a/src/ts/game/root.ts +++ b/src/ts/game/root.ts @@ -29,7 +29,7 @@ import type { KeyActionMapper } from "./key_action_mapper"; import type { Vector } from "../core/vector"; import type { GameMode } from "./game_mode"; /* typehints:end */ -const logger: any = createLogger("game/root"); +const logger = createLogger("game/root"); export const layers: Array = ["regular", "wires"]; /** * The game root is basically the whole game state at a given point, @@ -164,7 +164,7 @@ export class GameRoot { /** * Destructs the game root */ - destruct(): any { + destruct() { logger.log("destructing root"); this.signals.aboutToDestruct.dispatch(); this.reset(); @@ -172,10 +172,10 @@ export class GameRoot { /** * Resets the whole root and removes all properties */ - reset(): any { + reset() { if (this.signals) { // Destruct all signals - for (let i: any = 0; i < this.signals.length; ++i) { + for (let i = 0; i < this.signals.length; ++i) { this.signals[i].removeAll(); } } @@ -186,7 +186,7 @@ export class GameRoot { this.camera.cleanup(); } // Finally free all properties - for (let prop: any in this) { + for (let prop in this) { if (this.hasOwnProperty(prop)) { delete this[prop]; } diff --git a/src/ts/game/shape_definition.ts b/src/ts/game/shape_definition.ts index db9a334c..66895dfb 100644 --- a/src/ts/game/shape_definition.ts +++ b/src/ts/game/shape_definition.ts @@ -20,10 +20,10 @@ export type ShapeLayerItem = { color: enumColors; }; -export const TOP_RIGHT: any = 0; -export const BOTTOM_RIGHT: any = 1; -export const BOTTOM_LEFT: any = 2; -export const TOP_LEFT: any = 3; +export const TOP_RIGHT = 0; +export const BOTTOM_RIGHT = 1; +export const BOTTOM_LEFT = 2; +export const TOP_LEFT = 3; export type ShapeLayer = [ ShapeLayerItem?, ShapeLayerItem?, @@ -31,37 +31,37 @@ export type ShapeLayer = [ ShapeLayerItem? ]; -const arrayQuadrantIndexToOffset: any = [ +const arrayQuadrantIndexToOffset = [ new Vector(1, -1), new Vector(1, 1), new Vector(-1, 1), new Vector(-1, -1), // tl ]; /** @enum {string} */ -export const enumSubShape: any = { +export const enumSubShape = { rect: "rect", circle: "circle", star: "star", windmill: "windmill", }; /** @enum {string} */ -export const enumSubShapeToShortcode: any = { +export const enumSubShapeToShortcode = { [enumSubShape.rect]: "R", [enumSubShape.circle]: "C", [enumSubShape.star]: "S", [enumSubShape.windmill]: "W", }; /** @enum {enumSubShape} */ -export const enumShortcodeToSubShape: any = {}; -for (const key: any in enumSubShapeToShortcode) { +export const enumShortcodeToSubShape = {}; +for (const key in enumSubShapeToShortcode) { enumShortcodeToSubShape[enumSubShapeToShortcode[key]] = key; } /** * Converts the given parameters to a valid shape definition * @returns{} *n createSimpleShape(layers: *): Array { - layers.forEach((layer: any): any => { - layer.forEach((item: any): any => { + layers.forEach(layer => { + layer.forEach(item => { if (item) { item.color = item.color || enumColors.uncolored; } @@ -74,21 +74,21 @@ for (const key: any in enumSubShapeToShortcode) { */ const SHORT_KEY_CACHE: Map = new Map(); export class ShapeDefinition extends BasicSerializableObject { - static getId(): any { + static getId() { return "ShapeDefinition"; } - static getSchema(): any { + static getSchema() { return {}; } - deserialize(data: any): any { - const errorCode: any = super.deserialize(data); + deserialize(data) { + const errorCode = super.deserialize(data); if (errorCode) { return errorCode; } - const definition: any = ShapeDefinition.fromShortKey(data); + const definition = ShapeDefinition.fromShortKey(data); this.layers = definition.layers as Array); } - serialize(): any { + serialize() { return this.getHash(); } public layers: Array = layers; @@ -103,16 +103,16 @@ export class ShapeDefinition extends BasicSerializableObject { * {} */ static fromShortKey(key: string): ShapeDefinition { - const sourceLayers: any = key.split(":"); - let layers: any = []; - for (let i: any = 0; i < sourceLayers.length; ++i) { - const text: any = sourceLayers[i]; + const sourceLayers = key.split(":"); + let layers = []; + for (let i = 0; i < sourceLayers.length; ++i) { + const text = sourceLayers[i]; assert(text.length === 8, "Invalid shape short key: " + key); const quads: ShapeLayer = [null, null, null, null]; - for (let quad: any = 0; quad < 4; ++quad) { - const shapeText: any = text[quad * 2 + 0]; - const subShape: any = enumShortcodeToSubShape[shapeText]; - const color: any = enumShortcodeToColor[text[quad * 2 + 1]]; + for (let quad = 0; quad < 4; ++quad) { + const shapeText = text[quad * 2 + 0]; + const subShape = enumShortcodeToSubShape[shapeText]; + const color = enumShortcodeToColor[text[quad * 2 + 1]]; if (subShape) { assert(color, "Invalid shape short key:", key); quads[quad] = { @@ -126,7 +126,7 @@ export class ShapeDefinition extends BasicSerializableObject { } layers.push(quads); } - const definition: any = new ShapeDefinition({ layers }); + const definition = new ShapeDefinition({ layers }); // We know the hash so save some work definition.cachedHash = key; return definition; @@ -139,7 +139,7 @@ export class ShapeDefinition extends BasicSerializableObject { if (SHORT_KEY_CACHE.has(key)) { return SHORT_KEY_CACHE.get(key); } - const result: any = ShapeDefinition.isValidShortKeyInternal(key); + const result = ShapeDefinition.isValidShortKeyInternal(key); SHORT_KEY_CACHE.set(key, result); return result; } @@ -149,20 +149,20 @@ export class ShapeDefinition extends BasicSerializableObject { * {} */ static isValidShortKeyInternal(key: string): boolean { - const sourceLayers: any = key.split(":"); - let layers: any = []; - for (let i: any = 0; i < sourceLayers.length; ++i) { - const text: any = sourceLayers[i]; + const sourceLayers = key.split(":"); + let layers = []; + for (let i = 0; i < sourceLayers.length; ++i) { + const text = sourceLayers[i]; if (text.length !== 8) { return false; } const quads: ShapeLayer = [null, null, null, null]; - let anyFilled: any = false; - for (let quad: any = 0; quad < 4; ++quad) { - const shapeText: any = text[quad * 2 + 0]; - const colorText: any = text[quad * 2 + 1]; - const subShape: any = enumShortcodeToSubShape[shapeText]; - const color: any = enumShortcodeToColor[colorText]; + let anyFilled = false; + for (let quad = 0; quad < 4; ++quad) { + const shapeText = text[quad * 2 + 0]; + const colorText = text[quad * 2 + 1]; + const subShape = enumShortcodeToSubShape[shapeText]; + const color = enumShortcodeToColor[colorText]; // Valid shape if (subShape) { if (!color) { @@ -219,11 +219,11 @@ export class ShapeDefinition extends BasicSerializableObject { if (this.cachedHash) { return this.cachedHash; } - let id: any = ""; - for (let layerIndex: any = 0; layerIndex < this.layers.length; ++layerIndex) { - const layer: any = this.layers[layerIndex]; - for (let quadrant: any = 0; quadrant < layer.length; ++quadrant) { - const item: any = layer[quadrant]; + let id = ""; + for (let layerIndex = 0; layerIndex < this.layers.length; ++layerIndex) { + const layer = this.layers[layerIndex]; + for (let quadrant = 0; quadrant < layer.length; ++quadrant) { + const item = layer[quadrant]; if (item) { id += enumSubShapeToShortcode[item.subShape] + enumColorToShortcode[item.color]; } @@ -241,13 +241,13 @@ export class ShapeDefinition extends BasicSerializableObject { /** * Draws the shape definition */ - drawCentered(x: number, y: number, parameters: DrawParameters, diameter: number= = 20): any { - const dpi: any = smoothenDpi(globalConfig.shapesSharpness * parameters.zoomLevel); + drawCentered(x: number, y: number, parameters: DrawParameters, diameter: number= = 20) { + const dpi = smoothenDpi(globalConfig.shapesSharpness * parameters.zoomLevel); if (!this.bufferGenerator) { this.bufferGenerator = this.internalGenerateShapeBuffer.bind(this); } - const key: any = diameter + "/" + dpi + "/" + this.cachedHash; - const canvas: any = parameters.root.buffers.getForKey({ + const key = diameter + "/" + dpi + "/" + this.cachedHash; + const canvas = parameters.root.buffers.getForKey({ key: "shapedef", subKey: key, w: diameter, @@ -260,14 +260,14 @@ export class ShapeDefinition extends BasicSerializableObject { /** * Draws the item to a canvas */ - drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number): any { + drawFullSizeOnCanvas(context: CanvasRenderingContext2D, size: number) { this.internalGenerateShapeBuffer(null, context, size, size, 1); } /** * Generates this shape as a canvas */ - generateAsCanvas(size: number = 120): any { - const [canvas, context]: any = makeOffscreenBuffer(size, size, { + generateAsCanvas(size: number = 120) { + const [canvas, context] = makeOffscreenBuffer(size, size, { smooth: true, label: "definition-canvas-cache-" + this.getHash(), reusable: false, @@ -275,27 +275,27 @@ export class ShapeDefinition extends BasicSerializableObject { this.internalGenerateShapeBuffer(canvas, context, size, size, 1); return canvas; } - internalGenerateShapeBuffer(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number): any { + internalGenerateShapeBuffer(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number) { context.translate((w * dpi) / 2, (h * dpi) / 2); context.scale((dpi * w) / 23, (dpi * h) / 23); context.fillStyle = "#e9ecf7"; - const quadrantSize: any = 10; - const quadrantHalfSize: any = quadrantSize / 2; + const quadrantSize = 10; + const quadrantHalfSize = quadrantSize / 2; context.fillStyle = THEME.items.circleBackground; context.beginCircle(0, 0, quadrantSize * 1.15); context.fill(); - for (let layerIndex: any = 0; layerIndex < this.layers.length; ++layerIndex) { - const quadrants: any = this.layers[layerIndex]; - const layerScale: any = Math.max(0.1, 0.9 - layerIndex * 0.22); - for (let quadrantIndex: any = 0; quadrantIndex < 4; ++quadrantIndex) { + for (let layerIndex = 0; layerIndex < this.layers.length; ++layerIndex) { + const quadrants = this.layers[layerIndex]; + const layerScale = Math.max(0.1, 0.9 - layerIndex * 0.22); + for (let quadrantIndex = 0; quadrantIndex < 4; ++quadrantIndex) { if (!quadrants[quadrantIndex]) { continue; } - const { subShape, color }: any = quadrants[quadrantIndex]; - const quadrantPos: any = arrayQuadrantIndexToOffset[quadrantIndex]; - const centerQuadrantX: any = quadrantPos.x * quadrantHalfSize; - const centerQuadrantY: any = quadrantPos.y * quadrantHalfSize; - const rotation: any = Math.radians(quadrantIndex * 90); + const { subShape, color } = quadrants[quadrantIndex]; + const quadrantPos = arrayQuadrantIndexToOffset[quadrantIndex]; + const centerQuadrantX = quadrantPos.x * quadrantHalfSize; + const centerQuadrantY = quadrantPos.y * quadrantHalfSize; + const rotation = Math.radians(quadrantIndex * 90); context.translate(centerQuadrantX, centerQuadrantY); context.rotate(rotation); context.fillStyle = enumColorsToHexCode[color]; @@ -312,7 +312,7 @@ export class ShapeDefinition extends BasicSerializableObject { switch (subShape) { case enumSubShape.rect: { context.beginPath(); - const dims: any = quadrantSize * layerScale; + const dims = quadrantSize * layerScale; context.rect(-quadrantHalfSize, quadrantHalfSize - dims, dims, dims); context.fill(); context.stroke(); @@ -320,10 +320,10 @@ export class ShapeDefinition extends BasicSerializableObject { } case enumSubShape.star: { context.beginPath(); - const dims: any = quadrantSize * layerScale; - let originX: any = -quadrantHalfSize; - let originY: any = quadrantHalfSize - dims; - const moveInwards: any = dims * 0.4; + const dims = quadrantSize * layerScale; + let originX = -quadrantHalfSize; + let originY = quadrantHalfSize - dims; + const moveInwards = dims * 0.4; context.moveTo(originX, originY + moveInwards); context.lineTo(originX + dims, originY); context.lineTo(originX + dims - moveInwards, originY + dims); @@ -335,10 +335,10 @@ export class ShapeDefinition extends BasicSerializableObject { } case enumSubShape.windmill: { context.beginPath(); - const dims: any = quadrantSize * layerScale; - let originX: any = -quadrantHalfSize; - let originY: any = quadrantHalfSize - dims; - const moveInwards: any = dims * 0.4; + const dims = quadrantSize * layerScale; + let originX = -quadrantHalfSize; + let originY = quadrantHalfSize - dims; + const moveInwards = dims * 0.4; context.moveTo(originX, originY + moveInwards); context.lineTo(originX + dims, originY); context.lineTo(originX + dims, originY + dims); @@ -372,11 +372,11 @@ export class ShapeDefinition extends BasicSerializableObject { * {} */ cloneFilteredByQuadrants(includeQuadrants: Array): ShapeDefinition { - const newLayers: any = this.getClonedLayers(); - for (let layerIndex: any = 0; layerIndex < newLayers.length; ++layerIndex) { - const quadrants: any = newLayers[layerIndex]; - let anyContents: any = false; - for (let quadrantIndex: any = 0; quadrantIndex < 4; ++quadrantIndex) { + const newLayers = this.getClonedLayers(); + for (let layerIndex = 0; layerIndex < newLayers.length; ++layerIndex) { + const quadrants = newLayers[layerIndex]; + let anyContents = false; + for (let quadrantIndex = 0; quadrantIndex < 4; ++quadrantIndex) { if (includeQuadrants.indexOf(quadrantIndex) < 0) { quadrants[quadrantIndex] = null; } @@ -397,9 +397,9 @@ export class ShapeDefinition extends BasicSerializableObject { * {} */ cloneRotateCW(): ShapeDefinition { - const newLayers: any = this.getClonedLayers(); - for (let layerIndex: any = 0; layerIndex < newLayers.length; ++layerIndex) { - const quadrants: any = newLayers[layerIndex]; + const newLayers = this.getClonedLayers(); + for (let layerIndex = 0; layerIndex < newLayers.length; ++layerIndex) { + const quadrants = newLayers[layerIndex]; quadrants.unshift(quadrants[3]); quadrants.pop(); } @@ -410,9 +410,9 @@ export class ShapeDefinition extends BasicSerializableObject { * {} */ cloneRotateCCW(): ShapeDefinition { - const newLayers: any = this.getClonedLayers(); - for (let layerIndex: any = 0; layerIndex < newLayers.length; ++layerIndex) { - const quadrants: any = newLayers[layerIndex]; + const newLayers = this.getClonedLayers(); + for (let layerIndex = 0; layerIndex < newLayers.length; ++layerIndex) { + const quadrants = newLayers[layerIndex]; quadrants.push(quadrants[0]); quadrants.shift(); } @@ -423,9 +423,9 @@ export class ShapeDefinition extends BasicSerializableObject { * {} */ cloneRotate180(): ShapeDefinition { - const newLayers: any = this.getClonedLayers(); - for (let layerIndex: any = 0; layerIndex < newLayers.length; ++layerIndex) { - const quadrants: any = newLayers[layerIndex]; + const newLayers = this.getClonedLayers(); + for (let layerIndex = 0; layerIndex < newLayers.length; ++layerIndex) { + const quadrants = newLayers[layerIndex]; quadrants.push(quadrants.shift(), quadrants.shift()); } return new ShapeDefinition({ layers: newLayers }); @@ -433,27 +433,27 @@ export class ShapeDefinition extends BasicSerializableObject { /** * Stacks the given shape definition on top. */ - cloneAndStackWith(definition: ShapeDefinition): any { + cloneAndStackWith(definition: ShapeDefinition) { if (this.isEntirelyEmpty() || definition.isEntirelyEmpty()) { assert(false, "Can not stack entirely empty definition"); } - const bottomShapeLayers: any = this.layers; - const bottomShapeHighestLayerByQuad: any = [-1, -1, -1, -1]; - for (let layer: any = bottomShapeLayers.length - 1; layer >= 0; --layer) { - const shapeLayer: any = bottomShapeLayers[layer]; - for (let quad: any = 0; quad < 4; ++quad) { - const shapeQuad: any = shapeLayer[quad]; + const bottomShapeLayers = this.layers; + const bottomShapeHighestLayerByQuad = [-1, -1, -1, -1]; + for (let layer = bottomShapeLayers.length - 1; layer >= 0; --layer) { + const shapeLayer = bottomShapeLayers[layer]; + for (let quad = 0; quad < 4; ++quad) { + const shapeQuad = shapeLayer[quad]; if (shapeQuad !== null && bottomShapeHighestLayerByQuad[quad] < layer) { bottomShapeHighestLayerByQuad[quad] = layer; } } } - const topShapeLayers: any = definition.layers; - const topShapeLowestLayerByQuad: any = [4, 4, 4, 4]; - for (let layer: any = 0; layer < topShapeLayers.length; ++layer) { - const shapeLayer: any = topShapeLayers[layer]; - for (let quad: any = 0; quad < 4; ++quad) { - const shapeQuad: any = shapeLayer[quad]; + const topShapeLayers = definition.layers; + const topShapeLowestLayerByQuad = [4, 4, 4, 4]; + for (let layer = 0; layer < topShapeLayers.length; ++layer) { + const shapeLayer = topShapeLayers[layer]; + for (let quad = 0; quad < 4; ++quad) { + const shapeQuad = shapeLayer[quad]; if (shapeQuad !== null && topShapeLowestLayerByQuad[quad] > layer) { topShapeLowestLayerByQuad[quad] = layer; } @@ -466,22 +466,22 @@ export class ShapeDefinition extends BasicSerializableObject { * though they go negative, and calculating the number to add to it so the minimum gap is 1 (ends * up being 1 - minimum). */ - const gapsBetweenShapes: any = []; - for (let quad: any = 0; quad < 4; ++quad) { + const gapsBetweenShapes = []; + for (let quad = 0; quad < 4; ++quad) { gapsBetweenShapes.push(topShapeLowestLayerByQuad[quad] - bottomShapeHighestLayerByQuad[quad]); } - const smallestGapBetweenShapes: any = Math.min(...gapsBetweenShapes); + const smallestGapBetweenShapes = Math.min(...gapsBetweenShapes); // Can't merge at a layer lower than 0 - const layerToMergeAt: any = Math.max(1 - smallestGapBetweenShapes, 0); - const mergedLayers: any = this.getClonedLayers(); - for (let layer: any = mergedLayers.length; layer < layerToMergeAt + topShapeLayers.length; ++layer) { + const layerToMergeAt = Math.max(1 - smallestGapBetweenShapes, 0); + const mergedLayers = this.getClonedLayers(); + for (let layer = mergedLayers.length; layer < layerToMergeAt + topShapeLayers.length; ++layer) { mergedLayers.push([null, null, null, null]); } - for (let layer: any = 0; layer < topShapeLayers.length; ++layer) { - const layerMergingAt: any = layerToMergeAt + layer; - const bottomShapeLayer: any = mergedLayers[layerMergingAt]; - const topShapeLayer: any = topShapeLayers[layer]; - for (let quad: any = 0; quad < 4; quad++) { + for (let layer = 0; layer < topShapeLayers.length; ++layer) { + const layerMergingAt = layerToMergeAt + layer; + const bottomShapeLayer = mergedLayers[layerMergingAt]; + const topShapeLayer = topShapeLayers[layer]; + for (let quad = 0; quad < 4; quad++) { assert(!(bottomShapeLayer[quad] && topShapeLayer[quad]), "Shape merge: Sub shape got lost"); bottomShapeLayer[quad] = bottomShapeLayer[quad] || topShapeLayer[quad]; } @@ -493,12 +493,12 @@ export class ShapeDefinition extends BasicSerializableObject { /** * Clones the shape and colors everything in the given color */ - cloneAndPaintWith(color: enumColors): any { - const newLayers: any = this.getClonedLayers(); - for (let layerIndex: any = 0; layerIndex < newLayers.length; ++layerIndex) { - const quadrants: any = newLayers[layerIndex]; - for (let quadrantIndex: any = 0; quadrantIndex < 4; ++quadrantIndex) { - const item: any = quadrants[quadrantIndex]; + cloneAndPaintWith(color: enumColors) { + const newLayers = this.getClonedLayers(); + for (let layerIndex = 0; layerIndex < newLayers.length; ++layerIndex) { + const quadrants = newLayers[layerIndex]; + for (let quadrantIndex = 0; quadrantIndex < 4; ++quadrantIndex) { + const item = quadrants[quadrantIndex]; if (item) { item.color = color; } @@ -514,12 +514,12 @@ export class ShapeDefinition extends BasicSerializableObject { enumColors, enumColors, enumColors - ]): any { - const newLayers: any = this.getClonedLayers(); - for (let layerIndex: any = 0; layerIndex < newLayers.length; ++layerIndex) { - const quadrants: any = newLayers[layerIndex]; - for (let quadrantIndex: any = 0; quadrantIndex < 4; ++quadrantIndex) { - const item: any = quadrants[quadrantIndex]; + ]) { + const newLayers = this.getClonedLayers(); + for (let layerIndex = 0; layerIndex < newLayers.length; ++layerIndex) { + const quadrants = newLayers[layerIndex]; + for (let quadrantIndex = 0; quadrantIndex < 4; ++quadrantIndex) { + const item = quadrants[quadrantIndex]; if (item) { item.color = colors[quadrantIndex] || item.color; } diff --git a/src/ts/game/shape_definition_manager.ts b/src/ts/game/shape_definition_manager.ts index ba4301d6..0e6dff55 100644 --- a/src/ts/game/shape_definition_manager.ts +++ b/src/ts/game/shape_definition_manager.ts @@ -5,9 +5,9 @@ import { ShapeItem } from "./items/shape_item"; import { GameRoot } from "./root"; import { enumSubShape, ShapeDefinition } from "./shape_definition"; import { ACHIEVEMENTS } from "../platform/achievement_provider"; -const logger: any = createLogger("shape_definition_manager"); +const logger = createLogger("shape_definition_manager"); export class ShapeDefinitionManager extends BasicSerializableObject { - static getId(): any { + static getId() { return "ShapeDefinitionManager"; } public root = root; @@ -27,7 +27,7 @@ export class ShapeDefinitionManager extends BasicSerializableObject { * {} */ getShapeFromShortKey(hash: string): ShapeDefinition { - const cached: any = this.shapeKeyToDefinition[hash]; + const cached = this.shapeKeyToDefinition[hash]; if (cached) { return cached; } @@ -38,11 +38,11 @@ export class ShapeDefinitionManager extends BasicSerializableObject { * {} */ getShapeItemFromShortKey(hash: string): ShapeItem { - const cached: any = this.shapeKeyToItem[hash]; + const cached = this.shapeKeyToItem[hash]; if (cached) { return cached; } - const definition: any = this.getShapeFromShortKey(hash); + const definition = this.getShapeFromShortKey(hash); return (this.shapeKeyToItem[hash] = new ShapeItem(definition)); } /** @@ -55,8 +55,8 @@ export class ShapeDefinitionManager extends BasicSerializableObject { /** * Registers a new shape definition */ - registerShapeDefinition(definition: ShapeDefinition): any { - const id: any = definition.getHash(); + registerShapeDefinition(definition: ShapeDefinition) { + const id = definition.getHash(); assert(!this.shapeKeyToDefinition[id], "Shape Definition " + id + " already exists"); this.shapeKeyToDefinition[id] = definition; // logger.log("Registered shape with key", id); @@ -69,15 +69,15 @@ export class ShapeDefinitionManager extends BasicSerializableObject { ShapeDefinition, ShapeDefinition ] { - const key: any = "cut/" + definition.getHash(); + const key = "cut/" + definition.getHash(); if (this.operationCache[key]) { return this.operationCache[key] as [ ShapeDefinition, ShapeDefinition ]); } - const rightSide: any = definition.cloneFilteredByQuadrants([2, 3]); - const leftSide: any = definition.cloneFilteredByQuadrants([0, 1]); + const rightSide = definition.cloneFilteredByQuadrants([2, 3]); + const leftSide = definition.cloneFilteredByQuadrants([0, 1]); this.root.signals.achievementCheck.dispatch(ACHIEVEMENTS.cutShape, null); return this.operationCache[key] = [ this.registerOrReturnHandle(rightSide), @@ -97,7 +97,7 @@ export class ShapeDefinitionManager extends BasicSerializableObject { ShapeDefinition, ShapeDefinition ] { - const key: any = "cut-quad/" + definition.getHash(); + const key = "cut-quad/" + definition.getHash(); if (this.operationCache[key]) { return this .operationCache[key] as [ @@ -124,11 +124,11 @@ export class ShapeDefinitionManager extends BasicSerializableObject { * {} */ shapeActionRotateCW(definition: ShapeDefinition): ShapeDefinition { - const key: any = "rotate-cw/" + definition.getHash(); + const key = "rotate-cw/" + definition.getHash(); if (this.operationCache[key]) { return this.operationCache[key] as ShapeDefinition); } - const rotated: any = definition.cloneRotateCW(); + const rotated = definition.cloneRotateCW(); this.root.signals.achievementCheck.dispatch(ACHIEVEMENTS.rotateShape, null); return this.operationCache[key] = this.registerOrReturnHandle(rotated) as ShapeDefinition); } @@ -137,11 +137,11 @@ export class ShapeDefinitionManager extends BasicSerializableObject { * {} */ shapeActionRotateCCW(definition: ShapeDefinition): ShapeDefinition { - const key: any = "rotate-ccw/" + definition.getHash(); + const key = "rotate-ccw/" + definition.getHash(); if (this.operationCache[key]) { return this.operationCache[key] as ShapeDefinition); } - const rotated: any = definition.cloneRotateCCW(); + const rotated = definition.cloneRotateCCW(); return this.operationCache[key] = this.registerOrReturnHandle(rotated) as ShapeDefinition); } /** @@ -149,11 +149,11 @@ export class ShapeDefinitionManager extends BasicSerializableObject { * {} */ shapeActionRotate180(definition: ShapeDefinition): ShapeDefinition { - const key: any = "rotate-fl/" + definition.getHash(); + const key = "rotate-fl/" + definition.getHash(); if (this.operationCache[key]) { return this.operationCache[key] as ShapeDefinition); } - const rotated: any = definition.cloneRotate180(); + const rotated = definition.cloneRotate180(); return this.operationCache[key] = this.registerOrReturnHandle(rotated) as ShapeDefinition); } /** @@ -161,12 +161,12 @@ export class ShapeDefinitionManager extends BasicSerializableObject { * {} */ shapeActionStack(lowerDefinition: ShapeDefinition, upperDefinition: ShapeDefinition): ShapeDefinition { - const key: any = "stack/" + lowerDefinition.getHash() + "/" + upperDefinition.getHash(); + const key = "stack/" + lowerDefinition.getHash() + "/" + upperDefinition.getHash(); if (this.operationCache[key]) { return this.operationCache[key] as ShapeDefinition); } this.root.signals.achievementCheck.dispatch(ACHIEVEMENTS.stackShape, null); - const stacked: any = lowerDefinition.cloneAndStackWith(upperDefinition); + const stacked = lowerDefinition.cloneAndStackWith(upperDefinition); return this.operationCache[key] = this.registerOrReturnHandle(stacked) as ShapeDefinition); } /** @@ -174,12 +174,12 @@ export class ShapeDefinitionManager extends BasicSerializableObject { * {} */ shapeActionPaintWith(definition: ShapeDefinition, color: enumColors): ShapeDefinition { - const key: any = "paint/" + definition.getHash() + "/" + color; + const key = "paint/" + definition.getHash() + "/" + color; if (this.operationCache[key]) { return this.operationCache[key] as ShapeDefinition); } this.root.signals.achievementCheck.dispatch(ACHIEVEMENTS.paintShape, null); - const colorized: any = definition.cloneAndPaintWith(color); + const colorized = definition.cloneAndPaintWith(color); return this.operationCache[key] = this.registerOrReturnHandle(colorized) as ShapeDefinition); } /** @@ -192,19 +192,19 @@ export class ShapeDefinitionManager extends BasicSerializableObject { enumColors, enumColors ]): ShapeDefinition { - const key: any = "paint4/" + definition.getHash() + "/" + colors.join(","); + const key = "paint4/" + definition.getHash() + "/" + colors.join(","); if (this.operationCache[key]) { return this.operationCache[key] as ShapeDefinition); } - const colorized: any = definition.cloneAndPaintWith4Colors(colors); + const colorized = definition.cloneAndPaintWith4Colors(colors); return this.operationCache[key] = this.registerOrReturnHandle(colorized) as ShapeDefinition); } /** * Checks if we already have cached this definition, and if so throws it away and returns the already * cached variant */ - registerOrReturnHandle(definition: ShapeDefinition): any { - const id: any = definition.getHash(); + registerOrReturnHandle(definition: ShapeDefinition) { + const id = definition.getHash(); if (this.shapeKeyToDefinition[id]) { return this.shapeKeyToDefinition[id]; } @@ -221,8 +221,8 @@ export class ShapeDefinitionManager extends BasicSerializableObject { enumSubShape, enumSubShape, enumSubShape - ], color: any = enumColors.uncolored): ShapeDefinition { - const shapeLayer: any = (subShapes.map((subShape: any): any => ({ subShape, color })) as import("./shape_definition").ShapeLayer); + ], color = enumColors.uncolored): ShapeDefinition { + const shapeLayer = subShapes.map(subShape => ({ subShape, color })) as import("./shape_definition").ShapeLayer); return this.registerOrReturnHandle(new ShapeDefinition({ layers: [shapeLayer] })); } } diff --git a/src/ts/game/sound_proxy.ts b/src/ts/game/sound_proxy.ts index 7385780a..34a51659 100644 --- a/src/ts/game/sound_proxy.ts +++ b/src/ts/game/sound_proxy.ts @@ -3,9 +3,9 @@ import type { GameRoot } from "./root"; /* typehints:end */ import { Vector } from "../core/vector"; import { SOUNDS } from "../platform/sound"; -const avgSoundDurationSeconds: any = 0.1; -const maxOngoingSounds: any = 2; -const maxOngoingUiSounds: any = 5; +const avgSoundDurationSeconds = 0.1; +const maxOngoingSounds = 2; +const maxOngoingUiSounds = 5; // Proxy to the application sound instance export class SoundProxy { public root = root; @@ -17,7 +17,7 @@ export class SoundProxy { /** * Plays a new ui sound */ - playUi(id: string): any { + playUi(id: string) { assert(typeof id === "string", "Not a valid sound id: " + id); this.internalUpdateOngoingSounds(); if (this.playingUiSounds.length > maxOngoingUiSounds) { @@ -30,19 +30,19 @@ export class SoundProxy { /** * Plays the ui click sound */ - playUiClick(): any { + playUiClick() { this.playUi(SOUNDS.uiClick); } /** * Plays the ui error sound */ - playUiError(): any { + playUiError() { this.playUi(SOUNDS.uiError); } /** * Plays a 3D sound whose volume is scaled based on where it was emitted */ - play3D(id: string, pos: Vector): any { + play3D(id: string, pos: Vector) { assert(typeof id === "string", "Not a valid sound id: " + id); assert(pos instanceof Vector, "Invalid sound position"); this.internalUpdateOngoingSounds(); @@ -57,15 +57,15 @@ export class SoundProxy { /** * Updates the list of ongoing sounds */ - internalUpdateOngoingSounds(): any { - const now: any = this.root.time.realtimeNow(); - for (let i: any = 0; i < this.playing3DSounds.length; ++i) { + internalUpdateOngoingSounds() { + const now = this.root.time.realtimeNow(); + for (let i = 0; i < this.playing3DSounds.length; ++i) { if (now - this.playing3DSounds[i] > avgSoundDurationSeconds) { this.playing3DSounds.splice(i, 1); i -= 1; } } - for (let i: any = 0; i < this.playingUiSounds.length; ++i) { + for (let i = 0; i < this.playingUiSounds.length; ++i) { if (now - this.playingUiSounds[i] > avgSoundDurationSeconds) { this.playingUiSounds.splice(i, 1); i -= 1; diff --git a/src/ts/game/systems/belt.ts b/src/ts/game/systems/belt.ts index e71e24c1..ae270413 100644 --- a/src/ts/game/systems/belt.ts +++ b/src/ts/game/systems/belt.ts @@ -15,8 +15,8 @@ import { GameSystem } from "../game_system"; import { GameSystemWithFilter } from "../game_system_with_filter"; import { MapChunkView } from "../map_chunk_view"; import { defaultBuildingVariant } from "../meta_building"; -export const BELT_ANIM_COUNT: any = 14; -const logger: any = createLogger("belt"); +export const BELT_ANIM_COUNT = 14; +const logger = createLogger("belt"); /** * Manages all belts */ @@ -39,7 +39,7 @@ export class BeltSystem extends GameSystem { constructor(root) { super(root); - for (let i: any = 0; i < BELT_ANIM_COUNT; ++i) { + for (let i = 0; i < BELT_ANIM_COUNT; ++i) { this.beltAnimations[enumDirection.top].push(Loader.getSprite("sprites/belt/built/forward_" + i + ".png")); this.beltAnimations[enumDirection.left].push(Loader.getSprite("sprites/belt/built/left_" + i + ".png")); this.beltAnimations[enumDirection.right].push(Loader.getSprite("sprites/belt/built/right_" + i + ".png")); @@ -55,8 +55,8 @@ export class BeltSystem extends GameSystem { * {} */ serializePaths(): Array { - let data: any = []; - for (let i: any = 0; i < this.beltPaths.length; ++i) { + let data = []; + for (let i = 0; i < this.beltPaths.length; ++i) { data.push(this.beltPaths[i].serialize()); } return data; @@ -64,12 +64,12 @@ export class BeltSystem extends GameSystem { /** * Deserializes all belt paths */ - deserializePaths(data: Array): any { + deserializePaths(data: Array) { if (!Array.isArray(data)) { return "Belt paths are not an array: " + typeof data; } - for (let i: any = 0; i < data.length; ++i) { - const path: any = BeltPath.fromSerialized(this.root, data[i]); + for (let i = 0; i < data.length; ++i) { + const path = BeltPath.fromSerialized(this.root, data[i]); // If path is a string, that means its an error if (!(path instanceof BeltPath)) { return "Failed to create path from belt data: " + path; @@ -91,35 +91,35 @@ export class BeltSystem extends GameSystem { /** * Updates the belt placement after an entity has been added / deleted */ - updateSurroundingBeltPlacement(entity: Entity): any { + updateSurroundingBeltPlacement(entity: Entity) { if (!this.root.gameInitialized) { return; } - const staticComp: any = entity.components.StaticMapEntity; + const staticComp = entity.components.StaticMapEntity; if (!staticComp) { return; } - const metaBelt: any = gMetaBuildingRegistry.findByClass(MetaBeltBuilding); + const metaBelt = gMetaBuildingRegistry.findByClass(MetaBeltBuilding); // Compute affected area - const originalRect: any = staticComp.getTileSpaceBounds(); - const affectedArea: any = originalRect.expandedInAllDirections(1); + const originalRect = staticComp.getTileSpaceBounds(); + const affectedArea = originalRect.expandedInAllDirections(1); const changedPaths: Set = new Set(); - for (let x: any = affectedArea.x; x < affectedArea.right(); ++x) { - for (let y: any = affectedArea.y; y < affectedArea.bottom(); ++y) { + for (let x = affectedArea.x; x < affectedArea.right(); ++x) { + for (let y = affectedArea.y; y < affectedArea.bottom(); ++y) { if (originalRect.containsPoint(x, y)) { // Make sure we don't update the original entity continue; } - const targetEntities: any = this.root.map.getLayersContentsMultipleXY(x, y); - for (let i: any = 0; i < targetEntities.length; ++i) { - const targetEntity: any = targetEntities[i]; - const targetBeltComp: any = targetEntity.components.Belt; - const targetStaticComp: any = targetEntity.components.StaticMapEntity; + const targetEntities = this.root.map.getLayersContentsMultipleXY(x, y); + for (let i = 0; i < targetEntities.length; ++i) { + const targetEntity = targetEntities[i]; + const targetBeltComp = targetEntity.components.Belt; + const targetStaticComp = targetEntity.components.StaticMapEntity; if (!targetBeltComp) { // Not a belt continue; } - const { rotation, rotationVariant, }: any = metaBelt.computeOptimalDirectionAndRotationVariantAtTile({ + const { rotation, rotationVariant, } = metaBelt.computeOptimalDirectionAndRotationVariantAtTile({ root: this.root, tile: new Vector(x, y), rotation: targetStaticComp.originalRotation, @@ -127,10 +127,10 @@ export class BeltSystem extends GameSystem { layer: targetEntity.layer, }); // Compute delta to see if anything changed - const newDirection: any = arrayBeltVariantToRotation[rotationVariant]; + const newDirection = arrayBeltVariantToRotation[rotationVariant]; if (!this.root.immutableOperationRunning && (targetStaticComp.rotation !== rotation || newDirection !== targetBeltComp.direction)) { - const originalPath: any = targetBeltComp.assignedPath; + const originalPath = targetBeltComp.assignedPath; // Ok, first remove it from its current path this.deleteEntityFromPath(targetBeltComp.assignedPath, targetEntity); // Change stuff @@ -156,7 +156,7 @@ export class BeltSystem extends GameSystem { } } // notify all paths *afterwards* to avoid multi-updates - changedPaths.forEach((path: any): any => path.onSurroundingsChanged()); + changedPaths.forEach(path => path.onSurroundingsChanged()); if (G_IS_DEV && globalConfig.debug.checkBeltPaths) { this.debug_verifyBeltPaths(); } @@ -164,14 +164,14 @@ export class BeltSystem extends GameSystem { /** * Called when an entity got destroyed */ - onEntityDestroyed(entity: Entity): any { + onEntityDestroyed(entity: Entity) { if (!this.root.gameInitialized) { return; } if (!entity.components.Belt) { return; } - const assignedPath: any = entity.components.Belt.assignedPath; + const assignedPath = entity.components.Belt.assignedPath; assert(assignedPath, "Entity has no belt path assigned"); this.deleteEntityFromPath(assignedPath, entity); if (G_IS_DEV && globalConfig.debug.checkBeltPaths) { @@ -181,7 +181,7 @@ export class BeltSystem extends GameSystem { /** * Attempts to delete the belt from its current path */ - deleteEntityFromPath(path: BeltPath, entity: Entity): any { + deleteEntityFromPath(path: BeltPath, entity: Entity) { if (path.entityPath.length === 1) { // This is a single entity path, easy to do, simply erase whole path fastArrayDeleteValue(this.beltPaths, path); @@ -199,7 +199,7 @@ export class BeltSystem extends GameSystem { } else { // We tried to delete something inbetween - const newPath: any = path.deleteEntityOnPathSplitIntoTwo(entity); + const newPath = path.deleteEntityOnPathSplitIntoTwo(entity); this.beltPaths.push(newPath); } // Sanity @@ -208,16 +208,16 @@ export class BeltSystem extends GameSystem { /** * Adds the given entity to the appropriate paths */ - addEntityToPaths(entity: Entity): any { - const fromEntity: any = this.findSupplyingEntity(entity); - const toEntity: any = this.findFollowUpEntity(entity); + addEntityToPaths(entity: Entity) { + const fromEntity = this.findSupplyingEntity(entity); + const toEntity = this.findFollowUpEntity(entity); // Check if we can add the entity to the previous path if (fromEntity) { - const fromPath: any = fromEntity.components.Belt.assignedPath; + const fromPath = fromEntity.components.Belt.assignedPath; fromPath.extendOnEnd(entity); // Check if we now can extend the current path by the next path if (toEntity) { - const toPath: any = toEntity.components.Belt.assignedPath; + const toPath = toEntity.components.Belt.assignedPath; if (fromPath === toPath) { // This is a circular dependency -> Ignore } @@ -231,12 +231,12 @@ export class BeltSystem extends GameSystem { else { if (toEntity) { // Prepend it to the other path - const toPath: any = toEntity.components.Belt.assignedPath; + const toPath = toEntity.components.Belt.assignedPath; toPath.extendOnBeginning(entity); } else { // This is an empty belt path - const path: any = new BeltPath(this.root, [entity]); + const path = new BeltPath(this.root, [entity]); this.beltPaths.push(path); } } @@ -244,7 +244,7 @@ export class BeltSystem extends GameSystem { /** * Called when an entity got added */ - onEntityAdded(entity: Entity): any { + onEntityAdded(entity: Entity) { if (!this.root.gameInitialized) { return; } @@ -259,21 +259,21 @@ export class BeltSystem extends GameSystem { /** * Draws all belt paths */ - drawBeltItems(parameters: DrawParameters): any { - for (let i: any = 0; i < this.beltPaths.length; ++i) { + drawBeltItems(parameters: DrawParameters) { + for (let i = 0; i < this.beltPaths.length; ++i) { this.beltPaths[i].draw(parameters); } } /** * Verifies all belt paths */ - debug_verifyBeltPaths(): any { - for (let i: any = 0; i < this.beltPaths.length; ++i) { + debug_verifyBeltPaths() { + for (let i = 0; i < this.beltPaths.length; ++i) { this.beltPaths[i].debug_checkIntegrity("general-verify"); } - const belts: any = this.root.entityMgr.getAllWithComponent(BeltComponent); - for (let i: any = 0; i < belts.length; ++i) { - const path: any = belts[i].components.Belt.assignedPath; + const belts = this.root.entityMgr.getAllWithComponent(BeltComponent); + for (let i = 0; i < belts.length; ++i) { + const path = belts[i].components.Belt.assignedPath; if (!path) { throw new Error("Belt has no path: " + belts[i].uid); } @@ -287,18 +287,18 @@ export class BeltSystem extends GameSystem { * {} */ findFollowUpEntity(entity: Entity): Entity | null { - const staticComp: any = entity.components.StaticMapEntity; - const beltComp: any = entity.components.Belt; - const followUpDirection: any = staticComp.localDirectionToWorld(beltComp.direction); - const followUpVector: any = enumDirectionToVector[followUpDirection]; - const followUpTile: any = staticComp.origin.add(followUpVector); - const followUpEntity: any = this.root.map.getLayerContentXY(followUpTile.x, followUpTile.y, entity.layer); + const staticComp = entity.components.StaticMapEntity; + const beltComp = entity.components.Belt; + const followUpDirection = staticComp.localDirectionToWorld(beltComp.direction); + const followUpVector = enumDirectionToVector[followUpDirection]; + const followUpTile = staticComp.origin.add(followUpVector); + const followUpEntity = this.root.map.getLayerContentXY(followUpTile.x, followUpTile.y, entity.layer); // Check if there's a belt at the tile we point to if (followUpEntity) { - const followUpBeltComp: any = followUpEntity.components.Belt; + const followUpBeltComp = followUpEntity.components.Belt; if (followUpBeltComp) { - const followUpStatic: any = followUpEntity.components.StaticMapEntity; - const acceptedDirection: any = followUpStatic.localDirectionToWorld(enumDirection.top); + const followUpStatic = followUpEntity.components.StaticMapEntity; + const acceptedDirection = followUpStatic.localDirectionToWorld(enumDirection.top); if (acceptedDirection === followUpDirection) { return followUpEntity; } @@ -311,17 +311,17 @@ export class BeltSystem extends GameSystem { * {} */ findSupplyingEntity(entity: Entity): Entity | null { - const staticComp: any = entity.components.StaticMapEntity; - const supplyDirection: any = staticComp.localDirectionToWorld(enumDirection.bottom); - const supplyVector: any = enumDirectionToVector[supplyDirection]; - const supplyTile: any = staticComp.origin.add(supplyVector); - const supplyEntity: any = this.root.map.getLayerContentXY(supplyTile.x, supplyTile.y, entity.layer); + const staticComp = entity.components.StaticMapEntity; + const supplyDirection = staticComp.localDirectionToWorld(enumDirection.bottom); + const supplyVector = enumDirectionToVector[supplyDirection]; + const supplyTile = staticComp.origin.add(supplyVector); + const supplyEntity = this.root.map.getLayerContentXY(supplyTile.x, supplyTile.y, entity.layer); // Check if there's a belt at the tile we point to if (supplyEntity) { - const supplyBeltComp: any = supplyEntity.components.Belt; + const supplyBeltComp = supplyEntity.components.Belt; if (supplyBeltComp) { - const supplyStatic: any = supplyEntity.components.StaticMapEntity; - const otherDirection: any = supplyStatic.localDirectionToWorld(enumInvertedDirections[supplyBeltComp.direction]); + const supplyStatic = supplyEntity.components.StaticMapEntity; + const otherDirection = supplyStatic.localDirectionToWorld(enumInvertedDirections[supplyBeltComp.direction]); if (otherDirection === supplyDirection) { return supplyEntity; } @@ -332,24 +332,24 @@ export class BeltSystem extends GameSystem { /** * Recomputes the belt path network. Only required for old savegames */ - recomputeAllBeltPaths(): any { + recomputeAllBeltPaths() { logger.warn("Recomputing all belt paths"); - const visitedUids: any = new Set(); - const result: any = []; - const beltEntities: any = this.root.entityMgr.getAllWithComponent(BeltComponent); - for (let i: any = 0; i < beltEntities.length; ++i) { - const entity: any = beltEntities[i]; + const visitedUids = new Set(); + const result = []; + const beltEntities = this.root.entityMgr.getAllWithComponent(BeltComponent); + for (let i = 0; i < beltEntities.length; ++i) { + const entity = beltEntities[i]; if (visitedUids.has(entity.uid)) { continue; } // Mark entity as visited visitedUids.add(entity.uid); // Compute path, start with entity and find precedors / successors - const path: any = [entity]; + const path = [entity]; // Prevent infinite loops - let maxIter: any = 99999; + let maxIter = 99999; // Find precedors - let prevEntity: any = this.findSupplyingEntity(entity); + let prevEntity = this.findSupplyingEntity(entity); while (prevEntity && --maxIter > 0) { if (visitedUids.has(prevEntity.uid)) { break; @@ -359,7 +359,7 @@ export class BeltSystem extends GameSystem { prevEntity = this.findSupplyingEntity(prevEntity); } // Find succedors - let nextEntity: any = this.findFollowUpEntity(entity); + let nextEntity = this.findFollowUpEntity(entity); while (nextEntity && --maxIter > 0) { if (visitedUids.has(nextEntity.uid)) { break; @@ -377,11 +377,11 @@ export class BeltSystem extends GameSystem { /** * Updates all belts */ - update(): any { + update() { if (G_IS_DEV && globalConfig.debug.checkBeltPaths) { this.debug_verifyBeltPaths(); } - for (let i: any = 0; i < this.beltPaths.length; ++i) { + for (let i = 0; i < this.beltPaths.length; ++i) { this.beltPaths[i].update(); } if (G_IS_DEV && globalConfig.debug.checkBeltPaths) { @@ -391,33 +391,33 @@ export class BeltSystem extends GameSystem { /** * Draws a given chunk */ - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { if (G_IS_DEV && globalConfig.debug.doNotRenderStatics) { return; } // Limit speed to avoid belts going backwards - const speedMultiplier: any = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10); + const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10); // SYNC with systems/item_acceptor.js:drawEntityUnderlays! // 126 / 42 is the exact animation speed of the png animation - const animationIndex: any = Math.floor(((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) * + const animationIndex = Math.floor(((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) * globalConfig.itemSpacingOnBelts); - const contents: any = chunk.containedEntitiesByLayer.regular; + const contents = chunk.containedEntitiesByLayer.regular; if (this.root.app.settings.getAllSettings().simplifiedBelts) { // POTATO Mode: Only show items when belt is hovered - let hoveredBeltPath: any = null; - const mousePos: any = this.root.app.mousePosition; + let hoveredBeltPath = null; + const mousePos = this.root.app.mousePosition; if (mousePos && this.root.currentLayer === "regular") { - const tile: any = this.root.camera.screenToWorld(mousePos).toTileSpace(); - const contents: any = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); + const tile = this.root.camera.screenToWorld(mousePos).toTileSpace(); + const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); if (contents && contents.components.Belt) { hoveredBeltPath = contents.components.Belt.assignedPath; } } - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; if (entity.components.Belt) { - const direction: any = entity.components.Belt.direction; - let sprite: any = this.beltAnimations[direction][0]; + const direction = entity.components.Belt.direction; + let sprite = this.beltAnimations[direction][0]; if (entity.components.Belt.assignedPath === hoveredBeltPath) { sprite = this.beltAnimations[direction][animationIndex % BELT_ANIM_COUNT]; } @@ -427,11 +427,11 @@ export class BeltSystem extends GameSystem { } } else { - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; if (entity.components.Belt) { - const direction: any = entity.components.Belt.direction; - const sprite: any = this.beltAnimations[direction][animationIndex % BELT_ANIM_COUNT]; + const direction = entity.components.Belt.direction; + const sprite = this.beltAnimations[direction][animationIndex % BELT_ANIM_COUNT]; // Culling happens within the static map entity component entity.components.StaticMapEntity.drawSpriteOnBoundsClipped(parameters, sprite, 0); } @@ -441,8 +441,8 @@ export class BeltSystem extends GameSystem { /** * Draws the belt path debug overlays */ - drawBeltPathDebug(parameters: DrawParameters): any { - for (let i: any = 0; i < this.beltPaths.length; ++i) { + drawBeltPathDebug(parameters: DrawParameters) { + for (let i = 0; i < this.beltPaths.length; ++i) { this.beltPaths[i].drawDebug(parameters); } } diff --git a/src/ts/game/systems/belt_reader.ts b/src/ts/game/systems/belt_reader.ts index b8225172..94a51fb8 100644 --- a/src/ts/game/systems/belt_reader.ts +++ b/src/ts/game/systems/belt_reader.ts @@ -7,14 +7,14 @@ export class BeltReaderSystem extends GameSystemWithFilter { constructor(root) { super(root, [BeltReaderComponent]); } - update(): any { - const now: any = this.root.time.now(); - const minimumTime: any = now - globalConfig.readerAnalyzeIntervalSeconds; - const minimumTimeForThroughput: any = now - 1; - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const readerComp: any = entity.components.BeltReader; - const pinsComp: any = entity.components.WiredPins; + update() { + const now = this.root.time.now(); + const minimumTime = now - globalConfig.readerAnalyzeIntervalSeconds; + const minimumTimeForThroughput = now - 1; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const readerComp = entity.components.BeltReader; + const pinsComp = entity.components.WiredPins; // Remove outdated items while (readerComp.lastItemTimes[0] < minimumTime) { readerComp.lastItemTimes.shift(); @@ -30,14 +30,14 @@ export class BeltReaderSystem extends GameSystemWithFilter { if (now - readerComp.lastThroughputComputation > 0.5) { // Compute throughput readerComp.lastThroughputComputation = now; - let throughput: any = 0; + let throughput = 0; if (readerComp.lastItemTimes.length < 2) { throughput = 0; } else { - let averageSpacing: any = 0; - let averageSpacingNum: any = 0; - for (let i: any = 0; i < readerComp.lastItemTimes.length - 1; ++i) { + let averageSpacing = 0; + let averageSpacingNum = 0; + for (let i = 0; i < readerComp.lastItemTimes.length - 1; ++i) { averageSpacing += readerComp.lastItemTimes[i + 1] - readerComp.lastItemTimes[i]; ++averageSpacingNum; } diff --git a/src/ts/game/systems/belt_underlays.ts b/src/ts/game/systems/belt_underlays.ts index 96792770..76a0ec02 100644 --- a/src/ts/game/systems/belt_underlays.ts +++ b/src/ts/game/systems/belt_underlays.ts @@ -34,27 +34,27 @@ export class BeltUnderlaysSystem extends GameSystem { constructor(root) { super(root); - for (let i: any = 0; i < BELT_ANIM_COUNT; ++i) { + for (let i = 0; i < BELT_ANIM_COUNT; ++i) { this.underlayBeltSprites.push(Loader.getSprite("sprites/belt/built/forward_" + i + ".png")); } this.staleArea.recomputeOnComponentsChanged([BeltUnderlaysComponent, BeltComponent, ItemAcceptorComponent, ItemEjectorComponent], 1); } - update(): any { + update() { this.staleArea.update(); } /** * Called when an area changed - Resets all caches in the given area */ - recomputeStaleArea(area: Rectangle): any { - for (let x: any = 0; x < area.w; ++x) { - for (let y: any = 0; y < area.h; ++y) { - const tileX: any = area.x + x; - const tileY: any = area.y + y; - const entity: any = this.root.map.getLayerContentXY(tileX, tileY, "regular"); + recomputeStaleArea(area: Rectangle) { + for (let x = 0; x < area.w; ++x) { + for (let y = 0; y < area.h; ++y) { + const tileX = area.x + x; + const tileY = area.y + y; + const entity = this.root.map.getLayerContentXY(tileX, tileY, "regular"); if (entity) { - const underlayComp: any = entity.components.BeltUnderlays; + const underlayComp = entity.components.BeltUnderlays; if (underlayComp) { - for (let i: any = 0; i < underlayComp.underlays.length; ++i) { + for (let i = 0; i < underlayComp.underlays.length; ++i) { underlayComp.underlays[i].cachedType = null; } } @@ -67,29 +67,29 @@ export class BeltUnderlaysSystem extends GameSystem { * {} */ checkIsAcceptorConnected(tile: Vector, fromDirection: enumDirection): boolean { - const contents: any = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); + const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); if (!contents) { return false; } - const staticComp: any = contents.components.StaticMapEntity; + const staticComp = contents.components.StaticMapEntity; // Check if its a belt, since then its simple - const beltComp: any = contents.components.Belt; + const beltComp = contents.components.Belt; if (beltComp) { return staticComp.localDirectionToWorld(enumDirection.bottom) === fromDirection; } // Check if there's an item acceptor - const acceptorComp: any = contents.components.ItemAcceptor; + const acceptorComp = contents.components.ItemAcceptor; if (acceptorComp) { // Check each slot to see if its connected - for (let i: any = 0; i < acceptorComp.slots.length; ++i) { - const slot: any = acceptorComp.slots[i]; - const slotTile: any = staticComp.localTileToWorld(slot.pos); + for (let i = 0; i < acceptorComp.slots.length; ++i) { + const slot = acceptorComp.slots[i]; + const slotTile = staticComp.localTileToWorld(slot.pos); // Step 1: Check if the tile matches if (!slotTile.equals(tile)) { continue; } // Step 2: Check if the direction matches - const slotDirection: any = staticComp.localDirectionToWorld(slot.direction); + const slotDirection = staticComp.localDirectionToWorld(slot.direction); if (slotDirection === fromDirection) { return true; } @@ -102,29 +102,29 @@ export class BeltUnderlaysSystem extends GameSystem { * {} */ checkIsEjectorConnected(tile: Vector, toDirection: enumDirection): boolean { - const contents: any = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); + const contents = this.root.map.getLayerContentXY(tile.x, tile.y, "regular"); if (!contents) { return false; } - const staticComp: any = contents.components.StaticMapEntity; + const staticComp = contents.components.StaticMapEntity; // Check if its a belt, since then its simple - const beltComp: any = contents.components.Belt; + const beltComp = contents.components.Belt; if (beltComp) { return staticComp.localDirectionToWorld(beltComp.direction) === toDirection; } // Check for an ejector - const ejectorComp: any = contents.components.ItemEjector; + const ejectorComp = contents.components.ItemEjector; if (ejectorComp) { // Check each slot to see if its connected - for (let i: any = 0; i < ejectorComp.slots.length; ++i) { - const slot: any = ejectorComp.slots[i]; - const slotTile: any = staticComp.localTileToWorld(slot.pos); + for (let i = 0; i < ejectorComp.slots.length; ++i) { + const slot = ejectorComp.slots[i]; + const slotTile = staticComp.localTileToWorld(slot.pos); // Step 1: Check if the tile matches if (!slotTile.equals(tile)) { continue; } // Step 2: Check if the direction matches - const slotDirection: any = staticComp.localDirectionToWorld(slot.direction); + const slotDirection = staticComp.localDirectionToWorld(slot.direction); if (slotDirection === toDirection) { return true; } @@ -140,18 +140,18 @@ export class BeltUnderlaysSystem extends GameSystem { if (underlayTile.cachedType) { return underlayTile.cachedType; } - const staticComp: any = entity.components.StaticMapEntity; - const transformedPos: any = staticComp.localTileToWorld(underlayTile.pos); - const destX: any = transformedPos.x * globalConfig.tileSize; - const destY: any = transformedPos.y * globalConfig.tileSize; + const staticComp = entity.components.StaticMapEntity; + const transformedPos = staticComp.localTileToWorld(underlayTile.pos); + const destX = transformedPos.x * globalConfig.tileSize; + const destY = transformedPos.y * globalConfig.tileSize; // Extract direction and angle - const worldDirection: any = staticComp.localDirectionToWorld(underlayTile.direction); - const worldDirectionVector: any = enumDirectionToVector[worldDirection]; + const worldDirection = staticComp.localDirectionToWorld(underlayTile.direction); + const worldDirectionVector = enumDirectionToVector[worldDirection]; // Figure out if there is anything connected at the top - const connectedTop: any = this.checkIsAcceptorConnected(transformedPos.add(worldDirectionVector), enumInvertedDirections[worldDirection]); + const connectedTop = this.checkIsAcceptorConnected(transformedPos.add(worldDirectionVector), enumInvertedDirections[worldDirection]); // Figure out if there is anything connected at the bottom - const connectedBottom: any = this.checkIsEjectorConnected(transformedPos.sub(worldDirectionVector), worldDirection); - let flag: any = enumClippedBeltUnderlayType.none; + const connectedBottom = this.checkIsEjectorConnected(transformedPos.sub(worldDirectionVector), worldDirection); + let flag = enumClippedBeltUnderlayType.none; if (connectedTop && connectedBottom) { flag = enumClippedBeltUnderlayType.full; } @@ -166,24 +166,24 @@ export class BeltUnderlaysSystem extends GameSystem { /** * Draws a given chunk */ - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { // Limit speed to avoid belts going backwards - const speedMultiplier: any = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10); - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const underlayComp: any = entity.components.BeltUnderlays; + const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10); + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const underlayComp = entity.components.BeltUnderlays; if (!underlayComp) { continue; } - const staticComp: any = entity.components.StaticMapEntity; - const underlays: any = underlayComp.underlays; - for (let i: any = 0; i < underlays.length; ++i) { + const staticComp = entity.components.StaticMapEntity; + const underlays = underlayComp.underlays; + for (let i = 0; i < underlays.length; ++i) { // Extract underlay parameters - const { pos, direction }: any = underlays[i]; - const transformedPos: any = staticComp.localTileToWorld(pos); - const destX: any = transformedPos.x * globalConfig.tileSize; - const destY: any = transformedPos.y * globalConfig.tileSize; + const { pos, direction } = underlays[i]; + const transformedPos = staticComp.localTileToWorld(pos); + const destX = transformedPos.x * globalConfig.tileSize; + const destY = transformedPos.y * globalConfig.tileSize; // Culling, Part 1: Check if the chunk contains the tile if (!chunk.tileSpaceRectangle.containsPoint(transformedPos.x, transformedPos.y)) { continue; @@ -193,20 +193,20 @@ export class BeltUnderlaysSystem extends GameSystem { continue; } // Extract direction and angle - const worldDirection: any = staticComp.localDirectionToWorld(direction); - const angle: any = enumDirectionToAngle[worldDirection]; - const underlayType: any = this.computeBeltUnderlayType(entity, underlays[i]); - const clipRect: any = enumUnderlayTypeToClipRect[underlayType]; + const worldDirection = staticComp.localDirectionToWorld(direction); + const angle = enumDirectionToAngle[worldDirection]; + const underlayType = this.computeBeltUnderlayType(entity, underlays[i]); + const clipRect = enumUnderlayTypeToClipRect[underlayType]; if (!clipRect) { // Empty continue; } // Actually draw the sprite - const x: any = destX + globalConfig.halfTileSize; - const y: any = destY + globalConfig.halfTileSize; - const angleRadians: any = Math.radians(angle); + const x = destX + globalConfig.halfTileSize; + const y = destY + globalConfig.halfTileSize; + const angleRadians = Math.radians(angle); // SYNC with systems/belt.js:drawSingleEntity! - const animationIndex: any = Math.floor(((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) * + const animationIndex = Math.floor(((this.root.time.realtimeNow() * speedMultiplier * BELT_ANIM_COUNT * 126) / 42) * globalConfig.itemSpacingOnBelts); parameters.context.translate(x, y); parameters.context.rotate(angleRadians); diff --git a/src/ts/game/systems/constant_producer.ts b/src/ts/game/systems/constant_producer.ts index aeb83e28..93486e05 100644 --- a/src/ts/game/systems/constant_producer.ts +++ b/src/ts/game/systems/constant_producer.ts @@ -10,11 +10,11 @@ export class ConstantProducerSystem extends GameSystemWithFilter { constructor(root) { super(root, [ConstantSignalComponent, ItemProducerComponent]); } - update(): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const signalComp: any = entity.components.ConstantSignal; - const ejectorComp: any = entity.components.ItemEjector; + update() { + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const signalComp = entity.components.ConstantSignal; + const ejectorComp = entity.components.ItemEjector; if (!ejectorComp) { continue; } @@ -103,21 +103,21 @@ export class ConstantProducerSystem extends GameSystemWithFilter { * @param {MapChunk} chunk * @returns */ - drawChunk(parameters: DrawParameters, chunk: MapChunk): any { - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const producerComp: any = contents[i].components.ItemProducer; - const signalComp: any = contents[i].components.ConstantSignal; + drawChunk(parameters: DrawParameters, chunk: MapChunk) { + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const producerComp = contents[i].components.ItemProducer; + const signalComp = contents[i].components.ConstantSignal; if (!producerComp || !signalComp) { continue; } - const staticComp: any = contents[i].components.StaticMapEntity; - const item: any = signalComp.signal; + const staticComp = contents[i].components.StaticMapEntity; + const item = signalComp.signal; if (!item) { continue; } - const center: any = staticComp.getTileSpaceBounds().getCenter().toWorldSpace(); - const localOffset: any = new Vector(0, 1).rotateFastMultipleOf90(staticComp.rotation); + const center = staticComp.getTileSpaceBounds().getCenter().toWorldSpace(); + const localOffset = new Vector(0, 1).rotateFastMultipleOf90(staticComp.rotation); item.drawItemCenteredClipped(center.x + localOffset.x, center.y + localOffset.y, parameters, globalConfig.tileSize * 0.65); } } diff --git a/src/ts/game/systems/constant_signal.ts b/src/ts/game/systems/constant_signal.ts index 6b38e9d2..c92d942b 100644 --- a/src/ts/game/systems/constant_signal.ts +++ b/src/ts/game/systems/constant_signal.ts @@ -4,19 +4,19 @@ export class ConstantSignalSystem extends GameSystemWithFilter { constructor(root) { super(root, [ConstantSignalComponent]); - this.root.signals.entityManuallyPlaced.add((entity: any): any => { - const editorHud: any = this.root.hud.parts.constantSignalEdit; + this.root.signals.entityManuallyPlaced.add(entity => { + const editorHud = this.root.hud.parts.constantSignalEdit; if (editorHud) { editorHud.editConstantSignal(entity, { deleteOnCancel: true }); } }); } - update(): any { + update() { // Set signals - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const signalComp: any = entity.components.ConstantSignal; - const pinsComp: any = entity.components.WiredPins; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const signalComp = entity.components.ConstantSignal; + const pinsComp = entity.components.WiredPins; if (pinsComp) { pinsComp.slots[0].value = signalComp.signal; } diff --git a/src/ts/game/systems/display.ts b/src/ts/game/systems/display.ts index 55a4c2ef..1e7255c5 100644 --- a/src/ts/game/systems/display.ts +++ b/src/ts/game/systems/display.ts @@ -19,7 +19,7 @@ export class DisplaySystem extends GameSystem { constructor(root) { super(root); - for (const colorId: any in enumColors) { + for (const colorId in enumColors) { if (colorId === enumColors.uncolored) { continue; } @@ -42,7 +42,7 @@ export class DisplaySystem extends GameSystem { return isTrueItem(value) ? COLOR_ITEM_SINGLETONS[enumColors.white] : null; } case "color": { - const item: any = (value as ColorItem); + const item = (value as ColorItem); return item.color === enumColors.uncolored ? null : item; } case "shape": { @@ -55,17 +55,17 @@ export class DisplaySystem extends GameSystem { /** * Draws a given chunk */ - drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView): any { - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; + drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView) { + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; if (entity && entity.components.Display) { - const pinsComp: any = entity.components.WiredPins; - const network: any = pinsComp.slots[0].linkedNetwork; + const pinsComp = entity.components.WiredPins; + const network = pinsComp.slots[0].linkedNetwork; if (!network || !network.hasValue()) { continue; } - const value: any = this.getDisplayItem(network.currentValue); + const value = this.getDisplayItem(network.currentValue); if (!value) { continue; } @@ -76,7 +76,7 @@ export class DisplaySystem extends GameSystem { value, ]); } - const origin: any = entity.components.StaticMapEntity.origin; + const origin = entity.components.StaticMapEntity.origin; if (value.getItemType() === "color") { this.displaySprites[ alue as ColorItem).color].drawCachedCentered(parameters, (origin.x + 0.5) * globalConfig.tileSize, (origin.y + 0.5) * globalConfig.tileSize, globalConfig.tileSize); } diff --git a/src/ts/game/systems/filter.ts b/src/ts/game/systems/filter.ts index 3b9427e5..7feae2ce 100644 --- a/src/ts/game/systems/filter.ts +++ b/src/ts/game/systems/filter.ts @@ -4,27 +4,27 @@ import { FilterComponent } from "../components/filter"; import { Entity } from "../entity"; import { GameSystemWithFilter } from "../game_system_with_filter"; import { BOOL_TRUE_SINGLETON } from "../items/boolean_item"; -const MAX_ITEMS_IN_QUEUE: any = 2; +const MAX_ITEMS_IN_QUEUE = 2; export class FilterSystem extends GameSystemWithFilter { constructor(root) { super(root, [FilterComponent]); } - update(): any { - const progress: any = this.root.dynamicTickrate.deltaSeconds * + update() { + const progress = this.root.dynamicTickrate.deltaSeconds * this.root.hubGoals.getBeltBaseSpeed() * globalConfig.itemSpacingOnBelts; - const requiredProgress: any = 1 - progress; - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const filterComp: any = entity.components.Filter; - const ejectorComp: any = entity.components.ItemEjector; + const requiredProgress = 1 - progress; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const filterComp = entity.components.Filter; + const ejectorComp = entity.components.ItemEjector; // Process payloads - const slotsAndLists: any = [filterComp.pendingItemsToLeaveThrough, filterComp.pendingItemsToReject]; - for (let slotIndex: any = 0; slotIndex < slotsAndLists.length; ++slotIndex) { - const pendingItems: any = slotsAndLists[slotIndex]; - for (let j: any = 0; j < pendingItems.length; ++j) { - const nextItem: any = pendingItems[j]; + const slotsAndLists = [filterComp.pendingItemsToLeaveThrough, filterComp.pendingItemsToReject]; + for (let slotIndex = 0; slotIndex < slotsAndLists.length; ++slotIndex) { + const pendingItems = slotsAndLists[slotIndex]; + for (let j = 0; j < pendingItems.length; ++j) { + const nextItem = pendingItems[j]; // Advance next item nextItem.progress = Math.min(requiredProgress, nextItem.progress + progress); // Check if it's ready to eject @@ -37,17 +37,17 @@ export class FilterSystem extends GameSystemWithFilter { } } } - tryAcceptItem(entity: Entity, slot: number, item: BaseItem): any { - const network: any = entity.components.WiredPins.slots[0].linkedNetwork; + tryAcceptItem(entity: Entity, slot: number, item: BaseItem) { + const network = entity.components.WiredPins.slots[0].linkedNetwork; if (!network || !network.hasValue()) { // Filter is not connected return false; } - const value: any = network.currentValue; - const filterComp: any = entity.components.Filter; + const value = network.currentValue; + const filterComp = entity.components.Filter; assert(filterComp, "entity is no filter"); // Figure out which list we have to check - let listToCheck: any; + let listToCheck; if (value.equals(BOOL_TRUE_SINGLETON) || value.equals(item)) { listToCheck = filterComp.pendingItemsToLeaveThrough; } diff --git a/src/ts/game/systems/goal_acceptor.ts b/src/ts/game/systems/goal_acceptor.ts index 0a42acf0..41e79d7e 100644 --- a/src/ts/game/systems/goal_acceptor.ts +++ b/src/ts/game/systems/goal_acceptor.ts @@ -11,12 +11,12 @@ export class GoalAcceptorSystem extends GameSystemWithFilter { constructor(root) { super(root, [GoalAcceptorComponent]); } - update(): any { - const now: any = this.root.time.now(); - let allAccepted: any = true; - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const goalComp: any = entity.components.GoalAcceptor; + update() { + const now = this.root.time.now(); + let allAccepted = true; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const goalComp = entity.components.GoalAcceptor; if (!goalComp.lastDelivery) { allAccepted = false; continue; @@ -118,23 +118,23 @@ export class GoalAcceptorSystem extends GameSystemWithFilter { * @param {MapChunk} chunk * @returns */ - drawChunk(parameters: DrawParameters, chunk: MapChunk): any { - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const goalComp: any = contents[i].components.GoalAcceptor; + drawChunk(parameters: DrawParameters, chunk: MapChunk) { + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const goalComp = contents[i].components.GoalAcceptor; if (!goalComp) { continue; } - const staticComp: any = contents[i].components.StaticMapEntity; - const item: any = goalComp.item; - const requiredItems: any = globalConfig.goalAcceptorItemsRequired; - const fillPercentage: any = clamp(goalComp.currentDeliveredItems / requiredItems, 0, 1); - const center: any = staticComp.getTileSpaceBounds().getCenter().toWorldSpace(); + const staticComp = contents[i].components.StaticMapEntity; + const item = goalComp.item; + const requiredItems = globalConfig.goalAcceptorItemsRequired; + const fillPercentage = clamp(goalComp.currentDeliveredItems / requiredItems, 0, 1); + const center = staticComp.getTileSpaceBounds().getCenter().toWorldSpace(); if (item) { - const localOffset: any = new Vector(0, -1.8).rotateFastMultipleOf90(staticComp.rotation); + const localOffset = new Vector(0, -1.8).rotateFastMultipleOf90(staticComp.rotation); item.drawItemCenteredClipped(center.x + localOffset.x, center.y + localOffset.y, parameters, globalConfig.tileSize * 0.65); } - const isValid: any = item && goalComp.currentDeliveredItems >= requiredItems; + const isValid = item && goalComp.currentDeliveredItems >= requiredItems; parameters.context.translate(center.x, center.y); parameters.context.rotate((staticComp.rotation / 180) * Math.PI); parameters.context.lineWidth = 1; @@ -143,8 +143,8 @@ export class GoalAcceptorSystem extends GameSystemWithFilter { parameters.context.lineCap = "round"; // progress arc goalComp.displayPercentage = lerp(goalComp.displayPercentage, fillPercentage, 0.2); - const startAngle: any = Math.PI * 0.595; - const maxAngle: any = Math.PI * 1.82; + const startAngle = Math.PI * 0.595; + const maxAngle = Math.PI * 1.82; parameters.context.beginPath(); parameters.context.arc(0.25, -1.5, 11.6, startAngle, startAngle + goalComp.displayPercentage * maxAngle, false); parameters.context.arc(0.25, -1.5, 15.5, startAngle + goalComp.displayPercentage * maxAngle, startAngle, true); diff --git a/src/ts/game/systems/hub.ts b/src/ts/game/systems/hub.ts index 5b8eb73f..f2dc0701 100644 --- a/src/ts/game/systems/hub.ts +++ b/src/ts/game/systems/hub.ts @@ -10,31 +10,31 @@ import { T } from "../../translations"; import { HubComponent } from "../components/hub"; import { Entity } from "../entity"; import { GameSystemWithFilter } from "../game_system_with_filter"; -const HUB_SIZE_TILES: any = 4; -const HUB_SIZE_PIXELS: any = HUB_SIZE_TILES * globalConfig.tileSize; +const HUB_SIZE_TILES = 4; +const HUB_SIZE_PIXELS = HUB_SIZE_TILES * globalConfig.tileSize; export class HubSystem extends GameSystemWithFilter { public hubSprite = Loader.getSprite("sprites/buildings/hub.png"); constructor(root) { super(root, [HubComponent]); } - draw(parameters: DrawParameters): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { + draw(parameters: DrawParameters) { + for (let i = 0; i < this.allEntities.length; ++i) { this.drawEntity(parameters, this.allEntities[i]); } } - update(): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { + update() { + for (let i = 0; i < this.allEntities.length; ++i) { // Set hub goal - const entity: any = this.allEntities[i]; - const pinsComp: any = entity.components.WiredPins; + const entity = this.allEntities[i]; + const pinsComp = entity.components.WiredPins; pinsComp.slots[0].value = this.root.shapeDefinitionMgr.getShapeItemFromDefinition(this.root.hubGoals.currentGoal.definition); } } - redrawHubBaseTexture(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number): any { + redrawHubBaseTexture(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number) { // This method is quite ugly, please ignore it! context.scale(dpi, dpi); - const parameters: any = new DrawParameters({ + const parameters = new DrawParameters({ context, visibleRect: new Rectangle(0, 0, w, h), desiredAtlasScale: ORIGINAL_SPRITE_SCALE, @@ -52,14 +52,14 @@ export class HubSystem extends GameSystemWithFilter { context.textAlign = "left"; return; } - const definition: any = this.root.hubGoals.currentGoal.definition; + const definition = this.root.hubGoals.currentGoal.definition; definition.drawCentered(45, 58, parameters, 36); - const goals: any = this.root.hubGoals.currentGoal; - const textOffsetX: any = 70; - const textOffsetY: any = 61; + const goals = this.root.hubGoals.currentGoal; + const textOffsetX = 70; + const textOffsetY = 61; if (goals.throughputOnly) { // Throughput - const deliveredText: any = T.ingame.statistics.shapesDisplayUnits.second.replace("", formatBigNumber(goals.required)); + const deliveredText = T.ingame.statistics.shapesDisplayUnits.second.replace("", formatBigNumber(goals.required)); context.font = "bold 12px GameFont"; context.fillStyle = "#64666e"; context.textAlign = "left"; @@ -67,8 +67,8 @@ export class HubSystem extends GameSystemWithFilter { } else { // Deliver count - const delivered: any = this.root.hubGoals.getCurrentGoalDelivered(); - const deliveredText: any = "" + formatBigNumber(delivered); + const delivered = this.root.hubGoals.getCurrentGoalDelivered(); + const deliveredText = "" + formatBigNumber(delivered); if (delivered > 9999) { context.font = "bold 16px GameFont"; } @@ -87,7 +87,7 @@ export class HubSystem extends GameSystemWithFilter { context.fillText("/ " + formatBigNumber(goals.required), textOffsetX, textOffsetY + 13); } // Reward - const rewardText: any = T.storyRewards[goals.reward].title.toUpperCase(); + const rewardText = T.storyRewards[goals.reward].title.toUpperCase(); if (rewardText.length > 12) { context.font = "bold 8px GameFont"; } @@ -111,7 +111,7 @@ export class HubSystem extends GameSystemWithFilter { context.font = "bold 10px GameFont"; context.fillText(T.buildings.hub.deliver.toUpperCase(), HUB_SIZE_PIXELS / 2, 30); // "To unlock" - const unlockText: any = T.buildings.hub.toUnlock.toUpperCase(); + const unlockText = T.buildings.hub.toUnlock.toUpperCase(); if (unlockText.length > 15) { context.font = "bold 8px GameFont"; } @@ -121,16 +121,16 @@ export class HubSystem extends GameSystemWithFilter { context.fillText(T.buildings.hub.toUnlock.toUpperCase(), HUB_SIZE_PIXELS / 2, 92); context.textAlign = "left"; } - drawEntity(parameters: DrawParameters, entity: Entity): any { - const staticComp: any = entity.components.StaticMapEntity; + drawEntity(parameters: DrawParameters, entity: Entity) { + const staticComp = entity.components.StaticMapEntity; if (!staticComp.shouldBeDrawn(parameters)) { return; } // Deliver count - const delivered: any = this.root.hubGoals.getCurrentGoalDelivered(); - const deliveredText: any = "" + formatBigNumber(delivered); - const dpi: any = smoothenDpi(globalConfig.shapesSharpness * parameters.zoomLevel); - const canvas: any = parameters.root.buffers.getForKey({ + const delivered = this.root.hubGoals.getCurrentGoalDelivered(); + const deliveredText = "" + formatBigNumber(delivered); + const dpi = smoothenDpi(globalConfig.shapesSharpness * parameters.zoomLevel); + const canvas = parameters.root.buffers.getForKey({ key: "hub", subKey: dpi + "/" + this.root.hubGoals.level + "/" + deliveredText, w: globalConfig.tileSize * 4, @@ -138,7 +138,7 @@ export class HubSystem extends GameSystemWithFilter { dpi, redrawMethod: this.redrawHubBaseTexture.bind(this), }); - const extrude: any = 8; + const extrude = 8; drawSpriteClipped({ parameters, sprite: canvas, diff --git a/src/ts/game/systems/item_acceptor.ts b/src/ts/game/systems/item_acceptor.ts index dde3e5fc..b78699d3 100644 --- a/src/ts/game/systems/item_acceptor.ts +++ b/src/ts/game/systems/item_acceptor.ts @@ -11,7 +11,7 @@ export class ItemAcceptorSystem extends GameSystemWithFilter { constructor(root) { super(root, [ItemAcceptorComponent]); } - update(): any { + update() { if (this.root.app.settings.getAllSettings().simplifiedBelts) { // Disabled in potato mode return; @@ -23,21 +23,21 @@ export class ItemAcceptorSystem extends GameSystemWithFilter { return; } // Compute how much ticks we missed - const numTicks: any = 1 + this.accumulatedTicksWhileInMapOverview; - const progress: any = this.root.dynamicTickrate.deltaSeconds * + const numTicks = 1 + this.accumulatedTicksWhileInMapOverview; + const progress = this.root.dynamicTickrate.deltaSeconds * 2 * this.root.hubGoals.getBeltBaseSpeed() * globalConfig.itemSpacingOnBelts * // * 2 because its only a half tile numTicks; // Reset accumulated ticks this.accumulatedTicksWhileInMapOverview = 0; - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const aceptorComp: any = entity.components.ItemAcceptor; - const animations: any = aceptorComp.itemConsumptionAnimations; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const aceptorComp = entity.components.ItemAcceptor; + const animations = aceptorComp.itemConsumptionAnimations; // Process item consumption animations to avoid items popping from the belts - for (let animIndex: any = 0; animIndex < animations.length; ++animIndex) { - const anim: any = animations[animIndex]; + for (let animIndex = 0; animIndex < animations.length; ++animIndex) { + const anim = animations[animIndex]; anim.animProgress += progress; if (anim.animProgress > 1) { fastArrayDelete(animations, animIndex); @@ -46,29 +46,29 @@ export class ItemAcceptorSystem extends GameSystemWithFilter { } } } - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { if (this.root.app.settings.getAllSettings().simplifiedBelts) { // Disabled in potato mode return; } - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const acceptorComp: any = entity.components.ItemAcceptor; + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const acceptorComp = entity.components.ItemAcceptor; if (!acceptorComp) { continue; } - const staticComp: any = entity.components.StaticMapEntity; - for (let animIndex: any = 0; animIndex < acceptorComp.itemConsumptionAnimations.length; ++animIndex) { - const { item, slotIndex, animProgress, direction }: any = acceptorComp.itemConsumptionAnimations[animIndex]; - const slotData: any = acceptorComp.slots[slotIndex]; - const realSlotPos: any = staticComp.localTileToWorld(slotData.pos); + const staticComp = entity.components.StaticMapEntity; + for (let animIndex = 0; animIndex < acceptorComp.itemConsumptionAnimations.length; ++animIndex) { + const { item, slotIndex, animProgress, direction } = acceptorComp.itemConsumptionAnimations[animIndex]; + const slotData = acceptorComp.slots[slotIndex]; + const realSlotPos = staticComp.localTileToWorld(slotData.pos); if (!chunk.tileSpaceRectangle.containsPoint(realSlotPos.x, realSlotPos.y)) { // Not within this chunk continue; } - const fadeOutDirection: any = enumDirectionToVector[staticComp.localDirectionToWorld(direction)]; - const finalTile: any = realSlotPos.subScalars(fadeOutDirection.x * (animProgress / 2 - 0.5), fadeOutDirection.y * (animProgress / 2 - 0.5)); + const fadeOutDirection = enumDirectionToVector[staticComp.localDirectionToWorld(direction)]; + const finalTile = realSlotPos.subScalars(fadeOutDirection.x * (animProgress / 2 - 0.5), fadeOutDirection.y * (animProgress / 2 - 0.5)); item.drawItemCenteredClipped((finalTile.x + 0.5) * globalConfig.tileSize, (finalTile.y + 0.5) * globalConfig.tileSize, parameters, globalConfig.defaultItemDiameter); } } diff --git a/src/ts/game/systems/item_ejector.ts b/src/ts/game/systems/item_ejector.ts index aa180a30..48fae4a2 100644 --- a/src/ts/game/systems/item_ejector.ts +++ b/src/ts/game/systems/item_ejector.ts @@ -11,7 +11,7 @@ import { ItemEjectorComponent } from "../components/item_ejector"; import { Entity } from "../entity"; import { GameSystemWithFilter } from "../game_system_with_filter"; import { MapChunkView } from "../map_chunk_view"; -const logger: any = createLogger("systems/ejector"); +const logger = createLogger("systems/ejector"); export class ItemEjectorSystem extends GameSystemWithFilter { public staleAreaDetector = new StaleAreaDetector({ root: this.root, @@ -27,14 +27,14 @@ export class ItemEjectorSystem extends GameSystemWithFilter { /** * Recomputes an area after it changed */ - recomputeArea(area: Rectangle): any { + recomputeArea(area: Rectangle) { const seenUids: Set = new Set(); - for (let x: any = 0; x < area.w; ++x) { - for (let y: any = 0; y < area.h; ++y) { - const tileX: any = area.x + x; - const tileY: any = area.y + y; + for (let x = 0; x < area.w; ++x) { + for (let y = 0; y < area.h; ++y) { + const tileX = area.x + x; + const tileY = area.y + y; // @NOTICE: Item ejector currently only supports regular layer - const contents: any = this.root.map.getLayerContentXY(tileX, tileY, "regular"); + const contents = this.root.map.getLayerContentXY(tileX, tileY, "regular"); if (contents && contents.components.ItemEjector) { if (!seenUids.has(contents.uid)) { seenUids.add(contents.uid); @@ -47,37 +47,37 @@ export class ItemEjectorSystem extends GameSystemWithFilter { /** * Recomputes the whole cache after the game has loaded */ - recomputeCacheFull(): any { + recomputeCacheFull() { logger.log("Full cache recompute in post load hook"); - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; this.recomputeSingleEntityCache(entity); } } - recomputeSingleEntityCache(entity: Entity): any { - const ejectorComp: any = entity.components.ItemEjector; - const staticComp: any = entity.components.StaticMapEntity; - for (let slotIndex: any = 0; slotIndex < ejectorComp.slots.length; ++slotIndex) { - const ejectorSlot: any = ejectorComp.slots[slotIndex]; + recomputeSingleEntityCache(entity: Entity) { + const ejectorComp = entity.components.ItemEjector; + const staticComp = entity.components.StaticMapEntity; + for (let slotIndex = 0; slotIndex < ejectorComp.slots.length; ++slotIndex) { + const ejectorSlot = ejectorComp.slots[slotIndex]; // Clear the old cache. ejectorSlot.cachedDestSlot = null; ejectorSlot.cachedTargetEntity = null; ejectorSlot.cachedBeltPath = null; // Figure out where and into which direction we eject items - const ejectSlotWsTile: any = staticComp.localTileToWorld(ejectorSlot.pos); - const ejectSlotWsDirection: any = staticComp.localDirectionToWorld(ejectorSlot.direction); - const ejectSlotWsDirectionVector: any = enumDirectionToVector[ejectSlotWsDirection]; - const ejectSlotTargetWsTile: any = ejectSlotWsTile.add(ejectSlotWsDirectionVector); + const ejectSlotWsTile = staticComp.localTileToWorld(ejectorSlot.pos); + const ejectSlotWsDirection = staticComp.localDirectionToWorld(ejectorSlot.direction); + const ejectSlotWsDirectionVector = enumDirectionToVector[ejectSlotWsDirection]; + const ejectSlotTargetWsTile = ejectSlotWsTile.add(ejectSlotWsDirectionVector); // Try to find the given acceptor component to take the item // Since there can be cross layer dependencies, check on all layers - const targetEntities: any = this.root.map.getLayersContentsMultipleXY(ejectSlotTargetWsTile.x, ejectSlotTargetWsTile.y); - for (let i: any = 0; i < targetEntities.length; ++i) { - const targetEntity: any = targetEntities[i]; - const targetStaticComp: any = targetEntity.components.StaticMapEntity; - const targetBeltComp: any = targetEntity.components.Belt; + const targetEntities = this.root.map.getLayersContentsMultipleXY(ejectSlotTargetWsTile.x, ejectSlotTargetWsTile.y); + for (let i = 0; i < targetEntities.length; ++i) { + const targetEntity = targetEntities[i]; + const targetStaticComp = targetEntity.components.StaticMapEntity; + const targetBeltComp = targetEntity.components.Belt; // Check for belts (special case) if (targetBeltComp) { - const beltAcceptingDirection: any = targetStaticComp.localDirectionToWorld(enumDirection.top); + const beltAcceptingDirection = targetStaticComp.localDirectionToWorld(enumDirection.top); if (ejectSlotWsDirection === beltAcceptingDirection) { ejectorSlot.cachedTargetEntity = targetEntity; ejectorSlot.cachedBeltPath = targetBeltComp.assignedPath; @@ -85,12 +85,12 @@ export class ItemEjectorSystem extends GameSystemWithFilter { } } // Check for item acceptors - const targetAcceptorComp: any = targetEntity.components.ItemAcceptor; + const targetAcceptorComp = targetEntity.components.ItemAcceptor; if (!targetAcceptorComp) { // Entity doesn't accept items continue; } - const matchingSlot: any = targetAcceptorComp.findMatchingSlot(targetStaticComp.worldToLocalTile(ejectSlotTargetWsTile), targetStaticComp.worldDirectionToLocal(ejectSlotWsDirection)); + const matchingSlot = targetAcceptorComp.findMatchingSlot(targetStaticComp.worldToLocalTile(ejectSlotTargetWsTile), targetStaticComp.worldDirectionToLocal(ejectSlotWsDirection)); if (!matchingSlot) { // No matching slot found continue; @@ -102,21 +102,21 @@ export class ItemEjectorSystem extends GameSystemWithFilter { } } } - update(): any { + update() { this.staleAreaDetector.update(); // Precompute effective belt speed - let progressGrowth: any = 2 * this.root.dynamicTickrate.deltaSeconds; + let progressGrowth = 2 * this.root.dynamicTickrate.deltaSeconds; if (G_IS_DEV && globalConfig.debug.instantBelts) { progressGrowth = 1; } // Go over all cache entries - for (let i: any = 0; i < this.allEntities.length; ++i) { - const sourceEntity: any = this.allEntities[i]; - const sourceEjectorComp: any = sourceEntity.components.ItemEjector; - const slots: any = sourceEjectorComp.slots; - for (let j: any = 0; j < slots.length; ++j) { - const sourceSlot: any = slots[j]; - const item: any = sourceSlot.item; + for (let i = 0; i < this.allEntities.length; ++i) { + const sourceEntity = this.allEntities[i]; + const sourceEjectorComp = sourceEntity.components.ItemEjector; + const slots = sourceEjectorComp.slots; + for (let j = 0; j < slots.length; ++j) { + const sourceSlot = slots[j]; + const item = sourceSlot.item; if (!item) { // No item available to be ejected continue; @@ -134,7 +134,7 @@ export class ItemEjectorSystem extends GameSystemWithFilter { continue; } // Check if we are ejecting to a belt path - const destPath: any = sourceSlot.cachedBeltPath; + const destPath = sourceSlot.cachedBeltPath; if (destPath) { // Try passing the item over if (destPath.tryAcceptItem(item)) { @@ -145,10 +145,10 @@ export class ItemEjectorSystem extends GameSystemWithFilter { continue; } // Check if the target acceptor can actually accept this item - const destEntity: any = sourceSlot.cachedTargetEntity; - const destSlot: any = sourceSlot.cachedDestSlot; + const destEntity = sourceSlot.cachedTargetEntity; + const destSlot = sourceSlot.cachedDestSlot; if (destSlot) { - const targetAcceptorComp: any = destEntity.components.ItemAcceptor; + const targetAcceptorComp = destEntity.components.ItemAcceptor; if (!targetAcceptorComp.canAcceptItem(destSlot.index, item)) { continue; } @@ -165,12 +165,12 @@ export class ItemEjectorSystem extends GameSystemWithFilter { } } } - tryPassOverItem(item: BaseItem, receiver: Entity, slotIndex: number): any { + tryPassOverItem(item: BaseItem, receiver: Entity, slotIndex: number) { // Try figuring out how what to do with the item // @TODO: Kinda hacky. How to solve this properly? Don't want to go through inheritance hell. - const beltComp: any = receiver.components.Belt; + const beltComp = receiver.components.Belt; if (beltComp) { - const path: any = beltComp.assignedPath; + const path = beltComp.assignedPath; assert(path, "belt has no path"); if (path.tryAcceptItem(item)) { return true; @@ -185,7 +185,7 @@ export class ItemEjectorSystem extends GameSystemWithFilter { // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - const itemProcessorComp: any = receiver.components.ItemProcessor; + const itemProcessorComp = receiver.components.ItemProcessor; if (itemProcessorComp) { // Check for potential filters if (!this.root.systemMgr.systems.itemProcessor.checkRequirements(receiver, item, slotIndex)) { @@ -198,7 +198,7 @@ export class ItemEjectorSystem extends GameSystemWithFilter { // Item processor can have nothing else return false; } - const undergroundBeltComp: any = receiver.components.UndergroundBelt; + const undergroundBeltComp = receiver.components.UndergroundBelt; if (undergroundBeltComp) { // Its an underground belt. yay. if (undergroundBeltComp.tryAcceptExternalItem(item, this.root.hubGoals.getUndergroundBeltBaseSpeed())) { @@ -207,7 +207,7 @@ export class ItemEjectorSystem extends GameSystemWithFilter { // Underground belt can have nothing else return false; } - const storageComp: any = receiver.components.Storage; + const storageComp = receiver.components.Storage; if (storageComp) { // It's a storage if (storageComp.canAcceptItem(item)) { @@ -217,7 +217,7 @@ export class ItemEjectorSystem extends GameSystemWithFilter { // Storage can't have anything else return false; } - const filterComp: any = receiver.components.Filter; + const filterComp = receiver.components.Filter; if (filterComp) { // It's a filter! Unfortunately the filter has to know a lot about it's // surrounding state and components, so it can't be within the component itself. @@ -227,22 +227,22 @@ export class ItemEjectorSystem extends GameSystemWithFilter { } return false; } - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { if (this.root.app.settings.getAllSettings().simplifiedBelts) { // Disabled in potato mode return; } - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const ejectorComp: any = entity.components.ItemEjector; + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const ejectorComp = entity.components.ItemEjector; if (!ejectorComp) { continue; } - const staticComp: any = entity.components.StaticMapEntity; - for (let i: any = 0; i < ejectorComp.slots.length; ++i) { - const slot: any = ejectorComp.slots[i]; - const ejectedItem: any = slot.item; + const staticComp = entity.components.StaticMapEntity; + for (let i = 0; i < ejectorComp.slots.length; ++i) { + const slot = ejectorComp.slots[i]; + const ejectedItem = slot.item; if (!ejectedItem) { // No item continue; @@ -252,8 +252,8 @@ export class ItemEjectorSystem extends GameSystemWithFilter { continue; } // Limit the progress to the maximum available space on the next belt (also see #1000) - let progress: any = slot.progress; - const nextBeltPath: any = slot.cachedBeltPath; + let progress = slot.progress; + const nextBeltPath = slot.cachedBeltPath; if (nextBeltPath) { /* If you imagine the track between the center of the building and the center of the first belt as @@ -298,24 +298,24 @@ export class ItemEjectorSystem extends GameSystemWithFilter { And that's it! If you summarize the calculations from above into a formula, you get the one below. */ - const maxProgress: any = (0.5 + nextBeltPath.spacingToFirstItem - globalConfig.itemSpacingOnBelts) * 2; + const maxProgress = (0.5 + nextBeltPath.spacingToFirstItem - globalConfig.itemSpacingOnBelts) * 2; progress = Math.min(maxProgress, progress); } // Skip if the item would barely be visible if (progress < 0.05) { continue; } - const realPosition: any = staticComp.localTileToWorld(slot.pos); + const realPosition = staticComp.localTileToWorld(slot.pos); if (!chunk.tileSpaceRectangle.containsPoint(realPosition.x, realPosition.y)) { // Not within this chunk continue; } - const realDirection: any = staticComp.localDirectionToWorld(slot.direction); - const realDirectionVector: any = enumDirectionToVector[realDirection]; - const tileX: any = realPosition.x + 0.5 + realDirectionVector.x * 0.5 * progress; - const tileY: any = realPosition.y + 0.5 + realDirectionVector.y * 0.5 * progress; - const worldX: any = tileX * globalConfig.tileSize; - const worldY: any = tileY * globalConfig.tileSize; + const realDirection = staticComp.localDirectionToWorld(slot.direction); + const realDirectionVector = enumDirectionToVector[realDirection]; + const tileX = realPosition.x + 0.5 + realDirectionVector.x * 0.5 * progress; + const tileY = realPosition.y + 0.5 + realDirectionVector.y * 0.5 * progress; + const worldX = tileX * globalConfig.tileSize; + const worldY = tileY * globalConfig.tileSize; ejectedItem.drawItemCenteredClipped(worldX, worldY, parameters, globalConfig.defaultItemDiameter); } } diff --git a/src/ts/game/systems/item_processor.ts b/src/ts/game/systems/item_processor.ts index c1e30ca0..044d5ee7 100644 --- a/src/ts/game/systems/item_processor.ts +++ b/src/ts/game/systems/item_processor.ts @@ -10,7 +10,7 @@ import { ShapeItem } from "../items/shape_item"; /** * We need to allow queuing charges, otherwise the throughput will stall */ -const MAX_QUEUED_CHARGES: any = 2; +const MAX_QUEUED_CHARGES = 2; export type ProducedItem = { item: BaseItem; preferredSlot?: number; @@ -65,16 +65,16 @@ export class ItemProcessorSystem extends GameSystemWithFilter { constructor(root) { super(root, [ItemProcessorComponent]); // Bind all handlers - for (const key: any in this.handlers) { + for (const key in this.handlers) { this.handlers[key] = this.handlers[key].bind(this); } } - update(): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const processorComp: any = entity.components.ItemProcessor; - const ejectorComp: any = entity.components.ItemEjector; - const currentCharge: any = processorComp.ongoingCharges[0]; + update() { + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const processorComp = entity.components.ItemProcessor; + const ejectorComp = entity.components.ItemEjector; + const currentCharge = processorComp.ongoingCharges[0]; if (currentCharge) { // Process next charge if (currentCharge.remainingTime > 0.0) { @@ -86,9 +86,9 @@ export class ItemProcessorSystem extends GameSystemWithFilter { } // Check if it finished and we don't already have queued ejects if (currentCharge.remainingTime <= 0.0 && !processorComp.queuedEjects.length) { - const itemsToEject: any = currentCharge.items; + const itemsToEject = currentCharge.items; // Go over all items and add them to the queue - for (let j: any = 0; j < itemsToEject.length; ++j) { + for (let j = 0; j < itemsToEject.length; ++j) { processorComp.queuedEjects.push(itemsToEject[j]); } processorComp.ongoingCharges.shift(); @@ -100,10 +100,10 @@ export class ItemProcessorSystem extends GameSystemWithFilter { this.startNewCharge(entity); } } - for (let j: any = 0; j < processorComp.queuedEjects.length; ++j) { - const { item, requiredSlot, preferredSlot }: any = processorComp.queuedEjects[j]; + for (let j = 0; j < processorComp.queuedEjects.length; ++j) { + const { item, requiredSlot, preferredSlot } = processorComp.queuedEjects[j]; assert(ejectorComp, "To eject items, the building needs to have an ejector"); - let slot: any = null; + let slot = null; if (requiredSlot !== null && requiredSlot !== undefined) { // We have a slot override, check if that is free if (ejectorComp.canEjectOnSlot(requiredSlot)) { @@ -143,8 +143,8 @@ export class ItemProcessorSystem extends GameSystemWithFilter { * {} */ checkRequirements(entity: Entity, item: BaseItem, slotIndex: number): boolean { - const itemProcessorComp: any = entity.components.ItemProcessor; - const pinsComp: any = entity.components.WiredPins; + const itemProcessorComp = entity.components.ItemProcessor; + const pinsComp = entity.components.WiredPins; if (MODS_PROCESSING_REQUIREMENTS[itemProcessorComp.processingRequirement]) { return MODS_PROCESSING_REQUIREMENTS[itemProcessorComp.processingRequirement].bind(this)({ entity, @@ -159,8 +159,8 @@ export class ItemProcessorSystem extends GameSystemWithFilter { return true; } // Check the network value at the given slot - const network: any = pinsComp.slots[slotIndex - 1].linkedNetwork; - const slotIsEnabled: any = network && network.hasValue() && isTruthyItem(network.currentValue); + const network = pinsComp.slots[slotIndex - 1].linkedNetwork; + const slotIsEnabled = network && network.hasValue() && isTruthyItem(network.currentValue); if (!slotIsEnabled) { return false; } @@ -174,8 +174,8 @@ export class ItemProcessorSystem extends GameSystemWithFilter { /** * Checks whether it's possible to process something */ - canProcess(entity: Entity): any { - const processorComp: any = entity.components.ItemProcessor; + canProcess(entity: Entity) { + const processorComp = entity.components.ItemProcessor; if (MODS_CAN_PROCESS[processorComp.processingRequirement]) { return MODS_CAN_PROCESS[processorComp.processingRequirement].bind(this)({ entity, @@ -190,18 +190,18 @@ export class ItemProcessorSystem extends GameSystemWithFilter { // QUAD PAINTER // For the quad painter, it might be possible to start processing earlier case enumItemProcessorRequirements.painterQuad: { - const pinsComp: any = entity.components.WiredPins; + const pinsComp = entity.components.WiredPins; // First slot is the shape, so if it's not there we can't do anything - const shapeItem: any = (processorComp.inputSlots.get(0) as ShapeItem); + const shapeItem = processorComp.inputSlots.get(0) as ShapeItem); if (!shapeItem) { return false; } - const slotStatus: any = []; + const slotStatus = []; // Check which slots are enabled - for (let i: any = 0; i < 4; ++i) { + for (let i = 0; i < 4; ++i) { // Extract the network value on the Nth pin - const network: any = pinsComp.slots[i].linkedNetwork; - const networkValue: any = network && network.hasValue() ? network.currentValue : null; + const network = pinsComp.slots[i].linkedNetwork; + const networkValue = network && network.hasValue() ? network.currentValue : null; // If there is no "1" on that slot, don't paint there if (!isTruthyItem(networkValue)) { slotStatus.push(false); @@ -214,12 +214,12 @@ export class ItemProcessorSystem extends GameSystemWithFilter { return false; } // Check if all colors of the enabled slots are there - for (let i: any = 0; i < slotStatus.length; ++i) { + for (let i = 0; i < slotStatus.length; ++i) { if (slotStatus[i] && !processorComp.inputSlots.get(1 + i)) { // A slot which is enabled wasn't enabled. Make sure if there is anything on the quadrant, // it is not possible to paint, but if there is nothing we can ignore it - for (let j: any = 0; j < 4; ++j) { - const layer: any = shapeItem.definition.layers[j]; + for (let j = 0; j < 4; ++j) { + const layer = shapeItem.definition.layers[j]; if (layer && layer[i]) { return false; } @@ -235,10 +235,10 @@ export class ItemProcessorSystem extends GameSystemWithFilter { /** * Starts a new charge for the entity */ - startNewCharge(entity: Entity): any { - const processorComp: any = entity.components.ItemProcessor; + startNewCharge(entity: Entity) { + const processorComp = entity.components.ItemProcessor; // First, take items - const items: any = processorComp.inputSlots; + const items = processorComp.inputSlots; const outItems: Array = []; const handler: function(: void):void = this.handlers[processorComp.type]; assert(handler, "No handler for processor type defined: " + processorComp.type); @@ -250,16 +250,16 @@ export class ItemProcessorSystem extends GameSystemWithFilter { inputCount: processorComp.inputCount, }); // Track produced items - for (let i: any = 0; i < outItems.length; ++i) { + for (let i = 0; i < outItems.length; ++i) { if (!outItems[i].doNotTrack) { this.root.signals.itemProduced.dispatch(outItems[i].item); } } // Queue Charge - const baseSpeed: any = this.root.hubGoals.getProcessorBaseSpeed(processorComp.type); - const originalTime: any = 1 / baseSpeed; - const bonusTimeToApply: any = Math.min(originalTime, processorComp.bonusTime); - const timeToProcess: any = originalTime - bonusTimeToApply; + const baseSpeed = this.root.hubGoals.getProcessorBaseSpeed(processorComp.type); + const originalTime = 1 / baseSpeed; + const bonusTimeToApply = Math.min(originalTime, processorComp.bonusTime); + const timeToProcess = originalTime - bonusTimeToApply; processorComp.bonusTime -= bonusTimeToApply; processorComp.ongoingCharges.push({ items: outItems, @@ -268,12 +268,12 @@ export class ItemProcessorSystem extends GameSystemWithFilter { processorComp.inputSlots.clear(); processorComp.inputCount = 0; } - process_BALANCER(payload: ProcessorImplementationPayload): any { + process_BALANCER(payload: ProcessorImplementationPayload) { assert(payload.entity.components.ItemEjector, "To be a balancer, the building needs to have an ejector"); - const availableSlots: any = payload.entity.components.ItemEjector.slots.length; - const processorComp: any = payload.entity.components.ItemProcessor; - for (let i: any = 0; i < 2; ++i) { - const item: any = payload.items.get(i); + const availableSlots = payload.entity.components.ItemEjector.slots.length; + const processorComp = payload.entity.components.ItemProcessor; + for (let i = 0; i < 2; ++i) { + const item = payload.items.get(i); if (!item) { continue; } @@ -285,14 +285,14 @@ export class ItemProcessorSystem extends GameSystemWithFilter { } return true; } - process_CUTTER(payload: ProcessorImplementationPayload): any { - const inputItem: any = (payload.items.get(0) as ShapeItem); + process_CUTTER(payload: ProcessorImplementationPayload) { + const inputItem = payload.items.get(0) as ShapeItem); assert(inputItem instanceof ShapeItem, "Input for cut is not a shape"); - const inputDefinition: any = inputItem.definition; - const cutDefinitions: any = this.root.shapeDefinitionMgr.shapeActionCutHalf(inputDefinition); - const ejectorComp: any = payload.entity.components.ItemEjector; - for (let i: any = 0; i < cutDefinitions.length; ++i) { - const definition: any = cutDefinitions[i]; + const inputDefinition = inputItem.definition; + const cutDefinitions = this.root.shapeDefinitionMgr.shapeActionCutHalf(inputDefinition); + const ejectorComp = payload.entity.components.ItemEjector; + for (let i = 0; i < cutDefinitions.length; ++i) { + const definition = cutDefinitions[i]; if (definition.isEntirelyEmpty()) { ejectorComp.slots[i].lastItem = null; continue; @@ -303,14 +303,14 @@ export class ItemProcessorSystem extends GameSystemWithFilter { }); } } - process_CUTTER_QUAD(payload: ProcessorImplementationPayload): any { - const inputItem: any = (payload.items.get(0) as ShapeItem); + process_CUTTER_QUAD(payload: ProcessorImplementationPayload) { + const inputItem = payload.items.get(0) as ShapeItem); assert(inputItem instanceof ShapeItem, "Input for cut is not a shape"); - const inputDefinition: any = inputItem.definition; - const cutDefinitions: any = this.root.shapeDefinitionMgr.shapeActionCutQuad(inputDefinition); - const ejectorComp: any = payload.entity.components.ItemEjector; - for (let i: any = 0; i < cutDefinitions.length; ++i) { - const definition: any = cutDefinitions[i]; + const inputDefinition = inputItem.definition; + const cutDefinitions = this.root.shapeDefinitionMgr.shapeActionCutQuad(inputDefinition); + const ejectorComp = payload.entity.components.ItemEjector; + for (let i = 0; i < cutDefinitions.length; ++i) { + const definition = cutDefinitions[i]; if (definition.isEntirelyEmpty()) { ejectorComp.slots[i].lastItem = null; continue; @@ -321,57 +321,57 @@ export class ItemProcessorSystem extends GameSystemWithFilter { }); } } - process_ROTATER(payload: ProcessorImplementationPayload): any { - const inputItem: any = (payload.items.get(0) as ShapeItem); + process_ROTATER(payload: ProcessorImplementationPayload) { + const inputItem = payload.items.get(0) as ShapeItem); assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape"); - const inputDefinition: any = inputItem.definition; - const rotatedDefinition: any = this.root.shapeDefinitionMgr.shapeActionRotateCW(inputDefinition); + const inputDefinition = inputItem.definition; + const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateCW(inputDefinition); payload.outItems.push({ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition), }); } - process_ROTATER_CCW(payload: ProcessorImplementationPayload): any { - const inputItem: any = (payload.items.get(0) as ShapeItem); + process_ROTATER_CCW(payload: ProcessorImplementationPayload) { + const inputItem = payload.items.get(0) as ShapeItem); assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape"); - const inputDefinition: any = inputItem.definition; - const rotatedDefinition: any = this.root.shapeDefinitionMgr.shapeActionRotateCCW(inputDefinition); + const inputDefinition = inputItem.definition; + const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateCCW(inputDefinition); payload.outItems.push({ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition), }); } - process_ROTATER_180(payload: ProcessorImplementationPayload): any { - const inputItem: any = (payload.items.get(0) as ShapeItem); + process_ROTATER_180(payload: ProcessorImplementationPayload) { + const inputItem = payload.items.get(0) as ShapeItem); assert(inputItem instanceof ShapeItem, "Input for rotation is not a shape"); - const inputDefinition: any = inputItem.definition; - const rotatedDefinition: any = this.root.shapeDefinitionMgr.shapeActionRotate180(inputDefinition); + const inputDefinition = inputItem.definition; + const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotate180(inputDefinition); payload.outItems.push({ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition), }); } - process_STACKER(payload: ProcessorImplementationPayload): any { - const lowerItem: any = (payload.items.get(0) as ShapeItem); - const upperItem: any = (payload.items.get(1) as ShapeItem); + process_STACKER(payload: ProcessorImplementationPayload) { + const lowerItem = payload.items.get(0) as ShapeItem); + const upperItem = payload.items.get(1) as ShapeItem); assert(lowerItem instanceof ShapeItem, "Input for lower stack is not a shape"); assert(upperItem instanceof ShapeItem, "Input for upper stack is not a shape"); - const stackedDefinition: any = this.root.shapeDefinitionMgr.shapeActionStack(lowerItem.definition, upperItem.definition); + const stackedDefinition = this.root.shapeDefinitionMgr.shapeActionStack(lowerItem.definition, upperItem.definition); payload.outItems.push({ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(stackedDefinition), }); } - process_TRASH(payload: ProcessorImplementationPayload): any { + process_TRASH(payload: ProcessorImplementationPayload) { // Do nothing .. } - process_MIXER(payload: ProcessorImplementationPayload): any { + process_MIXER(payload: ProcessorImplementationPayload) { // Find both colors and combine them - const item1: any = (payload.items.get(0) as ColorItem); - const item2: any = (payload.items.get(1) as ColorItem); + const item1 = payload.items.get(0) as ColorItem); + const item2 = payload.items.get(1) as ColorItem); assert(item1 instanceof ColorItem, "Input for color mixer is not a color"); assert(item2 instanceof ColorItem, "Input for color mixer is not a color"); - const color1: any = item1.color; - const color2: any = item2.color; + const color1 = item1.color; + const color2 = item2.color; // Try finding mixer color, and if we can't mix it we simply return the same color - const mixedColor: any = enumColorMixingResults[color1][color2]; - let resultColor: any = color1; + const mixedColor = enumColorMixingResults[color1][color2]; + let resultColor = color1; if (mixedColor) { resultColor = mixedColor; } @@ -379,23 +379,23 @@ export class ItemProcessorSystem extends GameSystemWithFilter { item: COLOR_ITEM_SINGLETONS[resultColor], }); } - process_PAINTER(payload: ProcessorImplementationPayload): any { - const shapeItem: any = (payload.items.get(0) as ShapeItem); - const colorItem: any = (payload.items.get(1) as ColorItem); - const colorizedDefinition: any = this.root.shapeDefinitionMgr.shapeActionPaintWith(shapeItem.definition, colorItem.color); + process_PAINTER(payload: ProcessorImplementationPayload) { + const shapeItem = payload.items.get(0) as ShapeItem); + const colorItem = payload.items.get(1) as ColorItem); + const colorizedDefinition = this.root.shapeDefinitionMgr.shapeActionPaintWith(shapeItem.definition, colorItem.color); payload.outItems.push({ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition), }); } - process_PAINTER_DOUBLE(payload: ProcessorImplementationPayload): any { - const shapeItem1: any = (payload.items.get(0) as ShapeItem); - const shapeItem2: any = (payload.items.get(1) as ShapeItem); - const colorItem: any = (payload.items.get(2) as ColorItem); + process_PAINTER_DOUBLE(payload: ProcessorImplementationPayload) { + const shapeItem1 = payload.items.get(0) as ShapeItem); + const shapeItem2 = payload.items.get(1) as ShapeItem); + const colorItem = payload.items.get(2) as ColorItem); assert(shapeItem1 instanceof ShapeItem, "Input for painter is not a shape"); assert(shapeItem2 instanceof ShapeItem, "Input for painter is not a shape"); assert(colorItem instanceof ColorItem, "Input for painter is not a color"); - const colorizedDefinition1: any = this.root.shapeDefinitionMgr.shapeActionPaintWith(shapeItem1.definition, colorItem.color); - const colorizedDefinition2: any = this.root.shapeDefinitionMgr.shapeActionPaintWith(shapeItem2.definition, colorItem.color); + const colorizedDefinition1 = this.root.shapeDefinitionMgr.shapeActionPaintWith(shapeItem1.definition, colorItem.color); + const colorizedDefinition2 = this.root.shapeDefinitionMgr.shapeActionPaintWith(shapeItem2.definition, colorItem.color); payload.outItems.push({ item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition1), }); @@ -403,17 +403,17 @@ export class ItemProcessorSystem extends GameSystemWithFilter { item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition2), }); } - process_PAINTER_QUAD(payload: ProcessorImplementationPayload): any { - const shapeItem: any = (payload.items.get(0) as ShapeItem); + process_PAINTER_QUAD(payload: ProcessorImplementationPayload) { + const shapeItem = payload.items.get(0) as ShapeItem); assert(shapeItem instanceof ShapeItem, "Input for painter is not a shape"); const colors: Array = [null, null, null, null]; - for (let i: any = 0; i < 4; ++i) { - const colorItem: any = (payload.items.get(i + 1) as ColorItem); + for (let i = 0; i < 4; ++i) { + const colorItem = payload.items.get(i + 1) as ColorItem); if (colorItem) { colors[i] = colorItem.color; } } - const colorizedDefinition: any = this.root.shapeDefinitionMgr.shapeActionPaintWith4Colors(shapeItem.definition, + const colorizedDefinition = this.root.shapeDefinitionMgr.shapeActionPaintWith4Colors(shapeItem.definition, colors as [ string, string, @@ -424,34 +424,34 @@ export class ItemProcessorSystem extends GameSystemWithFilter { item: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(colorizedDefinition), }); } - process_READER(payload: ProcessorImplementationPayload): any { + process_READER(payload: ProcessorImplementationPayload) { // Pass through the item - const item: any = payload.items.get(0); + const item = payload.items.get(0); payload.outItems.push({ item, doNotTrack: true, }); // Track the item - const readerComp: any = payload.entity.components.BeltReader; + const readerComp = payload.entity.components.BeltReader; readerComp.lastItemTimes.push(this.root.time.now()); readerComp.lastItem = item; } - process_HUB(payload: ProcessorImplementationPayload): any { - const hubComponent: any = payload.entity.components.Hub; + process_HUB(payload: ProcessorImplementationPayload) { + const hubComponent = payload.entity.components.Hub; assert(hubComponent, "Hub item processor has no hub component"); // Hardcoded - for (let i: any = 0; i < payload.inputCount; ++i) { - const item: any = (payload.items.get(i) as ShapeItem); + for (let i = 0; i < payload.inputCount; ++i) { + const item = payload.items.get(i) as ShapeItem); if (!item) { continue; } this.root.hubGoals.handleDefinitionDelivered(item.definition); } } - process_GOAL(payload: ProcessorImplementationPayload): any { - const goalComp: any = payload.entity.components.GoalAcceptor; - const item: any = payload.items.get(0); - const now: any = this.root.time.now(); + process_GOAL(payload: ProcessorImplementationPayload) { + const goalComp = payload.entity.components.GoalAcceptor; + const item = payload.items.get(0); + const now = this.root.time.now(); if (goalComp.item && !item.equals(goalComp.item)) { goalComp.clearItems(); } diff --git a/src/ts/game/systems/item_processor_overlays.ts b/src/ts/game/systems/item_processor_overlays.ts index f896144e..1ef903de 100644 --- a/src/ts/game/systems/item_processor_overlays.ts +++ b/src/ts/game/systems/item_processor_overlays.ts @@ -16,18 +16,18 @@ export class ItemProcessorOverlaysSystem extends GameSystem { super(root); this.root.signals.gameFrameStarted.add(this.clearDrawnUids, this); } - clearDrawnUids(): any { + clearDrawnUids() { this.drawnUids.clear(); } - drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView): any { - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const processorComp: any = entity.components.ItemProcessor; - const filterComp: any = entity.components.Filter; + drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView) { + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const processorComp = entity.components.ItemProcessor; + const filterComp = entity.components.Filter; // Draw processor overlays if (processorComp) { - const requirement: any = processorComp.processingRequirement; + const requirement = processorComp.processingRequirement; if (!requirement && processorComp.type !== enumItemProcessorTypes.reader) { continue; } @@ -55,9 +55,9 @@ export class ItemProcessorOverlaysSystem extends GameSystem { } } } - drawReaderOverlays(parameters: import("../../core/draw_utils").DrawParameters, entity: Entity): any { - const staticComp: any = entity.components.StaticMapEntity; - const readerComp: any = entity.components.BeltReader; + drawReaderOverlays(parameters: import("../../core/draw_utils").DrawParameters, entity: Entity) { + const staticComp = entity.components.StaticMapEntity; + const readerComp = entity.components.BeltReader; this.readerOverlaySprite.drawCachedCentered(parameters, (staticComp.origin.x + 0.5) * globalConfig.tileSize, (staticComp.origin.y + 0.5) * globalConfig.tileSize, globalConfig.tileSize); parameters.context.fillStyle = "#333439"; parameters.context.textAlign = "center"; @@ -67,14 +67,14 @@ export class ItemProcessorOverlaysSystem extends GameSystem { } drawConnectedSlotRequirement(parameters: import("../../core/draw_utils").DrawParameters, entity: Entity, { drawIfFalse = true }: { drawIfFalse: boolean=; - }): any { - const staticComp: any = entity.components.StaticMapEntity; - const pinsComp: any = entity.components.WiredPins; - let anySlotConnected: any = false; + }) { + const staticComp = entity.components.StaticMapEntity; + const pinsComp = entity.components.WiredPins; + let anySlotConnected = false; // Check if any slot has a value - for (let i: any = 0; i < pinsComp.slots.length; ++i) { - const slot: any = pinsComp.slots[i]; - const network: any = slot.linkedNetwork; + for (let i = 0; i < pinsComp.slots.length; ++i) { + const slot = pinsComp.slots[i]; + const network = slot.linkedNetwork; if (network && network.hasValue()) { anySlotConnected = true; if (isTruthyItem(network.currentValue) || !drawIfFalse) { @@ -83,9 +83,9 @@ export class ItemProcessorOverlaysSystem extends GameSystem { } } } - const pulse: any = smoothPulse(this.root.time.now()); + const pulse = smoothPulse(this.root.time.now()); parameters.context.globalAlpha = 0.6 + 0.4 * pulse; - const sprite: any = anySlotConnected ? this.spriteDisabled : this.spriteDisconnected; + const sprite = anySlotConnected ? this.spriteDisabled : this.spriteDisconnected; sprite.drawCachedCentered(parameters, (staticComp.origin.x + 0.5) * globalConfig.tileSize, (staticComp.origin.y + 0.5) * globalConfig.tileSize, globalConfig.tileSize * (0.7 + 0.2 * pulse)); parameters.context.globalAlpha = 1; } diff --git a/src/ts/game/systems/item_producer.ts b/src/ts/game/systems/item_producer.ts index e1ba47ca..08ae2012 100644 --- a/src/ts/game/systems/item_producer.ts +++ b/src/ts/game/systems/item_producer.ts @@ -6,16 +6,16 @@ export class ItemProducerSystem extends GameSystemWithFilter { constructor(root) { super(root, [ItemProducerComponent]); } - update(): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const ejectorComp: any = entity.components.ItemEjector; - const pinsComp: any = entity.components.WiredPins; + update() { + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const ejectorComp = entity.components.ItemEjector; + const pinsComp = entity.components.WiredPins; if (!pinsComp) { continue; } - const pin: any = pinsComp.slots[0]; - const network: any = pin.linkedNetwork; + const pin = pinsComp.slots[0]; + const network = pin.linkedNetwork; if (!network || !network.hasValue()) { continue; } diff --git a/src/ts/game/systems/lever.ts b/src/ts/game/systems/lever.ts index f297394a..1dd5d273 100644 --- a/src/ts/game/systems/lever.ts +++ b/src/ts/game/systems/lever.ts @@ -10,11 +10,11 @@ export class LeverSystem extends GameSystemWithFilter { constructor(root) { super(root, [LeverComponent]); } - update(): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const leverComp: any = entity.components.Lever; - const pinsComp: any = entity.components.WiredPins; + update() { + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const leverComp = entity.components.Lever; + const pinsComp = entity.components.WiredPins; // Simply sync the status to the first slot pinsComp.slots[0].value = leverComp.toggled ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON; } @@ -22,13 +22,13 @@ export class LeverSystem extends GameSystemWithFilter { /** * Draws a given chunk */ - drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView): any { - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const leverComp: any = entity.components.Lever; + drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView) { + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const leverComp = entity.components.Lever; if (leverComp) { - const sprite: any = leverComp.toggled ? this.spriteOn : this.spriteOff; + const sprite = leverComp.toggled ? this.spriteOn : this.spriteOff; entity.components.StaticMapEntity.drawSpriteOnBoundsClipped(parameters, sprite); } } diff --git a/src/ts/game/systems/logic_gate.ts b/src/ts/game/systems/logic_gate.ts index 47a47b39..040aacac 100644 --- a/src/ts/game/systems/logic_gate.ts +++ b/src/ts/game/systems/logic_gate.ts @@ -26,21 +26,21 @@ export class LogicGateSystem extends GameSystemWithFilter { constructor(root) { super(root, [LogicGateComponent]); } - update(): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const logicComp: any = entity.components.LogicGate; - const slotComp: any = entity.components.WiredPins; - const slotValues: any = []; + update() { + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const logicComp = entity.components.LogicGate; + const slotComp = entity.components.WiredPins; + const slotValues = []; // Store if any conflict was found - let anyConflict: any = false; + let anyConflict = false; // Gather inputs from all connected networks - for (let i: any = 0; i < slotComp.slots.length; ++i) { - const slot: any = slotComp.slots[i]; + for (let i = 0; i < slotComp.slots.length; ++i) { + const slot = slotComp.slots[i]; if (slot.type !== enumPinSlotType.logicalAcceptor) { continue; } - const network: any = slot.linkedNetwork; + const network = slot.linkedNetwork; if (network) { if (network.valueConflict) { anyConflict = true; @@ -54,8 +54,8 @@ export class LogicGateSystem extends GameSystemWithFilter { } // Handle conflicts if (anyConflict) { - for (let i: any = 0; i < slotComp.slots.length; ++i) { - const slot: any = slotComp.slots[i]; + for (let i = 0; i < slotComp.slots.length; ++i) { + const slot = slotComp.slots[i]; if (slot.type !== enumPinSlotType.logicalEjector) { continue; } @@ -64,11 +64,11 @@ export class LogicGateSystem extends GameSystemWithFilter { continue; } // Compute actual result - const result: any = this.boundOperations[logicComp.type](slotValues); + const result = this.boundOperations[logicComp.type](slotValues); if (Array.isArray(result)) { - let resultIndex: any = 0; - for (let i: any = 0; i < slotComp.slots.length; ++i) { - const slot: any = slotComp.slots[i]; + let resultIndex = 0; + for (let i = 0; i < slotComp.slots.length; ++i) { + const slot = slotComp.slots[i]; if (slot.type !== enumPinSlotType.logicalEjector) { continue; } @@ -121,8 +121,8 @@ export class LogicGateSystem extends GameSystemWithFilter { */ compute_IF(parameters: Array): BaseItem { assert(parameters.length === 2, "bad parameter count for IF"); - const flag: any = parameters[0]; - const value: any = parameters[1]; + const flag = parameters[0]; + const value = parameters[1]; // pass through item if (isTruthyItem(flag)) { return value; @@ -133,13 +133,13 @@ export class LogicGateSystem extends GameSystemWithFilter { * {} */ compute_ROTATE(parameters: Array): BaseItem { - const item: any = parameters[0]; + const item = parameters[0]; if (!item || item.getItemType() !== "shape") { // Not a shape return null; } - const definition: any = (item as ShapeItem).definition; - const rotatedDefinitionCW: any = this.root.shapeDefinitionMgr.shapeActionRotateCW(definition); + const definition = item as ShapeItem).definition; + const rotatedDefinitionCW = this.root.shapeDefinitionMgr.shapeActionRotateCW(definition); return this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinitionCW); } /** @@ -149,21 +149,21 @@ export class LogicGateSystem extends GameSystemWithFilter { BaseItem, BaseItem ] { - const item: any = parameters[0]; + const item = parameters[0]; if (!item || item.getItemType() !== "shape") { // Not a shape return [null, null]; } - const definition: any = (item as ShapeItem).definition; - const lowerLayer: any = (definition.layers[0] as import("../shape_definition").ShapeLayer); + const definition = item as ShapeItem).definition; + const lowerLayer = definition.layers[0] as import("../shape_definition").ShapeLayer); if (!lowerLayer) { return [null, null]; } - const topRightContent: any = lowerLayer[0]; + const topRightContent = lowerLayer[0]; if (!topRightContent || topRightContent.subShape === null) { return [null, null]; } - const newDefinition: any = new ShapeDefinition({ + const newDefinition = new ShapeDefinition({ layers: [ [ { subShape: topRightContent.subShape, color: enumColors.uncolored }, @@ -185,13 +185,13 @@ export class LogicGateSystem extends GameSystemWithFilter { BaseItem, BaseItem ] { - const item: any = parameters[0]; + const item = parameters[0]; if (!item || item.getItemType() !== "shape") { // Not a shape return [null, null]; } - const definition: any = (item as ShapeItem).definition; - const result: any = this.root.shapeDefinitionMgr.shapeActionCutHalf(definition); + const definition = item as ShapeItem).definition; + const result = this.root.shapeDefinitionMgr.shapeActionCutHalf(definition); return [ result[0].isEntirelyEmpty() ? null @@ -208,18 +208,18 @@ export class LogicGateSystem extends GameSystemWithFilter { BaseItem, BaseItem ] { - const item: any = parameters[0]; + const item = parameters[0]; if (!item || item.getItemType() !== "shape") { // Not a shape return [null, null]; } - const definition: any = (item as ShapeItem).definition; - const layers: any = (definition.layers as Array); - const upperLayerDefinition: any = new ShapeDefinition({ + const definition = item as ShapeItem).definition; + const layers = definition.layers as Array); + const upperLayerDefinition = new ShapeDefinition({ layers: [layers[layers.length - 1]], }); - const lowerLayers: any = layers.slice(0, layers.length - 1); - const lowerLayerDefinition: any = lowerLayers.length > 0 ? new ShapeDefinition({ layers: lowerLayers }) : null; + const lowerLayers = layers.slice(0, layers.length - 1); + const lowerLayerDefinition = lowerLayers.length > 0 ? new ShapeDefinition({ layers: lowerLayers }) : null; return [ lowerLayerDefinition ? this.root.shapeDefinitionMgr.getShapeItemFromDefinition(lowerLayerDefinition) @@ -231,8 +231,8 @@ export class LogicGateSystem extends GameSystemWithFilter { * {} */ compute_STACKER(parameters: Array): BaseItem { - const lowerItem: any = parameters[0]; - const upperItem: any = parameters[1]; + const lowerItem = parameters[0]; + const upperItem = parameters[1]; if (!lowerItem || !upperItem) { // Empty return null; @@ -241,7 +241,7 @@ export class LogicGateSystem extends GameSystemWithFilter { // Bad type return null; } - const stackedShape: any = this.root.shapeDefinitionMgr.shapeActionStack( + const stackedShape = this.root.shapeDefinitionMgr.shapeActionStack( lowerItem as ShapeItem).definition, upperItem as ShapeItem).definition); return this.root.shapeDefinitionMgr.getShapeItemFromDefinition(stackedShape); @@ -250,8 +250,8 @@ export class LogicGateSystem extends GameSystemWithFilter { * {} */ compute_PAINTER(parameters: Array): BaseItem { - const shape: any = parameters[0]; - const color: any = parameters[1]; + const shape = parameters[0]; + const color = parameters[1]; if (!shape || !color) { // Empty return null; @@ -260,7 +260,7 @@ export class LogicGateSystem extends GameSystemWithFilter { // Bad type return null; } - const coloredShape: any = this.root.shapeDefinitionMgr.shapeActionPaintWith( + const coloredShape = this.root.shapeDefinitionMgr.shapeActionPaintWith( shape as ShapeItem).definition, color as ColorItem).color); return this.root.shapeDefinitionMgr.getShapeItemFromDefinition(coloredShape); @@ -269,8 +269,8 @@ export class LogicGateSystem extends GameSystemWithFilter { * {} */ compute_COMPARE(parameters: Array): BaseItem { - const itemA: any = parameters[0]; - const itemB: any = parameters[1]; + const itemA = parameters[0]; + const itemB = parameters[1]; if (!itemA || !itemB) { // Empty return null; diff --git a/src/ts/game/systems/map_resources.ts b/src/ts/game/systems/map_resources.ts index 0e367d68..ea86eb95 100644 --- a/src/ts/game/systems/map_resources.ts +++ b/src/ts/game/systems/map_resources.ts @@ -8,8 +8,8 @@ export class MapResourcesSystem extends GameSystem { /** * Draws the map resources */ - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { - const basicChunkBackground: any = this.root.buffers.getForKey({ + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { + const basicChunkBackground = this.root.buffers.getForKey({ key: "mapresourcebg", subKey: chunk.renderKey, w: globalConfig.mapChunkSize, @@ -32,33 +32,33 @@ export class MapResourcesSystem extends GameSystem { parameters.context.globalAlpha = 0.5; if (this.root.app.settings.getAllSettings().lowQualityMapResources) { // LOW QUALITY: Draw patch items only - for (let i: any = 0; i < chunk.patches.length; ++i) { - const patch: any = chunk.patches[i]; - const destX: any = chunk.x * globalConfig.mapChunkWorldSize + patch.pos.x * globalConfig.tileSize; - const destY: any = chunk.y * globalConfig.mapChunkWorldSize + patch.pos.y * globalConfig.tileSize; - const diameter: any = Math.min(80, 40 / parameters.zoomLevel); + for (let i = 0; i < chunk.patches.length; ++i) { + const patch = chunk.patches[i]; + const destX = chunk.x * globalConfig.mapChunkWorldSize + patch.pos.x * globalConfig.tileSize; + const destY = chunk.y * globalConfig.mapChunkWorldSize + patch.pos.y * globalConfig.tileSize; + const diameter = Math.min(80, 40 / parameters.zoomLevel); patch.item.drawItemCenteredClipped(destX, destY, parameters, diameter); } } else { // HIGH QUALITY: Draw all items - const layer: any = chunk.lowerLayer; - const layerEntities: any = chunk.contents; - for (let x: any = 0; x < globalConfig.mapChunkSize; ++x) { - const row: any = layer[x]; - const rowEntities: any = layerEntities[x]; - const worldX: any = (chunk.tileX + x) * globalConfig.tileSize; - for (let y: any = 0; y < globalConfig.mapChunkSize; ++y) { - const lowerItem: any = row[y]; - const entity: any = rowEntities[y]; + const layer = chunk.lowerLayer; + const layerEntities = chunk.contents; + for (let x = 0; x < globalConfig.mapChunkSize; ++x) { + const row = layer[x]; + const rowEntities = layerEntities[x]; + const worldX = (chunk.tileX + x) * globalConfig.tileSize; + for (let y = 0; y < globalConfig.mapChunkSize; ++y) { + const lowerItem = row[y]; + const entity = rowEntities[y]; if (entity) { // Don't draw if there is an entity above continue; } if (lowerItem) { - const worldY: any = (chunk.tileY + y) * globalConfig.tileSize; - const destX: any = worldX + globalConfig.halfTileSize; - const destY: any = worldY + globalConfig.halfTileSize; + const worldY = (chunk.tileY + y) * globalConfig.tileSize; + const destX = worldX + globalConfig.halfTileSize; + const destY = worldY + globalConfig.halfTileSize; lowerItem.drawItemCenteredClipped(destX, destY, parameters, globalConfig.defaultItemDiameter); } } @@ -66,7 +66,7 @@ export class MapResourcesSystem extends GameSystem { } parameters.context.globalAlpha = 1; } - generateChunkBackground(chunk: MapChunkView, canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number): any { + generateChunkBackground(chunk: MapChunkView, canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, w: number, h: number, dpi: number) { if (this.root.app.settings.getAllSettings().disableTileGrid) { // The map doesn't draw a background, so we have to context.fillStyle = THEME.map.background; @@ -76,11 +76,11 @@ export class MapResourcesSystem extends GameSystem { context.clearRect(0, 0, w, h); } context.globalAlpha = 0.5; - const layer: any = chunk.lowerLayer; - for (let x: any = 0; x < globalConfig.mapChunkSize; ++x) { - const row: any = layer[x]; - for (let y: any = 0; y < globalConfig.mapChunkSize; ++y) { - const item: any = row[y]; + const layer = chunk.lowerLayer; + for (let x = 0; x < globalConfig.mapChunkSize; ++x) { + const row = layer[x]; + for (let y = 0; y < globalConfig.mapChunkSize; ++y) { + const item = row[y]; if (item) { context.fillStyle = item.getBackgroundColorAsResource(); context.fillRect(x, y, 1, 1); diff --git a/src/ts/game/systems/miner.ts b/src/ts/game/systems/miner.ts index 15c192c6..2b9c7dcb 100644 --- a/src/ts/game/systems/miner.ts +++ b/src/ts/game/systems/miner.ts @@ -18,29 +18,29 @@ export class MinerSystem extends GameSystemWithFilter { /** * Called whenever an entity got changed */ - onEntityChanged(entity: Entity): any { - const minerComp: any = entity.components.Miner; + onEntityChanged(entity: Entity) { + const minerComp = entity.components.Miner; if (minerComp && minerComp.chainable) { // Miner component, need to recompute this.needsRecompute = true; } } - update(): any { - let miningSpeed: any = this.root.hubGoals.getMinerBaseSpeed(); + update() { + let miningSpeed = this.root.hubGoals.getMinerBaseSpeed(); if (G_IS_DEV && globalConfig.debug.instantMiners) { miningSpeed *= 100; } - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const minerComp: any = entity.components.Miner; + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const minerComp = entity.components.Miner; // Reset everything on recompute if (this.needsRecompute) { minerComp.cachedChainedMiner = null; } // Check if miner is above an actual tile if (!minerComp.cachedMinedItem) { - const staticComp: any = entity.components.StaticMapEntity; - const tileBelow: any = this.root.map.getLowerLayerContentXY(staticComp.origin.x, staticComp.origin.y); + const staticComp = entity.components.StaticMapEntity; + const tileBelow = this.root.map.getLowerLayerContentXY(staticComp.origin.x, staticComp.origin.y); if (!tileBelow) { continue; } @@ -53,11 +53,11 @@ export class MinerSystem extends GameSystemWithFilter { continue; } } - const mineDuration: any = 1 / miningSpeed; - const timeSinceMine: any = this.root.time.now() - minerComp.lastMiningTime; + const mineDuration = 1 / miningSpeed; + const timeSinceMine = this.root.time.now() - minerComp.lastMiningTime; if (timeSinceMine > mineDuration) { // Store how much we overflowed - const buffer: any = Math.min(timeSinceMine - mineDuration, this.root.dynamicTickrate.deltaSeconds); + const buffer = Math.min(timeSinceMine - mineDuration, this.root.dynamicTickrate.deltaSeconds); if (this.tryPerformMinerEject(entity, minerComp.cachedMinedItem)) { // Analytics hook this.root.signals.itemProduced.dispatch(minerComp.cachedMinedItem); @@ -74,23 +74,23 @@ export class MinerSystem extends GameSystemWithFilter { * {} The chained entity or null if not found */ findChainedMiner(entity: Entity): Entity | false { - const ejectComp: any = entity.components.ItemEjector; - const staticComp: any = entity.components.StaticMapEntity; - const contentsBelow: any = this.root.map.getLowerLayerContentXY(staticComp.origin.x, staticComp.origin.y); + const ejectComp = entity.components.ItemEjector; + const staticComp = entity.components.StaticMapEntity; + const contentsBelow = this.root.map.getLowerLayerContentXY(staticComp.origin.x, staticComp.origin.y); if (!contentsBelow) { // This miner has no contents return null; } - const ejectingSlot: any = ejectComp.slots[0]; - const ejectingPos: any = staticComp.localTileToWorld(ejectingSlot.pos); - const ejectingDirection: any = staticComp.localDirectionToWorld(ejectingSlot.direction); - const targetTile: any = ejectingPos.add(enumDirectionToVector[ejectingDirection]); - const targetContents: any = this.root.map.getTileContent(targetTile, "regular"); + const ejectingSlot = ejectComp.slots[0]; + const ejectingPos = staticComp.localTileToWorld(ejectingSlot.pos); + const ejectingDirection = staticComp.localDirectionToWorld(ejectingSlot.direction); + const targetTile = ejectingPos.add(enumDirectionToVector[ejectingDirection]); + const targetContents = this.root.map.getTileContent(targetTile, "regular"); // Check if we are connected to another miner and thus do not eject directly if (targetContents) { - const targetMinerComp: any = targetContents.components.Miner; + const targetMinerComp = targetContents.components.Miner; if (targetMinerComp && targetMinerComp.chainable) { - const targetLowerLayer: any = this.root.map.getLowerLayerContentXY(targetTile.x, targetTile.y); + const targetLowerLayer = this.root.map.getLowerLayerContentXY(targetTile.x, targetTile.y); if (targetLowerLayer) { return targetContents; } @@ -98,19 +98,19 @@ export class MinerSystem extends GameSystemWithFilter { } return false; } - tryPerformMinerEject(entity: Entity, item: BaseItem): any { - const minerComp: any = entity.components.Miner; - const ejectComp: any = entity.components.ItemEjector; + tryPerformMinerEject(entity: Entity, item: BaseItem) { + const minerComp = entity.components.Miner; + const ejectComp = entity.components.ItemEjector; // Check if we are a chained miner if (minerComp.chainable) { - const targetEntity: any = minerComp.cachedChainedMiner; + const targetEntity = minerComp.cachedChainedMiner; // Check if the cache has to get recomputed if (targetEntity === null) { minerComp.cachedChainedMiner = this.findChainedMiner(entity); } // Check if we now have a target if (targetEntity) { - const targetMinerComp: any = targetEntity.components.Miner; + const targetMinerComp = targetEntity.components.Miner; if (targetMinerComp.tryAcceptChainedItem(item)) { return true; } @@ -125,24 +125,24 @@ export class MinerSystem extends GameSystemWithFilter { } return false; } - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const minerComp: any = entity.components.Miner; + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const minerComp = entity.components.Miner; if (!minerComp) { continue; } - const staticComp: any = entity.components.StaticMapEntity; + const staticComp = entity.components.StaticMapEntity; if (!minerComp.cachedMinedItem) { continue; } // Draw the item background - this is to hide the ejected item animation from // the item ejector - const padding: any = 3; - const destX: any = staticComp.origin.x * globalConfig.tileSize + padding; - const destY: any = staticComp.origin.y * globalConfig.tileSize + padding; - const dimensions: any = globalConfig.tileSize - 2 * padding; + const padding = 3; + const destX = staticComp.origin.x * globalConfig.tileSize + padding; + const destY = staticComp.origin.y * globalConfig.tileSize + padding; + const dimensions = globalConfig.tileSize - 2 * padding; if (parameters.visibleRect.containsRect4Params(destX, destY, dimensions, dimensions)) { parameters.context.fillStyle = minerComp.cachedMinedItem.getBackgroundColorAsResource(); parameters.context.fillRect(destX, destY, dimensions, dimensions); diff --git a/src/ts/game/systems/static_map_entity.ts b/src/ts/game/systems/static_map_entity.ts index 398dce77..18824925 100644 --- a/src/ts/game/systems/static_map_entity.ts +++ b/src/ts/game/systems/static_map_entity.ts @@ -12,21 +12,21 @@ export class StaticMapEntitySystem extends GameSystem { /** * Clears the uid list when a new frame started */ - clearUidList(): any { + clearUidList() { this.drawnUids.clear(); } /** * Draws the static entities */ - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { if (G_IS_DEV && globalConfig.debug.doNotRenderStatics) { return; } - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const staticComp: any = entity.components.StaticMapEntity; - const sprite: any = staticComp.getSprite(); + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const staticComp = entity.components.StaticMapEntity; + const sprite = staticComp.getSprite(); if (sprite) { // Avoid drawing an entity twice which has been drawn for // another chunk already @@ -41,22 +41,22 @@ export class StaticMapEntitySystem extends GameSystem { /** * Draws the static wire entities */ - drawWiresChunk(parameters: DrawParameters, chunk: MapChunkView): any { + drawWiresChunk(parameters: DrawParameters, chunk: MapChunkView) { if (G_IS_DEV && globalConfig.debug.doNotRenderStatics) { return; } - const drawnUids: any = new Set(); - const contents: any = chunk.wireContents; - for (let y: any = 0; y < globalConfig.mapChunkSize; ++y) { - for (let x: any = 0; x < globalConfig.mapChunkSize; ++x) { - const entity: any = contents[x][y]; + const drawnUids = new Set(); + const contents = chunk.wireContents; + for (let y = 0; y < globalConfig.mapChunkSize; ++y) { + for (let x = 0; x < globalConfig.mapChunkSize; ++x) { + const entity = contents[x][y]; if (entity) { if (drawnUids.has(entity.uid)) { continue; } drawnUids.add(entity.uid); - const staticComp: any = entity.components.StaticMapEntity; - const sprite: any = staticComp.getSprite(); + const staticComp = entity.components.StaticMapEntity; + const sprite = staticComp.getSprite(); if (sprite) { staticComp.drawSpriteOnBoundsClipped(parameters, sprite, 2); } diff --git a/src/ts/game/systems/storage.ts b/src/ts/game/systems/storage.ts index 3712596e..72dba583 100644 --- a/src/ts/game/systems/storage.ts +++ b/src/ts/game/systems/storage.ts @@ -13,18 +13,18 @@ export class StorageSystem extends GameSystemWithFilter { super(root, [StorageComponent]); this.root.signals.gameFrameStarted.add(this.clearDrawnUids, this); } - clearDrawnUids(): any { + clearDrawnUids() { this.drawnUids.clear(); } - update(): any { - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const storageComp: any = entity.components.Storage; - const pinsComp: any = entity.components.WiredPins; + update() { + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const storageComp = entity.components.Storage; + const pinsComp = entity.components.WiredPins; // Eject from storage if (storageComp.storedItem && storageComp.storedCount > 0) { - const ejectorComp: any = entity.components.ItemEjector; - const nextSlot: any = ejectorComp.getFirstFreeSlot(); + const ejectorComp = entity.components.ItemEjector; + const nextSlot = ejectorComp.getFirstFreeSlot(); if (nextSlot !== null) { if (ejectorComp.tryEject(nextSlot, storageComp.storedItem)) { storageComp.storedCount--; @@ -34,7 +34,7 @@ export class StorageSystem extends GameSystemWithFilter { } } } - let targetAlpha: any = storageComp.storedCount > 0 ? 1 : 0; + let targetAlpha = storageComp.storedCount > 0 ? 1 : 0; storageComp.overlayOpacity = lerp(storageComp.overlayOpacity, targetAlpha, 0.05); // a wired pins component is not guaranteed, but if its there, set the value if (pinsComp) { @@ -45,15 +45,15 @@ export class StorageSystem extends GameSystemWithFilter { } } } - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { - const contents: any = chunk.containedEntitiesByLayer.regular; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const storageComp: any = entity.components.Storage; + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { + const contents = chunk.containedEntitiesByLayer.regular; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const storageComp = entity.components.Storage; if (!storageComp) { continue; } - const storedItem: any = storageComp.storedItem; + const storedItem = storageComp.storedItem; if (!storedItem) { continue; } @@ -61,10 +61,10 @@ export class StorageSystem extends GameSystemWithFilter { continue; } this.drawnUids.add(entity.uid); - const staticComp: any = entity.components.StaticMapEntity; - const context: any = parameters.context; + const staticComp = entity.components.StaticMapEntity; + const context = parameters.context; context.globalAlpha = storageComp.overlayOpacity; - const center: any = staticComp.getTileSpaceBounds().getCenter().toWorldSpace(); + const center = staticComp.getTileSpaceBounds().getCenter().toWorldSpace(); storedItem.drawItemCenteredClipped(center.x, center.y, parameters, 30); this.storageOverlaySprite.drawCached(parameters, center.x - 15, center.y + 15, 30, 15); if (parameters.visibleRect.containsCircle(center.x, center.y + 25, 20)) { diff --git a/src/ts/game/systems/underground_belt.ts b/src/ts/game/systems/underground_belt.ts index 0099fb46..d24f7580 100644 --- a/src/ts/game/systems/underground_belt.ts +++ b/src/ts/game/systems/underground_belt.ts @@ -8,7 +8,7 @@ import { enumAngleToDirection, enumDirection, enumDirectionToAngle, enumDirectio import { enumUndergroundBeltMode, UndergroundBeltComponent } from "../components/underground_belt"; import { Entity } from "../entity"; import { GameSystemWithFilter } from "../game_system_with_filter"; -const logger: any = createLogger("tunnels"); +const logger = createLogger("tunnels"); export class UndergroundBeltSystem extends GameSystemWithFilter { public beltSprites = { [enumUndergroundBeltMode.sender]: Loader.getSprite("sprites/buildings/underground_belt_entry.png"), @@ -30,32 +30,32 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { /** * Callback when an entity got placed, used to remove belts between underground belts */ - onEntityManuallyPlaced(entity: Entity): any { + onEntityManuallyPlaced(entity: Entity) { if (!this.root.app.settings.getAllSettings().enableTunnelSmartplace) { // Smart-place disabled return; } - const undergroundComp: any = entity.components.UndergroundBelt; + const undergroundComp = entity.components.UndergroundBelt; if (undergroundComp && undergroundComp.mode === enumUndergroundBeltMode.receiver) { - const staticComp: any = entity.components.StaticMapEntity; - const tile: any = staticComp.origin; - const direction: any = enumAngleToDirection[staticComp.rotation]; - const inverseDirection: any = enumInvertedDirections[direction]; - const offset: any = enumDirectionToVector[inverseDirection]; - let currentPos: any = tile.copy(); - const tier: any = undergroundComp.tier; - const range: any = globalConfig.undergroundBeltMaxTilesByTier[tier]; + const staticComp = entity.components.StaticMapEntity; + const tile = staticComp.origin; + const direction = enumAngleToDirection[staticComp.rotation]; + const inverseDirection = enumInvertedDirections[direction]; + const offset = enumDirectionToVector[inverseDirection]; + let currentPos = tile.copy(); + const tier = undergroundComp.tier; + const range = globalConfig.undergroundBeltMaxTilesByTier[tier]; // FIND ENTRANCE // Search for the entrance which is farthest apart (this is why we can't reuse logic here) - let matchingEntrance: any = null; - for (let i: any = 0; i < range; ++i) { + let matchingEntrance = null; + for (let i = 0; i < range; ++i) { currentPos.addInplace(offset); - const contents: any = this.root.map.getTileContent(currentPos, entity.layer); + const contents = this.root.map.getTileContent(currentPos, entity.layer); if (!contents) { continue; } - const contentsUndergroundComp: any = contents.components.UndergroundBelt; - const contentsStaticComp: any = contents.components.StaticMapEntity; + const contentsUndergroundComp = contents.components.UndergroundBelt; + const contentsStaticComp = contents.components.StaticMapEntity; if (contentsUndergroundComp && contentsUndergroundComp.tier === undergroundComp.tier && contentsUndergroundComp.mode === enumUndergroundBeltMode.sender && @@ -74,16 +74,16 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { // Remove any belts between entrance and exit which have the same direction, // but only if they *all* have the right direction currentPos = tile.copy(); - let allBeltsMatch: any = true; - for (let i: any = 0; i < matchingEntrance.range; ++i) { + let allBeltsMatch = true; + for (let i = 0; i < matchingEntrance.range; ++i) { currentPos.addInplace(offset); - const contents: any = this.root.map.getTileContent(currentPos, entity.layer); + const contents = this.root.map.getTileContent(currentPos, entity.layer); if (!contents) { allBeltsMatch = false; break; } - const contentsStaticComp: any = contents.components.StaticMapEntity; - const contentsBeltComp: any = contents.components.Belt; + const contentsStaticComp = contents.components.StaticMapEntity; + const contentsBeltComp = contents.components.Belt; if (!contentsBeltComp) { allBeltsMatch = false; break; @@ -98,9 +98,9 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { currentPos = tile.copy(); if (allBeltsMatch) { // All belts between this are obsolete, so drop them - for (let i: any = 0; i < matchingEntrance.range; ++i) { + for (let i = 0; i < matchingEntrance.range; ++i) { currentPos.addInplace(offset); - const contents: any = this.root.map.getTileContent(currentPos, entity.layer); + const contents = this.root.map.getTileContent(currentPos, entity.layer); assert(contents, "Invalid smart underground belt logic"); this.root.logic.tryDeleteBuilding(contents); } @@ -108,16 +108,16 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { // REMOVE OBSOLETE TUNNELS // Remove any double tunnels, by checking the tile plus the tile above currentPos = tile.copy().add(offset); - for (let i: any = 0; i < matchingEntrance.range - 1; ++i) { - const posBefore: any = currentPos.copy(); + for (let i = 0; i < matchingEntrance.range - 1; ++i) { + const posBefore = currentPos.copy(); currentPos.addInplace(offset); - const entityBefore: any = this.root.map.getTileContent(posBefore, entity.layer); - const entityAfter: any = this.root.map.getTileContent(currentPos, entity.layer); + const entityBefore = this.root.map.getTileContent(posBefore, entity.layer); + const entityAfter = this.root.map.getTileContent(currentPos, entity.layer); if (!entityBefore || !entityAfter) { continue; } - const undergroundBefore: any = entityBefore.components.UndergroundBelt; - const undergroundAfter: any = entityAfter.components.UndergroundBelt; + const undergroundBefore = entityBefore.components.UndergroundBelt; + const undergroundAfter = entityAfter.components.UndergroundBelt; if (!undergroundBefore || !undergroundAfter) { // Not an underground belt continue; @@ -136,8 +136,8 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { continue; } // Check rotations - const staticBefore: any = entityBefore.components.StaticMapEntity; - const staticAfter: any = entityAfter.components.StaticMapEntity; + const staticBefore = entityBefore.components.StaticMapEntity; + const staticAfter = entityAfter.components.StaticMapEntity; if (enumAngleToDirection[staticBefore.rotation] !== direction || enumAngleToDirection[staticAfter.rotation] !== direction) { // Wrong rotation @@ -152,13 +152,13 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { /** * Recomputes the cache in the given area, invalidating all entries there */ - recomputeArea(area: Rectangle): any { - for (let x: any = area.x; x < area.right(); ++x) { - for (let y: any = area.y; y < area.bottom(); ++y) { - const entities: any = this.root.map.getLayersContentsMultipleXY(x, y); - for (let i: any = 0; i < entities.length; ++i) { - const entity: any = entities[i]; - const undergroundComp: any = entity.components.UndergroundBelt; + recomputeArea(area: Rectangle) { + for (let x = area.x; x < area.right(); ++x) { + for (let y = area.y; y < area.bottom(); ++y) { + const entities = this.root.map.getLayersContentsMultipleXY(x, y); + for (let i = 0; i < entities.length; ++i) { + const entity = entities[i]; + const undergroundComp = entity.components.UndergroundBelt; if (!undergroundComp) { continue; } @@ -167,13 +167,13 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { } } } - update(): any { + update() { this.staleAreaWatcher.update(); - const sender: any = enumUndergroundBeltMode.sender; - const now: any = this.root.time.now(); - for (let i: any = 0; i < this.allEntities.length; ++i) { - const entity: any = this.allEntities[i]; - const undergroundComp: any = entity.components.UndergroundBelt; + const sender = enumUndergroundBeltMode.sender; + const now = this.root.time.now(); + for (let i = 0; i < this.allEntities.length; ++i) { + const entity = this.allEntities[i]; + const undergroundComp = entity.components.UndergroundBelt; if (undergroundComp.mode === sender) { this.handleSender(entity); } @@ -187,26 +187,26 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { * {} */ findRecieverForSender(entity: Entity): import("../components/underground_belt").LinkedUndergroundBelt { - const staticComp: any = entity.components.StaticMapEntity; - const undergroundComp: any = entity.components.UndergroundBelt; - const searchDirection: any = staticComp.localDirectionToWorld(enumDirection.top); - const searchVector: any = enumDirectionToVector[searchDirection]; - const targetRotation: any = enumDirectionToAngle[searchDirection]; - let currentTile: any = staticComp.origin; + const staticComp = entity.components.StaticMapEntity; + const undergroundComp = entity.components.UndergroundBelt; + const searchDirection = staticComp.localDirectionToWorld(enumDirection.top); + const searchVector = enumDirectionToVector[searchDirection]; + const targetRotation = enumDirectionToAngle[searchDirection]; + let currentTile = staticComp.origin; // Search in the direction of the tunnel - for (let searchOffset: any = 0; searchOffset < globalConfig.undergroundBeltMaxTilesByTier[undergroundComp.tier]; ++searchOffset) { + for (let searchOffset = 0; searchOffset < globalConfig.undergroundBeltMaxTilesByTier[undergroundComp.tier]; ++searchOffset) { currentTile = currentTile.add(searchVector); - const potentialReceiver: any = this.root.map.getTileContent(currentTile, "regular"); + const potentialReceiver = this.root.map.getTileContent(currentTile, "regular"); if (!potentialReceiver) { // Empty tile continue; } - const receiverUndergroundComp: any = potentialReceiver.components.UndergroundBelt; + const receiverUndergroundComp = potentialReceiver.components.UndergroundBelt; if (!receiverUndergroundComp || receiverUndergroundComp.tier !== undergroundComp.tier) { // Not a tunnel, or not on the same tier continue; } - const receiverStaticComp: any = potentialReceiver.components.StaticMapEntity; + const receiverStaticComp = potentialReceiver.components.StaticMapEntity; if (receiverStaticComp.rotation !== targetRotation) { // Wrong rotation continue; @@ -220,10 +220,10 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { // None found return { entity: null, distance: 0 }; } - handleSender(entity: Entity): any { - const undergroundComp: any = entity.components.UndergroundBelt; + handleSender(entity: Entity) { + const undergroundComp = entity.components.UndergroundBelt; // Find the current receiver - let cacheEntry: any = undergroundComp.cachedLinkedEntity; + let cacheEntry = undergroundComp.cachedLinkedEntity; if (!cacheEntry) { // Need to recompute cache cacheEntry = undergroundComp.cachedLinkedEntity = this.findRecieverForSender(entity); @@ -233,7 +233,7 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { return; } // Check if we have any items to eject - const nextItemAndDuration: any = undergroundComp.pendingItems[0]; + const nextItemAndDuration = undergroundComp.pendingItems[0]; if (nextItemAndDuration) { assert(undergroundComp.pendingItems.length === 1, "more than 1 pending"); // Check if the receiver can accept it @@ -243,14 +243,14 @@ export class UndergroundBeltSystem extends GameSystemWithFilter { } } } - handleReceiver(entity: Entity, now: number): any { - const undergroundComp: any = entity.components.UndergroundBelt; + handleReceiver(entity: Entity, now: number) { + const undergroundComp = entity.components.UndergroundBelt; // Try to eject items, we only check the first one because it is sorted by remaining time - const nextItemAndDuration: any = undergroundComp.pendingItems[0]; + const nextItemAndDuration = undergroundComp.pendingItems[0]; if (nextItemAndDuration) { if (now > nextItemAndDuration[1]) { - const ejectorComp: any = entity.components.ItemEjector; - const nextSlotIndex: any = ejectorComp.getFirstFreeSlot(); + const ejectorComp = entity.components.ItemEjector; + const nextSlotIndex = ejectorComp.getFirstFreeSlot(); if (nextSlotIndex !== null) { if (ejectorComp.tryEject(nextSlotIndex, nextItemAndDuration[0])) { undergroundComp.pendingItems.shift(); diff --git a/src/ts/game/systems/wire.ts b/src/ts/game/systems/wire.ts index 79db6136..2dd09098 100644 --- a/src/ts/game/systems/wire.ts +++ b/src/ts/game/systems/wire.ts @@ -19,9 +19,9 @@ import { GameSystem } from "../game_system"; import { GameSystemWithFilter } from "../game_system_with_filter"; import { isTruthyItem } from "../items/boolean_item"; import { MapChunkView } from "../map_chunk_view"; -const logger: any = createLogger("wires"); -let networkUidCounter: any = 0; -const VERBOSE_WIRES: any = G_IS_DEV && false; +const logger = createLogger("wires"); +let networkUidCounter = 0; +const VERBOSE_WIRES = G_IS_DEV && false; export class WireNetwork { public providers: Array<{ entity: Entity; @@ -66,11 +66,11 @@ export class WireSystem extends GameSystem { constructor(root) { super(root); - const variants: any = ["conflict", ...Object.keys(enumWireVariant)]; - for (let i: any = 0; i < variants.length; ++i) { - const wireVariant: any = variants[i]; - const sprites: any = {}; - for (const wireType: any in enumWireType) { + const variants = ["conflict", ...Object.keys(enumWireVariant)]; + for (let i = 0; i < variants.length; ++i) { + const wireVariant = variants[i]; + const sprites = {}; + for (const wireType in enumWireType) { sprites[wireType] = Loader.getSprite("sprites/wires/sets/" + wireVariant + "_" + wireType + ".png"); } this.wireSprites[wireVariant] = sprites; @@ -84,7 +84,7 @@ export class WireSystem extends GameSystem { /** * Invalidates the wires network if the given entity is relevant for it */ - queueRecomputeIfWire(entity: Entity): any { + queueRecomputeIfWire(entity: Entity) { if (!this.root.gameInitialized) { return; } @@ -96,24 +96,24 @@ export class WireSystem extends GameSystem { /** * Recomputes the whole wires network */ - recomputeWiresNetwork(): any { + recomputeWiresNetwork() { this.needsRecompute = false; logger.log("Recomputing wires network"); this.networks = []; - const wireEntities: any = this.root.entityMgr.getAllWithComponent(WireComponent); - const tunnelEntities: any = this.root.entityMgr.getAllWithComponent(WireTunnelComponent); - const pinEntities: any = this.root.entityMgr.getAllWithComponent(WiredPinsComponent); + const wireEntities = this.root.entityMgr.getAllWithComponent(WireComponent); + const tunnelEntities = this.root.entityMgr.getAllWithComponent(WireTunnelComponent); + const pinEntities = this.root.entityMgr.getAllWithComponent(WiredPinsComponent); // Clear all network references, but not on the first update since that's the deserializing one if (!this.isFirstRecompute) { - for (let i: any = 0; i < wireEntities.length; ++i) { + for (let i = 0; i < wireEntities.length; ++i) { wireEntities[i].components.Wire.linkedNetwork = null; } - for (let i: any = 0; i < tunnelEntities.length; ++i) { + for (let i = 0; i < tunnelEntities.length; ++i) { tunnelEntities[i].components.WireTunnel.linkedNetworks = []; } - for (let i: any = 0; i < pinEntities.length; ++i) { - const slots: any = pinEntities[i].components.WiredPins.slots; - for (let k: any = 0; k < slots.length; ++k) { + for (let i = 0; i < pinEntities.length; ++i) { + const slots = pinEntities[i].components.WiredPins.slots; + for (let k = 0; k < slots.length; ++k) { slots[k].linkedNetwork = null; } } @@ -124,11 +124,11 @@ export class WireSystem extends GameSystem { } VERBOSE_WIRES && logger.log("Recomputing slots"); // Iterate over all ejector slots - for (let i: any = 0; i < pinEntities.length; ++i) { - const entity: any = pinEntities[i]; - const slots: any = entity.components.WiredPins.slots; - for (let k: any = 0; k < slots.length; ++k) { - const slot: any = slots[k]; + for (let i = 0; i < pinEntities.length; ++i) { + const entity = pinEntities[i]; + const slots = entity.components.WiredPins.slots; + for (let k = 0; k < slots.length; ++k) { + const slot = slots[k]; // Ejectors are computed directly, acceptors are just set if (slot.type === enumPinSlotType.logicalEjector && !slot.linkedNetwork) { this.findNetworkForEjector(entity, slot); @@ -139,11 +139,11 @@ export class WireSystem extends GameSystem { /** * Finds the network for the given slot */ - findNetworkForEjector(initialEntity: Entity, slot: import("../components/wired_pins").WirePinSlot): any { - let currentNetwork: any = new WireNetwork(); + findNetworkForEjector(initialEntity: Entity, slot: import("../components/wired_pins").WirePinSlot) { + let currentNetwork = new WireNetwork(); VERBOSE_WIRES && logger.log("Finding network for entity", initialEntity.uid, initialEntity.components.StaticMapEntity.origin.toString(), "(nw-id:", currentNetwork.uid, ")"); - const entitiesToVisit: any = [ + const entitiesToVisit = [ { entity: initialEntity, slot, @@ -155,14 +155,14 @@ export class WireSystem extends GameSystem { */ let variantMask: enumWireVariant = null; while (entitiesToVisit.length > 0) { - const nextData: any = entitiesToVisit.pop(); - const nextEntity: any = nextData.entity; - const wireComp: any = nextEntity.components.Wire; - const staticComp: any = nextEntity.components.StaticMapEntity; + const nextData = entitiesToVisit.pop(); + const nextEntity = nextData.entity; + const wireComp = nextEntity.components.Wire; + const staticComp = nextEntity.components.StaticMapEntity; VERBOSE_WIRES && logger.log("Visiting", staticComp.origin.toString(), "(", nextEntity.uid, ")"); // Where to search for neighbours - let newSearchDirections: any = []; - let newSearchTile: any = null; + let newSearchDirections = []; + let newSearchTile = null; //// WIRE if (wireComp) { // Sanity check @@ -188,9 +188,9 @@ export class WireSystem extends GameSystem { } } //// PINS - const pinsComp: any = nextEntity.components.WiredPins; + const pinsComp = nextEntity.components.WiredPins; if (pinsComp) { - const slot: any = nextData.slot; + const slot = nextData.slot; assert(slot, "No slot set for next entity"); if (slot.type === enumPinSlotType.logicalEjector) { VERBOSE_WIRES && @@ -231,9 +231,9 @@ export class WireSystem extends GameSystem { } if (newSearchTile) { // Find new surrounding wire targets - const newTargets: any = this.findSurroundingWireTargets(newSearchTile, newSearchDirections, currentNetwork, variantMask); + const newTargets = this.findSurroundingWireTargets(newSearchTile, newSearchDirections, currentNetwork, variantMask); VERBOSE_WIRES && logger.log(" Found", newTargets, "new targets to visit!"); - for (let i: any = 0; i < newTargets.length; ++i) { + for (let i = 0; i < newTargets.length; ++i) { entitiesToVisit.push(newTargets[i]); } } @@ -247,13 +247,13 @@ export class WireSystem extends GameSystem { } else { // Unregister network again - for (let i: any = 0; i < currentNetwork.wires.length; ++i) { + for (let i = 0; i < currentNetwork.wires.length; ++i) { currentNetwork.wires[i].components.Wire.linkedNetwork = null; } - for (let i: any = 0; i < currentNetwork.tunnels.length; ++i) { + for (let i = 0; i < currentNetwork.tunnels.length; ++i) { fastArrayDeleteValueIfContained(currentNetwork.tunnels[i].components.WireTunnel.linkedNetworks, currentNetwork); } - for (let i: any = 0; i < currentNetwork.allSlots.length; ++i) { + for (let i = 0; i < currentNetwork.allSlots.length; ++i) { currentNetwork.allSlots[i].slot.linkedNetwork = null; } } @@ -263,32 +263,32 @@ export class WireSystem extends GameSystem { * {} */ findSurroundingWireTargets(initialTile: Vector, directions: Array, network: WireNetwork, variantMask: enumWireVariant= = null): Array { - let result: any = []; + let result = []; VERBOSE_WIRES && logger.log(" Searching for new targets at", initialTile.toString(), "and d=", directions, "with mask=", variantMask); // Go over all directions we should search for - for (let i: any = 0; i < directions.length; ++i) { - const direction: any = directions[i]; - const offset: any = enumDirectionToVector[direction]; - const initialSearchTile: any = initialTile.add(offset); + for (let i = 0; i < directions.length; ++i) { + const direction = directions[i]; + const offset = enumDirectionToVector[direction]; + const initialSearchTile = initialTile.add(offset); // Store which tunnels we already visited to avoid infinite loops - const visitedTunnels: any = new Set(); + const visitedTunnels = new Set(); // First, find the initial connected entities - const initialContents: any = this.root.map.getLayersContentsMultipleXY(initialSearchTile.x, initialSearchTile.y); + const initialContents = this.root.map.getLayersContentsMultipleXY(initialSearchTile.x, initialSearchTile.y); // Link the initial tile to the initial entities, since it may change const contents: Array<{ entity: Entity; tile: Vector; }> = []; - for (let j: any = 0; j < initialContents.length; ++j) { + for (let j = 0; j < initialContents.length; ++j) { contents.push({ entity: initialContents[j], tile: initialSearchTile, }); } - for (let k: any = 0; k < contents.length; ++k) { - const { entity, tile }: any = contents[k]; - const wireComp: any = entity.components.Wire; + for (let k = 0; k < contents.length; ++k) { + const { entity, tile } = contents[k]; + const wireComp = entity.components.Wire; // Check for wire if (wireComp && !wireComp.linkedNetwork && @@ -299,20 +299,20 @@ export class WireSystem extends GameSystem { }); } // Check for connected slots - const pinComp: any = entity.components.WiredPins; + const pinComp = entity.components.WiredPins; if (pinComp) { - const staticComp: any = entity.components.StaticMapEntity; + const staticComp = entity.components.StaticMapEntity; // Go over all slots and see if they are connected - const pinSlots: any = pinComp.slots; - for (let j: any = 0; j < pinSlots.length; ++j) { - const slot: any = pinSlots[j]; + const pinSlots = pinComp.slots; + for (let j = 0; j < pinSlots.length; ++j) { + const slot = pinSlots[j]; // Check if the position matches - const pinPos: any = staticComp.localTileToWorld(slot.pos); + const pinPos = staticComp.localTileToWorld(slot.pos); if (!pinPos.equals(tile)) { continue; } // Check if the direction (inverted) matches - const pinDirection: any = staticComp.localDirectionToWorld(slot.direction); + const pinDirection = staticComp.localDirectionToWorld(slot.direction); if (pinDirection !== enumInvertedDirections[direction]) { continue; } @@ -327,20 +327,20 @@ export class WireSystem extends GameSystem { continue; } // Check if it's a tunnel, if so, go to the forwarded item - const tunnelComp: any = entity.components.WireTunnel; + const tunnelComp = entity.components.WireTunnel; if (tunnelComp) { if (visitedTunnels.has(entity.uid)) { continue; } - const staticComp: any = entity.components.StaticMapEntity; + const staticComp = entity.components.StaticMapEntity; // Compute where this tunnel connects to - const forwardedTile: any = staticComp.origin.add(offset); + const forwardedTile = staticComp.origin.add(offset); VERBOSE_WIRES && logger.log(" Found tunnel", entity.uid, "at", tile, "-> forwarding to", forwardedTile); // Figure out which entities are connected - const connectedContents: any = this.root.map.getLayersContentsMultipleXY(forwardedTile.x, forwardedTile.y); + const connectedContents = this.root.map.getLayersContentsMultipleXY(forwardedTile.x, forwardedTile.y); // Attach the entities and the tile we search at, because it may change - for (let h: any = 0; h < connectedContents.length; ++h) { + for (let h = 0; h < connectedContents.length; ++h) { contents.push({ entity: connectedContents[h], tile: forwardedTile, @@ -364,22 +364,22 @@ export class WireSystem extends GameSystem { /** * Updates the wires network */ - update(): any { + update() { this.staleArea.update(); if (this.needsRecompute) { this.recomputeWiresNetwork(); } // Re-compute values of all networks - for (let i: any = 0; i < this.networks.length; ++i) { - const network: any = this.networks[i]; + for (let i = 0; i < this.networks.length; ++i) { + const network = this.networks[i]; // Reset conflicts network.valueConflict = false; // Aggregate values of all senders - const senders: any = network.providers; - let value: any = null; - for (let k: any = 0; k < senders.length; ++k) { - const senderSlot: any = senders[k]; - const slotValue: any = senderSlot.slot.value; + const senders = network.providers; + let value = null; + for (let k = 0; k < senders.length; ++k) { + const senderSlot = senders[k]; + const slotValue = senderSlot.slot.value; // The first sender can just put in his value if (!value) { value = slotValue; @@ -423,7 +423,7 @@ export class WireSystem extends GameSystem { opacity: 0.5, }; } - const network: any = wireComp.linkedNetwork; + const network = wireComp.linkedNetwork; if (network.valueConflict) { // There is a conflict return { @@ -439,18 +439,18 @@ export class WireSystem extends GameSystem { /** * Draws a given chunk */ - drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView): any { - const contents: any = chunk.wireContents; - for (let y: any = 0; y < globalConfig.mapChunkSize; ++y) { - for (let x: any = 0; x < globalConfig.mapChunkSize; ++x) { - const entity: any = contents[x][y]; + drawChunk(parameters: import("../../core/draw_utils").DrawParameters, chunk: MapChunkView) { + const contents = chunk.wireContents; + for (let y = 0; y < globalConfig.mapChunkSize; ++y) { + for (let x = 0; x < globalConfig.mapChunkSize; ++x) { + const entity = contents[x][y]; if (entity && entity.components.Wire) { - const wireComp: any = entity.components.Wire; - const wireType: any = wireComp.type; - const { opacity, spriteSet }: any = this.getSpriteSetAndOpacityForWire(wireComp); - const sprite: any = spriteSet[wireType]; + const wireComp = entity.components.Wire; + const wireType = wireComp.type; + const { opacity, spriteSet } = this.getSpriteSetAndOpacityForWire(wireComp); + const sprite = spriteSet[wireType]; assert(sprite, "Unknown wire type: " + wireType); - const staticComp: any = entity.components.StaticMapEntity; + const staticComp = entity.components.StaticMapEntity; parameters.context.globalAlpha = opacity; staticComp.drawSpriteOnBoundsClipped(parameters, sprite, 0); // DEBUG Rendering @@ -471,8 +471,8 @@ export class WireSystem extends GameSystem { // DEBUG Rendering if (G_IS_DEV && globalConfig.debug.renderWireNetworkInfos) { if (entity) { - const staticComp: any = entity.components.StaticMapEntity; - const wireComp: any = entity.components.Wire; + const staticComp = entity.components.StaticMapEntity; + const wireComp = entity.components.Wire; // Draw network info for wires if (wireComp && wireComp.linkedNetwork) { parameters.context.fillStyle = "red"; @@ -488,44 +488,44 @@ export class WireSystem extends GameSystem { /** * Returns whether this entity is relevant for the wires network */ - isEntityRelevantForWires(entity: Entity): any { + isEntityRelevantForWires(entity: Entity) { return entity.components.Wire || entity.components.WiredPins || entity.components.WireTunnel; } - queuePlacementUpdate(entity: Entity): any { + queuePlacementUpdate(entity: Entity) { if (!this.root.gameInitialized) { return; } if (!this.isEntityRelevantForWires(entity)) { return; } - const staticComp: any = entity.components.StaticMapEntity; + const staticComp = entity.components.StaticMapEntity; if (!staticComp) { return; } this.root.signals.achievementCheck.dispatch(ACHIEVEMENTS.place5000Wires, entity); // Invalidate affected area - const originalRect: any = staticComp.getTileSpaceBounds(); - const affectedArea: any = originalRect.expandedInAllDirections(1); + const originalRect = staticComp.getTileSpaceBounds(); + const affectedArea = originalRect.expandedInAllDirections(1); this.staleArea.invalidate(affectedArea); } /** * Updates the wire placement after an entity has been added / deleted */ - updateSurroundingWirePlacement(affectedArea: Rectangle): any { - const metaWire: any = gMetaBuildingRegistry.findByClass(MetaWireBuilding); - for (let x: any = affectedArea.x; x < affectedArea.right(); ++x) { - for (let y: any = affectedArea.y; y < affectedArea.bottom(); ++y) { - const targetEntities: any = this.root.map.getLayersContentsMultipleXY(x, y); - for (let i: any = 0; i < targetEntities.length; ++i) { - const targetEntity: any = targetEntities[i]; - const targetWireComp: any = targetEntity.components.Wire; - const targetStaticComp: any = targetEntity.components.StaticMapEntity; + updateSurroundingWirePlacement(affectedArea: Rectangle) { + const metaWire = gMetaBuildingRegistry.findByClass(MetaWireBuilding); + for (let x = affectedArea.x; x < affectedArea.right(); ++x) { + for (let y = affectedArea.y; y < affectedArea.bottom(); ++y) { + const targetEntities = this.root.map.getLayersContentsMultipleXY(x, y); + for (let i = 0; i < targetEntities.length; ++i) { + const targetEntity = targetEntities[i]; + const targetWireComp = targetEntity.components.Wire; + const targetStaticComp = targetEntity.components.StaticMapEntity; if (!targetWireComp) { // Not a wire continue; } - const variant: any = targetStaticComp.getVariant(); - const { rotation, rotationVariant, }: any = metaWire.computeOptimalDirectionAndRotationVariantAtTile({ + const variant = targetStaticComp.getVariant(); + const { rotation, rotationVariant, } = metaWire.computeOptimalDirectionAndRotationVariantAtTile({ root: this.root, tile: new Vector(x, y), rotation: targetStaticComp.originalRotation, @@ -533,7 +533,7 @@ export class WireSystem extends GameSystem { layer: targetEntity.layer, }); // Compute delta to see if anything changed - const newType: any = arrayWireRotationVariantToType[rotationVariant]; + const newType = arrayWireRotationVariantToType[rotationVariant]; if (targetStaticComp.rotation !== rotation || newType !== targetWireComp.type) { // Change stuff targetStaticComp.rotation = rotation; diff --git a/src/ts/game/systems/wired_pins.ts b/src/ts/game/systems/wired_pins.ts index 841b44e7..f9e993ec 100644 --- a/src/ts/game/systems/wired_pins.ts +++ b/src/ts/game/systems/wired_pins.ts @@ -29,9 +29,9 @@ export class WiredPinsSystem extends GameSystemWithFilter { /** * Performs pre-placement checks */ - prePlacementCheck(entity: Entity, offset: Vector): any { + prePlacementCheck(entity: Entity, offset: Vector) { // Compute area of the building - const rect: any = entity.components.StaticMapEntity.getTileSpaceBounds(); + const rect = entity.components.StaticMapEntity.getTileSpaceBounds(); if (offset) { rect.x += offset.x; rect.y += offset.y; @@ -39,15 +39,15 @@ export class WiredPinsSystem extends GameSystemWithFilter { // If this entity is placed on the wires layer, make sure we don't // place it above a pin if (entity.layer === "wires") { - for (let x: any = rect.x; x < rect.x + rect.w; ++x) { - for (let y: any = rect.y; y < rect.y + rect.h; ++y) { + for (let x = rect.x; x < rect.x + rect.w; ++x) { + for (let y = rect.y; y < rect.y + rect.h; ++y) { // Find which entities are in same tiles of both layers - const entities: any = this.root.map.getLayersContentsMultipleXY(x, y); - for (let i: any = 0; i < entities.length; ++i) { - const otherEntity: any = entities[i]; + const entities = this.root.map.getLayersContentsMultipleXY(x, y); + for (let i = 0; i < entities.length; ++i) { + const otherEntity = entities[i]; // Check if entity has a wired component - const pinComponent: any = otherEntity.components.WiredPins; - const staticComp: any = otherEntity.components.StaticMapEntity; + const pinComponent = otherEntity.components.WiredPins; + const staticComp = otherEntity.components.StaticMapEntity; if (!pinComponent) { continue; } @@ -59,9 +59,9 @@ export class WiredPinsSystem extends GameSystemWithFilter { continue; } // Go over all pins and check if they are blocking - const pins: any = pinComponent.slots; - for (let pinSlot: any = 0; pinSlot < pins.length; ++pinSlot) { - const pos: any = staticComp.localTileToWorld(pins[pinSlot].pos); + const pins = pinComponent.slots; + for (let pinSlot = 0; pinSlot < pins.length; ++pinSlot) { + const pos = staticComp.localTileToWorld(pins[pinSlot].pos); // Occupied by a pin if (pos.x === x && pos.y === y) { return STOP_PROPAGATION; @@ -81,24 +81,24 @@ export class WiredPinsSystem extends GameSystemWithFilter { * {} True if the pins collide */ checkEntityPinsCollide(entity: Entity, offset: Vector=): boolean { - const pinsComp: any = entity.components.WiredPins; + const pinsComp = entity.components.WiredPins; if (!pinsComp) { return false; } // Go over all slots - for (let slotIndex: any = 0; slotIndex < pinsComp.slots.length; ++slotIndex) { - const slot: any = pinsComp.slots[slotIndex]; + for (let slotIndex = 0; slotIndex < pinsComp.slots.length; ++slotIndex) { + const slot = pinsComp.slots[slotIndex]; // Figure out which tile this slot is on - const worldPos: any = entity.components.StaticMapEntity.localTileToWorld(slot.pos); + const worldPos = entity.components.StaticMapEntity.localTileToWorld(slot.pos); if (offset) { worldPos.x += offset.x; worldPos.y += offset.y; } // Check if there is any entity on that tile (Wired pins are always on the wires layer) - const collidingEntity: any = this.root.map.getLayerContentXY(worldPos.x, worldPos.y, "wires"); + const collidingEntity = this.root.map.getLayerContentXY(worldPos.x, worldPos.y, "wires"); // If there's an entity, and it can't get removed -> That's a collision if (collidingEntity) { - const staticComp: any = collidingEntity.components.StaticMapEntity; + const staticComp = collidingEntity.components.StaticMapEntity; if (!staticComp .getMetaBuilding() .getIsReplaceable(staticComp.getVariant(), staticComp.getRotationVariant())) { @@ -111,19 +111,19 @@ export class WiredPinsSystem extends GameSystemWithFilter { /** * Called to free space for the given entity */ - freeEntityAreaBeforeBuild(entity: Entity): any { - const pinsComp: any = entity.components.WiredPins; + freeEntityAreaBeforeBuild(entity: Entity) { + const pinsComp = entity.components.WiredPins; if (!pinsComp) { // Entity has no pins return; } // Remove any stuff which collides with the pins - for (let i: any = 0; i < pinsComp.slots.length; ++i) { - const slot: any = pinsComp.slots[i]; - const worldPos: any = entity.components.StaticMapEntity.localTileToWorld(slot.pos); - const collidingEntity: any = this.root.map.getLayerContentXY(worldPos.x, worldPos.y, "wires"); + for (let i = 0; i < pinsComp.slots.length; ++i) { + const slot = pinsComp.slots[i]; + const worldPos = entity.components.StaticMapEntity.localTileToWorld(slot.pos); + const collidingEntity = this.root.map.getLayerContentXY(worldPos.x, worldPos.y, "wires"); if (collidingEntity) { - const staticComp: any = collidingEntity.components.StaticMapEntity; + const staticComp = collidingEntity.components.StaticMapEntity; assertAlways(staticComp .getMetaBuilding() .getIsReplaceable(staticComp.getVariant(), staticComp.getRotationVariant()), "Tried to replace non-repleaceable entity for pins"); @@ -136,29 +136,29 @@ export class WiredPinsSystem extends GameSystemWithFilter { /** * Draws a given entity */ - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { - const contents: any = chunk.containedEntities; - for (let i: any = 0; i < contents.length; ++i) { - const entity: any = contents[i]; - const pinsComp: any = entity.components.WiredPins; + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { + const contents = chunk.containedEntities; + for (let i = 0; i < contents.length; ++i) { + const entity = contents[i]; + const pinsComp = entity.components.WiredPins; if (!pinsComp) { continue; } - const staticComp: any = entity.components.StaticMapEntity; - const slots: any = pinsComp.slots; - for (let j: any = 0; j < slots.length; ++j) { - const slot: any = slots[j]; - const tile: any = staticComp.localTileToWorld(slot.pos); + const staticComp = entity.components.StaticMapEntity; + const slots = pinsComp.slots; + for (let j = 0; j < slots.length; ++j) { + const slot = slots[j]; + const tile = staticComp.localTileToWorld(slot.pos); if (!chunk.tileSpaceRectangle.containsPoint(tile.x, tile.y)) { // Doesn't belong to this chunk continue; } - const worldPos: any = tile.toWorldSpaceCenterOfTile(); + const worldPos = tile.toWorldSpaceCenterOfTile(); // Culling if (!parameters.visibleRect.containsCircle(worldPos.x, worldPos.y, globalConfig.halfTileSize)) { continue; } - const effectiveRotation: any = Math.radians(staticComp.rotation + enumDirectionToAngle[slot.direction]); + const effectiveRotation = Math.radians(staticComp.rotation + enumDirectionToAngle[slot.direction]); if (staticComp.getMetaBuilding().getRenderPins()) { drawRotatedSprite({ parameters, @@ -172,15 +172,15 @@ export class WiredPinsSystem extends GameSystemWithFilter { }); } // Draw contained item to visualize whats emitted - const value: any = slot.value; + const value = slot.value; if (value) { - const offset: any = new Vector(0, -9.1).rotated(effectiveRotation); + const offset = new Vector(0, -9.1).rotated(effectiveRotation); value.drawItemCenteredClipped(worldPos.x + offset.x, worldPos.y + offset.y, parameters, enumTypeToSize[value.getItemType()]); } // Debug view if (G_IS_DEV && globalConfig.debug.renderWireNetworkInfos) { - const offset: any = new Vector(0, -10).rotated(effectiveRotation); - const network: any = slot.linkedNetwork; + const offset = new Vector(0, -10).rotated(effectiveRotation); + const network = slot.linkedNetwork; parameters.context.fillStyle = "blue"; parameters.context.font = "5px Tahoma"; parameters.context.textAlign = "center"; diff --git a/src/ts/game/systems/zone.ts b/src/ts/game/systems/zone.ts index d59c9aae..f28ad876 100644 --- a/src/ts/game/systems/zone.ts +++ b/src/ts/game/systems/zone.ts @@ -15,7 +15,7 @@ export class ZoneSystem extends GameSystem { constructor(root) { super(root); this.root.signals.prePlacementCheck.add(this.prePlacementCheck, this); - this.root.signals.gameFrameStarted.add((): any => { + this.root.signals.gameFrameStarted.add(() => { this.drawn = false; }); } @@ -2433,48 +2433,48 @@ export class ZoneSystem extends GameSystem { * @param {Vector | undefined} tile * @returns */ - prePlacementCheck(entity: Entity, tile: Vector | undefined = null): any { - const staticComp: any = entity.components.StaticMapEntity; + prePlacementCheck(entity: Entity, tile: Vector | undefined = null) { + const staticComp = entity.components.StaticMapEntity; if (!staticComp) { return; } - const mode: any = this.root.gameMode; - const zones: any = mode.getBuildableZones(); + const mode = this.root.gameMode; + const zones = mode.getBuildableZones(); if (!zones) { return; } - const transformed: any = staticComp.getTileSpaceBounds(); + const transformed = staticComp.getTileSpaceBounds(); if (tile) { transformed.x += tile.x; transformed.y += tile.y; } - if (!zones.some((zone: any): any => zone.intersectsFully(transformed))) { + if (!zones.some(zone => zone.intersectsFully(transformed))) { return STOP_PROPAGATION; } } /** * Draws the zone */ - drawChunk(parameters: DrawParameters, chunk: MapChunkView): any { + drawChunk(parameters: DrawParameters, chunk: MapChunkView) { if (this.drawn) { // oof return; } this.drawn = true; - const mode: any = this.root.gameMode; - const zones: any = mode.getBuildableZones(); + const mode = this.root.gameMode; + const zones = mode.getBuildableZones(); if (!zones) { return; } - const zone: any = zones[0].allScaled(globalConfig.tileSize); - const context: any = parameters.context; + const zone = zones[0].allScaled(globalConfig.tileSize); + const context = parameters.context; context.lineWidth = 2; context.strokeStyle = THEME.map.zone.borderSolid; context.beginPath(); context.rect(zone.x - 1, zone.y - 1, zone.w + 2, zone.h + 2); context.stroke(); - const outer: any = zone; - const padding: any = 40 * globalConfig.tileSize; + const outer = zone; + const padding = 40 * globalConfig.tileSize; context.fillStyle = THEME.map.zone.outerColor; context.fillRect(outer.x + outer.w, outer.y, padding, outer.h); context.fillRect(outer.x - padding, outer.y, padding, outer.h); diff --git a/src/ts/game/theme.ts b/src/ts/game/theme.ts index c1f212d9..36590ed2 100644 --- a/src/ts/game/theme.ts +++ b/src/ts/game/theme.ts @@ -1,8 +1,8 @@ -export const THEMES: any = { +export const THEMES = { dark: require("./themes/dark.json"), light: require("./themes/light.json"), }; -export let THEME: any = THEMES.light; -export function applyGameTheme(id: any): any { +export let THEME = THEMES.light; +export function applyGameTheme(id) { THEME = THEMES[id]; } diff --git a/src/ts/game/time/base_game_speed.ts b/src/ts/game/time/base_game_speed.ts index 6dea174b..5614c06c 100644 --- a/src/ts/game/time/base_game_speed.ts +++ b/src/ts/game/time/base_game_speed.ts @@ -14,32 +14,32 @@ export class BaseGameSpeed extends BasicSerializableObject { abstract; return "unknown-speed"; } - getId(): any { + getId() { // @ts-ignore return this.constructor.getId(); } - static getSchema(): any { + static getSchema() { return {}; } - initializeAfterDeserialize(root: any): any { + initializeAfterDeserialize(root) { this.root = root; } /** * Returns the time multiplier */ - getTimeMultiplier(): any { + getTimeMultiplier() { return 1; } /** * Returns how many logic steps there may be queued */ - getMaxLogicStepsInQueue(): any { + getMaxLogicStepsInQueue() { return 3; } // Internals /** {} */ - newSpeed(instance: any): BaseGameSpeed { + newSpeed(instance): BaseGameSpeed { return new instance(this.root); } } diff --git a/src/ts/game/time/fast_forward_game_speed.ts b/src/ts/game/time/fast_forward_game_speed.ts index fb6c88de..0a79b5fd 100644 --- a/src/ts/game/time/fast_forward_game_speed.ts +++ b/src/ts/game/time/fast_forward_game_speed.ts @@ -1,13 +1,13 @@ import { BaseGameSpeed } from "./base_game_speed"; import { globalConfig } from "../../core/config"; export class FastForwardGameSpeed extends BaseGameSpeed { - static getId(): any { + static getId() { return "fast-forward"; } - getTimeMultiplier(): any { + getTimeMultiplier() { return globalConfig.fastForwardSpeed; } - getMaxLogicStepsInQueue(): any { + getMaxLogicStepsInQueue() { return 3 * globalConfig.fastForwardSpeed; } } diff --git a/src/ts/game/time/game_time.ts b/src/ts/game/time/game_time.ts index ad3ed836..603cf375 100644 --- a/src/ts/game/time/game_time.ts +++ b/src/ts/game/time/game_time.ts @@ -8,7 +8,7 @@ import { PausedGameSpeed } from "./paused_game_speed"; import { gGameSpeedRegistry } from "../../core/global_registries"; import { globalConfig } from "../../core/config"; import { createLogger } from "../../core/logging"; -const logger: any = createLogger("game_time"); +const logger = createLogger("game_time"); export class GameTime extends BasicSerializableObject { public root = root; public timeSeconds = 0; @@ -20,10 +20,10 @@ export class GameTime extends BasicSerializableObject { constructor(root) { super(); } - static getId(): any { + static getId() { return "GameTime"; } - static getSchema(): any { + static getSchema() { return { timeSeconds: types.float, speed: types.obj(gGameSpeedRegistry), @@ -33,13 +33,13 @@ export class GameTime extends BasicSerializableObject { /** * Fetches the new "real" time, called from the core once per frame, since performance now() is kinda slow */ - updateRealtimeNow(): any { + updateRealtimeNow() { this.realtimeSeconds = performance.now() / 1000.0 + this.realtimeAdjust; } /** * Returns the ingame time in milliseconds */ - getTimeMs(): any { + getTimeMs() { return this.timeSeconds * 1000.0; } /** @@ -59,17 +59,17 @@ export class GameTime extends BasicSerializableObject { /** * Internal method to generate new logic time budget */ - internalAddDeltaToBudget(deltaMs: number): any { + internalAddDeltaToBudget(deltaMs: number) { // Only update if game is supposed to update if (this.root.hud.shouldPauseGame()) { this.logicTimeBudget = 0; } else { - const multiplier: any = this.getSpeed().getTimeMultiplier(); + const multiplier = this.getSpeed().getTimeMultiplier(); this.logicTimeBudget += deltaMs * multiplier; } // Check for too big pile of updates -> reduce it to 1 - let maxLogicSteps: any = Math.max(3, (this.speed.getMaxLogicStepsInQueue() * this.root.dynamicTickrate.currentTickRate) / 60); + let maxLogicSteps = Math.max(3, (this.speed.getMaxLogicStepsInQueue() * this.root.dynamicTickrate.currentTickRate) / 60); if (G_IS_DEV && globalConfig.debug.framePausesBetweenTicks) { maxLogicSteps *= 1 + globalConfig.debug.framePausesBetweenTicks; } @@ -80,10 +80,10 @@ export class GameTime extends BasicSerializableObject { /** * Performs update ticks based on the queued logic budget */ - performTicks(deltaMs: number, updateMethod: function():boolean): any { + performTicks(deltaMs: number, updateMethod: function():boolean) { this.internalAddDeltaToBudget(deltaMs); - const speedAtStart: any = this.root.time.getSpeed(); - let effectiveDelta: any = this.root.dynamicTickrate.deltaMs; + const speedAtStart = this.root.time.getSpeed(); + let effectiveDelta = this.root.dynamicTickrate.deltaMs; if (G_IS_DEV && globalConfig.debug.framePausesBetweenTicks) { effectiveDelta += globalConfig.debug.framePausesBetweenTicks * this.root.dynamicTickrate.deltaMs; } @@ -124,13 +124,13 @@ export class GameTime extends BasicSerializableObject { systemNow(): number { return (this.realtimeSeconds - this.realtimeAdjust) * 1000.0; } - getIsPaused(): any { + getIsPaused() { return this.speed.getId() === PausedGameSpeed.getId(); } - getSpeed(): any { + getSpeed() { return this.speed; } - setSpeed(speed: any): any { + setSpeed(speed) { assert(speed instanceof BaseGameSpeed, "Not a valid game speed"); if (this.speed.getId() === speed.getId()) { @@ -138,8 +138,8 @@ export class GameTime extends BasicSerializableObject { } this.speed = speed; } - deserialize(data: any): any { - const errorCode: any = super.deserialize(data); + deserialize(data) { + const errorCode = super.deserialize(data); if (errorCode) { return errorCode; } diff --git a/src/ts/game/time/paused_game_speed.ts b/src/ts/game/time/paused_game_speed.ts index a7d7c347..4dc10376 100644 --- a/src/ts/game/time/paused_game_speed.ts +++ b/src/ts/game/time/paused_game_speed.ts @@ -1,12 +1,12 @@ import { BaseGameSpeed } from "./base_game_speed"; export class PausedGameSpeed extends BaseGameSpeed { - static getId(): any { + static getId() { return "paused"; } - getTimeMultiplier(): any { + getTimeMultiplier() { return 0; } - getMaxLogicStepsInQueue(): any { + getMaxLogicStepsInQueue() { return 0; } } diff --git a/src/ts/game/time/regular_game_speed.ts b/src/ts/game/time/regular_game_speed.ts index 44234d6f..ade4b373 100644 --- a/src/ts/game/time/regular_game_speed.ts +++ b/src/ts/game/time/regular_game_speed.ts @@ -1,9 +1,9 @@ import { BaseGameSpeed } from "./base_game_speed"; export class RegularGameSpeed extends BaseGameSpeed { - static getId(): any { + static getId() { return "regular"; } - getTimeMultiplier(): any { + getTimeMultiplier() { return 1; } } diff --git a/src/ts/game/tutorial_goals.ts b/src/ts/game/tutorial_goals.ts index 21b0f7dd..ad803e4a 100644 --- a/src/ts/game/tutorial_goals.ts +++ b/src/ts/game/tutorial_goals.ts @@ -2,7 +2,7 @@ * Don't forget to also update tutorial_goals_mappings.js as well as the translations! * @enum {string} */ -export const enumHubGoalRewards: any = { +export const enumHubGoalRewards = { reward_cutter_and_trash: "reward_cutter_and_trash", reward_rotater: "reward_rotater", reward_painter: "reward_painter", diff --git a/src/ts/game/tutorial_goals_mappings.ts b/src/ts/game/tutorial_goals_mappings.ts index 27086396..8a8271d9 100644 --- a/src/ts/game/tutorial_goals_mappings.ts +++ b/src/ts/game/tutorial_goals_mappings.ts @@ -24,12 +24,12 @@ import { enumHubGoalRewards } from "./tutorial_goals"; * Helper method for proper types * {} */ -const typed: any = (x: any): TutorialGoalReward => x; +const typed = (x): TutorialGoalReward => x; /** * Stores which reward unlocks what * @enum {TutorialGoalReward?} */ -export const enumHubGoalRewardsToContentUnlocked: any = { +export const enumHubGoalRewardsToContentUnlocked = { [enumHubGoalRewards.reward_cutter_and_trash]: typed([[MetaCutterBuilding, defaultBuildingVariant]]), [enumHubGoalRewards.reward_rotater]: typed([[MetaRotaterBuilding, defaultBuildingVariant]]), [enumHubGoalRewards.reward_painter]: typed([[MetaPainterBuilding, defaultBuildingVariant]]), @@ -67,12 +67,12 @@ export const enumHubGoalRewardsToContentUnlocked: any = { }; if (G_IS_DEV) { // Sanity check - for (const rewardId: any in enumHubGoalRewards) { - const mapping: any = enumHubGoalRewardsToContentUnlocked[rewardId]; + for (const rewardId in enumHubGoalRewards) { + const mapping = enumHubGoalRewardsToContentUnlocked[rewardId]; if (typeof mapping === "undefined") { assertAlways(false, "Please define a mapping for the reward " + rewardId + " in tutorial_goals_mappings.js"); } - const translation: any = T.storyRewards[rewardId]; + const translation = T.storyRewards[rewardId]; if (!translation || !translation.title || !translation.desc) { assertAlways(false, "Translation for reward " + rewardId + "missing"); } diff --git a/src/ts/languages.ts b/src/ts/languages.ts index 8aef3c84..f4983a62 100644 --- a/src/ts/languages.ts +++ b/src/ts/languages.ts @@ -1,5 +1,5 @@ export const LANGUAGES: { - [idx: string]: { + [code: string]: { name: string; data: any; code: string; diff --git a/src/ts/main.ts b/src/ts/main.ts index fc66b78e..2dec9f25 100644 --- a/src/ts/main.ts +++ b/src/ts/main.ts @@ -13,14 +13,23 @@ import { initMetaBuildingRegistry } from "./game/meta_building_registry"; import { initGameModeRegistry } from "./game/game_mode_registry"; import { initGameSpeedRegistry } from "./game/game_speed_registry"; -const logger: any = createLogger("main"); +const logger = createLogger("main"); if (window.coreThreadLoadedCb) { logger.log("Javascript parsed, calling html thread"); window.coreThreadLoadedCb(); } -console.log(`%cshapez.io ️%c\n© 2022 tobspr Games\nCommit %c${G_BUILD_COMMIT_HASH}%c on %c${new Date(G_BUILD_TIME).toLocaleString()}\n`, "font-size: 35px; font-family: Arial;font-weight: bold; padding: 10px 0;", "color: #aaa", "color: #7f7", "color: #aaa", "color: #7f7"); +console.log( + `%cshapez.io ️%c\n© 2022 tobspr Games\nCommit %c${G_BUILD_COMMIT_HASH}%c on %c${new Date( + G_BUILD_TIME + ).toLocaleString()}\n`, + "font-size: 35px; font-family: Arial;font-weight: bold; padding: 10px 0;", + "color: #aaa", + "color: #7f7", + "color: #aaa", + "color: #7f7" +); console.log("Environment: %c" + G_APP_ENVIRONMENT, "color: #fff"); @@ -46,9 +55,9 @@ initMetaBuildingRegistry(); initGameModeRegistry(); initGameSpeedRegistry(); -let app: Application = null; +let app = null; -function bootApp(): any { +function bootApp() { logger.log("Page Loaded"); app = new Application(); app.boot(); diff --git a/src/ts/mods/mod.ts b/src/ts/mods/mod.ts index 9705c0de..2445a99a 100644 --- a/src/ts/mods/mod.ts +++ b/src/ts/mods/mod.ts @@ -14,7 +14,7 @@ export class Mod { constructor({ app, modLoader, meta, settings, saveSettings }) { } - init(): any { + init() { // to be overridden } get dialogs() { diff --git a/src/ts/mods/mod_interface.ts b/src/ts/mods/mod_interface.ts index 26f8ed9a..b0d68a02 100644 --- a/src/ts/mods/mod_interface.ts +++ b/src/ts/mods/mod_interface.ts @@ -51,23 +51,23 @@ export class ModInterface { constructor(modLoader) { } - registerCss(cssString: any): any { + registerCss(cssString) { // Preprocess css - cssString = cssString.replace(/\$scaled\(([^)]*)\)/gim, (substr: any, expression: any): any => { + cssString = cssString.replace(/\$scaled\(([^)]*)\)/gim, (substr, expression) => { return "calc((" + expression + ") * var(--ui-scale))"; }); - const element: any = document.createElement("style"); + const element = document.createElement("style"); element.textContent = cssString; document.head.appendChild(element); } - registerSprite(spriteId: any, base64string: any): any { + registerSprite(spriteId, base64string) { assert(base64string.startsWith("data:image")); - const img: any = new Image(); - const sprite: any = new AtlasSprite(spriteId); + const img = new Image(); + const sprite = new AtlasSprite(spriteId); sprite.frozen = true; - img.addEventListener("load", (): any => { - for (const resolution: any in sprite.linksByResolution) { - const link: any = sprite.linksByResolution[resolution]; + img.addEventListener("load", () => { + for (const resolution in sprite.linksByResolution) { + const link = sprite.linksByResolution[resolution]; link.w = img.width; link.h = img.height; link.packedW = img.width; @@ -75,7 +75,7 @@ export class ModInterface { } }); img.src = base64string; - const link: any = new SpriteAtlasLink({ + const link = new SpriteAtlasLink({ w: 1, h: 1, atlas: img, @@ -91,20 +91,20 @@ export class ModInterface { sprite.linksByResolution["0.75"] = link; Loader.sprites.set(spriteId, sprite); } - registerAtlas(imageBase64: string, jsonTextData: string): any { - const atlasData: any = JSON.parse(jsonTextData); - const img: any = new Image(); + registerAtlas(imageBase64: string, jsonTextData: string) { + const atlasData = JSON.parse(jsonTextData); + const img = new Image(); img.src = imageBase64; - const sourceData: any = atlasData.frames; - for (const spriteName: any in sourceData) { - const { frame, sourceSize, spriteSourceSize }: any = sourceData[spriteName]; - let sprite: any = (Loader.sprites.get(spriteName) as AtlasSprite); + const sourceData = atlasData.frames; + for (const spriteName in sourceData) { + const { frame, sourceSize, spriteSourceSize } = sourceData[spriteName]; + let sprite = Loader.sprites.get(spriteName) as AtlasSprite); if (!sprite) { sprite = new AtlasSprite(spriteName); Loader.sprites.set(spriteName, sprite); } sprite.frozen = true; - const link: any = new SpriteAtlasLink({ + const link = new SpriteAtlasLink({ packedX: frame.x, packedY: frame.y, packedW: frame.w, @@ -130,7 +130,7 @@ export class ModInterface { shortCode: string; weightComputation: (distanceToOriginInChunks: number) => number; draw: (options: import("../game/shape_definition").SubShapeDrawOptions) => void; - }): any { + }) { if (shortCode.length !== 1) { throw new Error("Bad short code: " + shortCode); } @@ -140,8 +140,8 @@ export class ModInterface { MODS_ADDITIONAL_SHAPE_MAP_WEIGHTS[id] = weightComputation; MODS_ADDITIONAL_SUB_SHAPE_DRAWERS[id] = draw; } - registerTranslations(language: any, translations: any): any { - const data: any = LANGUAGES[language]; + registerTranslations(language, translations) { + const data = LANGUAGES[language]; if (!data) { throw new Error("Unknown language: " + language); } @@ -150,11 +150,11 @@ export class ModInterface { matchDataRecursive(T, translations, true); } } - registerItem(item: typeof BaseItem, resolver: (itemData: any) => BaseItem): any { + registerItem(item: typeof BaseItem, resolver: (itemData: any) => BaseItem) { gItemRegistry.register(item); MODS_ADDITIONAL_ITEMS[item.getId()] = resolver; } - registerComponent(component: typeof Component): any { + registerComponent(component: typeof Component) { gComponentRegistry.register(component); } registerGameSystem({ id, systemClass, before, drawHooks }: { @@ -162,9 +162,9 @@ export class ModInterface { systemClass: new (any) => GameSystem; before: string=; drawHooks: string[]=; - }): any { - const key: any = before || "key"; - const payload: any = { id, systemClass }; + }) { + const key = before || "key"; + const payload = { id, systemClass }; if (MODS_ADDITIONAL_SYSTEMS[key]) { MODS_ADDITIONAL_SYSTEMS[key].push(payload); } @@ -172,10 +172,10 @@ export class ModInterface { MODS_ADDITIONAL_SYSTEMS[key] = [payload]; } if (drawHooks) { - drawHooks.forEach((hookId: any): any => this.registerGameSystemDrawHook(hookId, id)); + drawHooks.forEach(hookId => this.registerGameSystemDrawHook(hookId, id)); } } - registerGameSystemDrawHook(hookId: string, systemId: string): any { + registerGameSystemDrawHook(hookId: string, systemId: string) { if (!MOD_CHUNK_DRAW_HOOKS[hookId]) { throw new Error("bad game system draw hook: " + hookId); } @@ -184,19 +184,19 @@ export class ModInterface { registerNewBuilding({ metaClass, buildingIconBase64 }: { metaClass: typeof ModMetaBuilding; buildingIconBase64: string=; - }): any { - const id: any = new metaClass as new (...args) => ModMetaBuilding)().getId(); + }) { + const id = new metaClass as new (...args) => ModMetaBuilding)().getId(); if (gMetaBuildingRegistry.hasId(id)) { throw new Error("Tried to register building twice: " + id); } gMetaBuildingRegistry.register(metaClass); - const metaInstance: any = gMetaBuildingRegistry.findByClass(metaClass); + const metaInstance = gMetaBuildingRegistry.findByClass(metaClass); T.buildings[id] = {}; - metaClass.getAllVariantCombinations().forEach((combination: any): any => { - const variant: any = combination.variant || defaultBuildingVariant; - const rotationVariant: any = combination.rotationVariant || 0; - const buildingIdentifier: any = id + (variant === defaultBuildingVariant ? "" : "-" + variant); - const uniqueTypeId: any = buildingIdentifier + (rotationVariant === 0 ? "" : "-" + rotationVariant); + metaClass.getAllVariantCombinations().forEach(combination => { + const variant = combination.variant || defaultBuildingVariant; + const rotationVariant = combination.rotationVariant || 0; + const buildingIdentifier = id + (variant === defaultBuildingVariant ? "" : "-" + variant); + const uniqueTypeId = buildingIdentifier + (rotationVariant === 0 ? "" : "-" + rotationVariant); registerBuildingVariant(uniqueTypeId, metaClass, variant, rotationVariant); gBuildingVariants[id].metaInstance = metaInstance; this.registerTranslations("en", { @@ -235,11 +235,11 @@ export class ModInterface { ctrl?: boolean; }=; builtin: boolean=; - }): any { + }) { if (!KEYMAPPINGS.mods) { KEYMAPPINGS.mods = {}; } - const binding: any = (KEYMAPPINGS.mods[id] = { + const binding = (KEYMAPPINGS.mods[id] = { keyCode, id, repeated, @@ -254,7 +254,7 @@ export class ModInterface { }, }); if (handler) { - this.modLoader.signals.gameStarted.add((root: any): any => { + this.modLoader.signals.gameStarted.add(root => { root.keyMapper.getBindingById(id).addToTop(handler.bind(null, root)); }); } @@ -264,7 +264,7 @@ export class ModInterface { * {} */ get dialogs() { - const state: any = this.modLoader.app.stateMgr.currentState; + const state = this.modLoader.app.stateMgr.currentState; // @ts-ignore if (state.dialogs) { // @ts-ignore @@ -272,7 +272,7 @@ export class ModInterface { } throw new Error("Tried to access dialogs but current state doesn't support it"); } - setBuildingToolbarIcon(buildingId: any, iconBase64: any): any { + setBuildingToolbarIcon(buildingId, iconBase64) { this.registerCss(` [data-icon="building_icons/${buildingId}.png"] .icon { background-image: url('${iconBase64}') !important; @@ -282,11 +282,11 @@ export class ModInterface { /** * * - etBuildingTutorialImage(buldingIdOrClass: string | (new () => MetaBuilding), variant: *, imageBase64: *): any { + etBuildingTutorialImage(buldingIdOrClass: string | (new () => MetaBuilding), variant: *, imageBase64: *) { if (typeof buildingIdOrClass === "function") { buildingIdOrClass = new buildingIdOrClass().id; } - const buildingIdentifier: any = buildingIdOrClass + (variant === defaultBuildingVariant ? "" : "-" + variant); + const buildingIdentifier = buildingIdOrClass + (variant === defaultBuildingVariant ? "" : "-" + variant); this.registerCss(` [data-icon="building_tutorials/${buildingIdentifier}.png"] { background-image: url('${imageBase64}') !important; @@ -299,7 +299,7 @@ export class ModInterface { id: string; name: string; theme: Object; - }): any { + }) { THEMES[id] = theme; this.registerTranslations("en", { settings: { @@ -316,17 +316,17 @@ export class ModInterface { /** * Registers a new state class, should be a GameState derived class */ - registerGameState(stateClass: typeof import("../core/game_state").GameState): any { + registerGameState(stateClass: typeof import("../core/game_state").GameState) { this.modLoader.app.stateMgr.register(stateClass); } addNewBuildingToToolbar({ toolbar, location, metaClass }: { toolbar: "regular" | "wires"; location: "primary" | "secondary"; metaClass: typeof MetaBuilding; - }): any { - const hudElementName: any = toolbar === "wires" ? "HUDWiresToolbar" : "HUDBuildingsToolbar"; - const property: any = location === "secondary" ? "secondaryBuildings" : "primaryBuildings"; - this.modLoader.signals.hudElementInitialized.add((element: any): any => { + }) { + const hudElementName = toolbar === "wires" ? "HUDWiresToolbar" : "HUDBuildingsToolbar"; + const property = location === "secondary" ? "secondaryBuildings" : "primaryBuildings"; + this.modLoader.signals.hudElementInitialized.add(element => { if (element.constructor.name === hudElementName) { element[property].push(metaClass); @@ -340,9 +340,9 @@ export class ModInterface { * @template {keyof P} M the name of the method we are overriding * @template {extendsPrams} O the method that will override the old one */ - replaceMethod(classHandle: C, methodName: M, override: bindThis, InstanceType>): any { - const oldMethod: any = classHandle.prototype[methodName]; - classHandle.prototype[methodName] = function (): any { + replaceMethod(classHandle: C, methodName: M, override: bindThis, InstanceType>) { + const oldMethod = classHandle.prototype[methodName]; + classHandle.prototype[methodName] = function () { //@ts-ignore This is true I just cant tell it that arguments will be Arguments return override.call(this, oldMethod.bind(this), arguments); }; @@ -354,9 +354,9 @@ export class ModInterface { * @template {keyof P} M the name of the method we are overriding * @template {extendsPrams} O the method that will run before the old one */ - runBeforeMethod(classHandle: C, methodName: M, executeBefore: bindThis>): any { - const oldHandle: any = classHandle.prototype[methodName]; - classHandle.prototype[methodName] = function (): any { + runBeforeMethod(classHandle: C, methodName: M, executeBefore: bindThis>) { + const oldHandle = classHandle.prototype[methodName]; + classHandle.prototype[methodName] = function () { //@ts-ignore Same as above executeBefore.apply(this, arguments); return oldHandle.apply(this, arguments); @@ -369,21 +369,21 @@ export class ModInterface { * @template {keyof P} M the name of the method we are overriding * @template {extendsPrams} O the method that will run before the old one */ - runAfterMethod(classHandle: C, methodName: M, executeAfter: bindThis>): any { - const oldHandle: any = classHandle.prototype[methodName]; - classHandle.prototype[methodName] = function (): any { - const returnValue: any = oldHandle.apply(this, arguments); + runAfterMethod(classHandle: C, methodName: M, executeAfter: bindThis>) { + const oldHandle = classHandle.prototype[methodName]; + classHandle.prototype[methodName] = function () { + const returnValue = oldHandle.apply(this, arguments); //@ts-ignore executeAfter.apply(this, arguments); return returnValue; }; } - extendObject(prototype: Object, extender: ({ $super, $old }) => any): any { - const $super: any = Object.getPrototypeOf(prototype); - const $old: any = {}; - const extensionMethods: any = extender({ $super, $old }); - const properties: any = Array.from(Object.getOwnPropertyNames(extensionMethods)); - properties.forEach((propertyName: any): any => { + extendObject(prototype: Object, extender: ({ $super, $old }) => any) { + const $super = Object.getPrototypeOf(prototype); + const $old = {}; + const extensionMethods = extender({ $super, $old }); + const properties = Array.from(Object.getOwnPropertyNames(extensionMethods)); + properties.forEach(propertyName => { if (["constructor", "prototype"].includes(propertyName)) { return; @@ -392,11 +392,11 @@ export class ModInterface { prototype[propertyName] = extensionMethods[propertyName]; }); } - extendClass(classHandle: Class, extender: ({ $super, $old }) => any): any { + extendClass(classHandle: Class, extender: ({ $super, $old }) => any) { this.extendObject(classHandle.prototype, extender); } - registerHudElement(id: string, element: new (...args) => BaseHUDPart): any { - this.modLoader.signals.hudInitializer.add((root: any): any => { + registerHudElement(id: string, element: new (...args) => BaseHUDPart) { + this.modLoader.signals.hudInitializer.add(root => { root.hud.parts[id] = new element(root); }); } @@ -404,7 +404,7 @@ export class ModInterface { name: string; description: string; language: string=; - }): any { + }) { if (typeof buildingIdOrClass === "function") { buildingIdOrClass = new buildingIdOrClass().id; } @@ -422,11 +422,11 @@ export class ModInterface { registerBuildingSprites(buildingIdOrClass: string | (new () => MetaBuilding), variant: string, { regularBase64, blueprintBase64 }: { regularBase64: string=; blueprintBase64: string=; - }): any { + }) { if (typeof buildingIdOrClass === "function") { buildingIdOrClass = new buildingIdOrClass().id; } - const spriteId: any = buildingIdOrClass + (variant === defaultBuildingVariant ? "" : "-" + variant) + ".png"; + const spriteId = buildingIdOrClass + (variant === defaultBuildingVariant ? "" : "-" + variant) + ".png"; if (regularBase64) { this.registerSprite("sprites/buildings/" + spriteId, regularBase64); } @@ -447,7 +447,7 @@ export class ModInterface { string ][]=; isUnlocked: (root: GameRoot) => boolean[]=; - }): any { + }) { if (!payload.rotationVariants) { payload.rotationVariants = [0]; } @@ -468,13 +468,13 @@ export class ModInterface { description: payload.description, }); } - const internalId: any = new metaClass().getId() + "-" + variant; + const internalId = new metaClass().getId() + "-" + variant; // Extend static methods - this.extendObject(metaClass, ({ $old }: any): any => ({ - getAllVariantCombinations(): any { + this.extendObject(metaClass, ({ $old }) => ({ + getAllVariantCombinations() { return [ ...$old.bind(this).getAllVariantCombinations(), - ...payload.rotationVariants.map((rotationVariant: any): any => ({ + ...payload.rotationVariants.map(rotationVariant => ({ internalId, variant, rotationVariant, @@ -483,10 +483,10 @@ export class ModInterface { }, })); // Dimensions - const $variant: any = variant; + const $variant = variant; if (payload.dimensions) { - this.extendClass(metaClass, ({ $old }: any): any => ({ - getDimensions(variant: any): any { + this.extendClass(metaClass, ({ $old }) => ({ + getDimensions(variant) { if (variant === $variant) { return payload.dimensions; } @@ -495,8 +495,8 @@ export class ModInterface { })); } if (payload.additionalStatistics) { - this.extendClass(metaClass, ({ $old }: any): any => ({ - getAdditionalStatistics(root: any, variant: any): any { + this.extendClass(metaClass, ({ $old }) => ({ + getAdditionalStatistics(root, variant) { if (variant === $variant) { return payload.additionalStatistics(root); } @@ -505,8 +505,8 @@ export class ModInterface { })); } if (payload.isUnlocked) { - this.extendClass(metaClass, ({ $old }: any): any => ({ - getAvailableVariants(root: any): any { + this.extendClass(metaClass, ({ $old }) => ({ + getAvailableVariants(root) { if (payload.isUnlocked(root)) { return [...$old.getAvailableVariants.bind(this)(root), $variant]; } @@ -515,6 +515,6 @@ export class ModInterface { })); } // Register our variant finally, with rotation variants - payload.rotationVariants.forEach((rotationVariant: any): any => shapez.registerBuildingVariant(rotationVariant ? internalId + "-" + rotationVariant : internalId, metaClass, variant, rotationVariant)); + payload.rotationVariants.forEach(rotationVariant => shapez.registerBuildingVariant(rotationVariant ? internalId + "-" + rotationVariant : internalId, metaClass, variant, rotationVariant)); } } diff --git a/src/ts/mods/mod_signals.ts b/src/ts/mods/mod_signals.ts index 9b33511a..37b63bb3 100644 --- a/src/ts/mods/mod_signals.ts +++ b/src/ts/mods/mod_signals.ts @@ -6,7 +6,7 @@ import type { InGameState } from "../states/ingame"; /* typehints:end */ import { Signal } from "../core/signal"; // Single file to avoid circular deps -export const MOD_SIGNALS: any = { +export const MOD_SIGNALS = { // Called when the application has booted and instances like the app settings etc are available appBooted: new Signal(), modifyLevelDefinitions: new Signal() as TypedSignal<[ diff --git a/src/ts/mods/modloader.ts b/src/ts/mods/modloader.ts index 18feae1b..b8d6b0e7 100644 --- a/src/ts/mods/modloader.ts +++ b/src/ts/mods/modloader.ts @@ -11,7 +11,7 @@ import { ModInterface } from "./mod_interface"; import { MOD_SIGNALS } from "./mod_signals"; import semverValidRange from "semver/ranges/valid"; import semverSatisifies from "semver/functions/satisfies"; -const LOG: any = createLogger("mods"); +const LOG = createLogger("mods"); export type ModMetadata = { name: string; version: string; @@ -39,17 +39,17 @@ export class ModLoader { constructor() { LOG.log("modloader created"); } - linkApp(app: any): any { + linkApp(app) { this.app = app; } - anyModsActive(): any { + anyModsActive() { return this.mods.length > 0; } getModsListForSavegame(): import("../savegame/savegame_typedefs").SavegameStoredMods { return this.mods - .filter((mod: any): any => !mod.metadata.doesNotAffectSavegame) - .map((mod: any): any => ({ + .filter(mod => !mod.metadata.doesNotAffectSavegame) + .map(mod => ({ id: mod.metadata.id, version: mod.metadata.version, website: mod.metadata.website, @@ -58,13 +58,13 @@ export class ModLoader { })); } - computeModDifference(originalMods: import("../savegame/savegame_typedefs").SavegameStoredMods): any { + computeModDifference(originalMods: import("../savegame/savegame_typedefs").SavegameStoredMods) { let missing: import("../savegame/savegame_typedefs").SavegameStoredMods = []; - const current: any = this.getModsListForSavegame(); - originalMods.forEach((mod: any): any => { - for (let i: any = 0; i < current.length; ++i) { - const currentMod: any = current[i]; + const current = this.getModsListForSavegame(); + originalMods.forEach(mod => { + for (let i = 0; i < current.length; ++i) { + const currentMod = current[i]; if (currentMod.id === mod.id && currentMod.version === mod.version) { current.splice(i, 1); return; @@ -77,14 +77,14 @@ export class ModLoader { extra: current, }; } - exposeExports(): any { + exposeExports() { if (G_IS_DEV || G_IS_STANDALONE) { - let exports: any = {}; - const modules: any = require.context("../", true, /\.js$/); - Array.from(modules.keys()).forEach((key: any): any => { + let exports = {}; + const modules = require.context("../", true, /\.js$/); + Array.from(modules.keys()).forEach(key => { // @ts-ignore - const module: any = modules(key); - for (const member: any in module) { + const module = modules(key); + for (const member in module) { if (member === "default" || member === "__$S__") { // Setter continue; @@ -93,10 +93,10 @@ export class ModLoader { throw new Error("Duplicate export of " + member); } Object.defineProperty(exports, member, { - get(): any { + get() { return module[member]; }, - set(v: any): any { + set(v) { module.__$S__(member, v); }, }); @@ -105,28 +105,28 @@ export class ModLoader { window.shapez = exports; } } - async initMods(): any { + async initMods() { if (!G_IS_STANDALONE && !G_IS_DEV) { this.initialized = true; return; } // Create a storage for reading mod settings - const storage: any = G_IS_STANDALONE + const storage = G_IS_STANDALONE ? new StorageImplElectron(this.app) : new StorageImplBrowserIndexedDB(this.app); await storage.initialize(); LOG.log("hook:init", this.app, this.app.storage); this.exposeExports(); - let mods: any = []; + let mods = []; if (G_IS_STANDALONE) { mods = await ipcRenderer.invoke("get-mods"); } if (G_IS_DEV && globalConfig.debug.externalModUrl) { - const modURLs: any = Array.isArray(globalConfig.debug.externalModUrl) + const modURLs = Array.isArray(globalConfig.debug.externalModUrl) ? globalConfig.debug.externalModUrl : [globalConfig.debug.externalModUrl]; - for (let i: any = 0; i < modURLs.length; i++) { - const response: any = await fetch(modURLs[i], { + for (let i = 0; i < modURLs.length; i++) { + const response = await fetch(modURLs[i], { method: "GET", }); if (response.status !== 200) { @@ -135,11 +135,11 @@ export class ModLoader { mods.push(await response.text()); } } - window.$shapez_registerMod = (modClass: any, meta: any): any => { + window.$shapez_registerMod = (modClass, meta) => { if (this.initialized) { throw new Error("Can't register mod after modloader is initialized"); } - if (this.modLoadQueue.some((entry: any): any => entry.meta.id === meta.id)) { + if (this.modLoadQueue.some(entry => entry.meta.id === meta.id)) { console.warn("Not registering mod", meta, "since a mod with the same id is already loaded"); return; } @@ -148,7 +148,7 @@ export class ModLoader { meta, }); }; - mods.forEach((modCode: any): any => { + mods.forEach(modCode => { modCode += ` if (typeof Mod !== 'undefined') { if (typeof METADATA !== 'object') { @@ -158,20 +158,20 @@ export class ModLoader { } `; try { - const func: any = new Function(modCode); + const func = new Function(modCode); func(); } - catch (ex: any) { + catch (ex) { console.error(ex); alert("Failed to parse mod (launch with --dev for more info): \n\n" + ex); } }); delete window.$shapez_registerMod; - for (let i: any = 0; i < this.modLoadQueue.length; i++) { - const { modClass, meta }: any = this.modLoadQueue[i]; - const modDataFile: any = "modsettings_" + meta.id + "__" + meta.version + ".json"; + for (let i = 0; i < this.modLoadQueue.length; i++) { + const { modClass, meta } = this.modLoadQueue[i]; + const modDataFile = "modsettings_" + meta.id + "__" + meta.version + ".json"; if (meta.minimumGameVersion) { - const minimumGameVersion: any = meta.minimumGameVersion; + const minimumGameVersion = meta.minimumGameVersion; if (!semverValidRange(minimumGameVersion)) { alert("Mod " + meta.id + " has invalid minimumGameVersion: " + minimumGameVersion); continue; @@ -187,13 +187,13 @@ export class ModLoader { continue; } } - let settings: any = meta.settings; + let settings = meta.settings; if (meta.settings) { try { - const storedSettings: any = await storage.readFileAsync(modDataFile); + const storedSettings = await storage.readFileAsync(modDataFile); settings = JSON.parse(storedSettings); } - catch (ex: any) { + catch (ex) { if (ex === FILE_NOT_FOUND) { // Write default data await storage.writeFileAsync(modDataFile, JSON.stringify(meta.settings)); @@ -204,17 +204,17 @@ export class ModLoader { } } try { - const mod: any = new modClass({ + const mod = new modClass({ app: this.app, modLoader: this, meta, settings, - saveSettings: (): any => storage.writeFileAsync(modDataFile, JSON.stringify(mod.settings)), + saveSettings: () => storage.writeFileAsync(modDataFile, JSON.stringify(mod.settings)), }); await mod.init(); this.mods.push(mod); } - catch (ex: any) { + catch (ex) { console.error(ex); alert("Failed to initialize mods (launch with --dev for more info): \n\n" + ex); } @@ -223,4 +223,4 @@ export class ModLoader { this.initialized = true; } } -export const MODS: any = new ModLoader(); +export const MODS = new ModLoader(); diff --git a/src/ts/platform/achievement_provider.ts b/src/ts/platform/achievement_provider.ts index 7e85206b..934de36f 100644 --- a/src/ts/platform/achievement_provider.ts +++ b/src/ts/platform/achievement_provider.ts @@ -8,7 +8,7 @@ import { enumAnalyticsDataSource } from "../game/production_analytics"; import { ShapeDefinition } from "../game/shape_definition"; import { ShapeItem } from "../game/items/shape_item"; import { globalConfig } from "../core/config"; -export const ACHIEVEMENTS: any = { +export const ACHIEVEMENTS = { belt500Tiles: "belt500Tiles", blueprint100k: "blueprint100k", blueprint1m: "blueprint1m", @@ -56,20 +56,20 @@ export const ACHIEVEMENTS: any = { upgradesTier8: "upgradesTier8", }; const DARK_MODE: keyof typeof THEMES = "dark"; -const HOUR_1: any = 3600; // Seconds -const HOUR_10: any = HOUR_1 * 10; -const HOUR_20: any = HOUR_1 * 20; -const ITEM_SHAPE: any = ShapeItem.getId(); -const MINUTE_30: any = 1800; // Seconds -const MINUTE_60: any = MINUTE_30 * 2; -const MINUTE_120: any = MINUTE_30 * 4; -const ROTATER_CCW_CODE: any = 12; -const ROTATER_180_CODE: any = 13; -const SHAPE_BP: any = "CbCbCbRb:CwCwCwCw"; -const SHAPE_LOGO: any = "RuCw--Cw:----Ru--"; -const SHAPE_MS_LOGO: any = "RgRyRbRr"; -const SHAPE_OLD_LEVEL_17: any = "WrRgWrRg:CwCrCwCr:SgSgSgSg"; -const SHAPE_ROCKET: any = "CbCuCbCu:Sr------:--CrSrCr:CwCwCwCw"; +const HOUR_1 = 3600; // Seconds +const HOUR_10 = HOUR_1 * 10; +const HOUR_20 = HOUR_1 * 20; +const ITEM_SHAPE = ShapeItem.getId(); +const MINUTE_30 = 1800; // Seconds +const MINUTE_60 = MINUTE_30 * 2; +const MINUTE_120 = MINUTE_30 * 4; +const ROTATER_CCW_CODE = 12; +const ROTATER_180_CODE = 13; +const SHAPE_BP = "CbCbCbRb:CwCwCwCw"; +const SHAPE_LOGO = "RuCw--Cw:----Ru--"; +const SHAPE_MS_LOGO = "RgRyRbRr"; +const SHAPE_OLD_LEVEL_17 = "WrRgWrRg:CwCrCwCr:SgSgSgSg"; +const SHAPE_ROCKET = "CbCuCbCu:Sr------:--CrSrCr:CwCwCwCw"; const WIRE_LAYER: Layer = "wires"; export class AchievementProviderInterface { /* typehints:start */ @@ -130,11 +130,11 @@ export class Achievement { constructor(key) { } - init(): any { } - isValid(): any { + init() { } + isValid() { return true; } - unlock(): any { + unlock() { if (!this.activatePromise) { this.activatePromise = this.activate(this.key); } @@ -238,11 +238,11 @@ export class AchievementCollection { this.add(ACHIEVEMENTS.upgradesTier5, this.createUpgradeOptions(5)); this.add(ACHIEVEMENTS.upgradesTier8, this.createUpgradeOptions(8)); } - initialize(root: GameRoot): any { + initialize(root: GameRoot) { this.root = root; this.root.signals.achievementCheck.add(this.unlock, this); this.root.signals.bulkAchievementCheck.add(this.bulkUnlock, this); - for (let [key, achievement]: any of this.map.entries()) { + for (let [key, achievement] of this.map.entries()) { if (achievement.signal) { achievement.receiver = this.unlock.bind(this, key); this.root.signals[achievement.signal].add(achievement.receiver); @@ -260,11 +260,11 @@ export class AchievementCollection { init: function; isValid: function; signal: string; - } = {}): any { + } = {}) { if (G_IS_DEV) { assert(ACHIEVEMENTS[key], "Achievement key not found: ", key); } - const achievement: any = new Achievement(key); + const achievement = new Achievement(key); achievement.activate = this.activate; if (options.init) { achievement.init = options.init.bind(this, achievement); @@ -277,25 +277,25 @@ export class AchievementCollection { } this.map.set(key, achievement); } - bulkUnlock(): any { - for (let i: any = 0; i < arguments.length; i += 2) { + bulkUnlock() { + for (let i = 0; i < arguments.length; i += 2) { this.unlock(arguments[i], arguments[i + 1]); } } - unlock(key: string, data: any): any { + unlock(key: string, data: any) { if (!this.map.has(key)) { return; } - const achievement: any = this.map.get(key); + const achievement = this.map.get(key); if (!achievement.isValid(data)) { return; } achievement .unlock() - .then((): any => { + .then(() => { this.onActivate(null, key); }) - .catch((err: any): any => { + .catch(err => { this.onActivate(err, key); }); } @@ -303,14 +303,14 @@ export class AchievementCollection { * Cleans up after achievement activation attempt with the provider. Could * utilize err to retry some number of times if needed. */ - onActivate(err: ?Error, key: string): any { + onActivate(err: ?Error, key: string) { this.remove(key); if (!this.hasDefaultReceivers()) { this.root.signals.achievementCheck.remove(this.unlock); } } - remove(key: string): any { - const achievement: any = this.map.get(key); + remove(key: string) { + const achievement = this.map.get(key); if (achievement) { if (achievement.receiver) { this.root.signals[achievement.signal].remove(achievement.receiver); @@ -322,11 +322,11 @@ export class AchievementCollection { * Check if the collection-level achievementCheck receivers are still * necessary. */ - hasDefaultReceivers(): any { + hasDefaultReceivers() { if (!this.map.size) { return false; } - for (let achievement: any of this.map.values()) { + for (let achievement of this.map.values()) { if (!achievement.signal) { return true; } @@ -337,9 +337,9 @@ export class AchievementCollection { * Remaining methods exist to extend Achievement instances within the * collection. */ - hasAllUpgradesAtLeastAtTier(tier: any): any { - const upgrades: any = this.root.gameMode.getUpgrades(); - for (let upgradeId: any in upgrades) { + hasAllUpgradesAtLeastAtTier(tier) { + const upgrades = this.root.gameMode.getUpgrades(); + for (let upgradeId in upgrades) { if (this.root.hubGoals.getUpgradeLevel(upgradeId) < tier - 1) { return false; } @@ -352,50 +352,50 @@ export class AchievementCollection { isShape(item: ShapeItem, shape: string): boolean { return item.getItemType() === ITEM_SHAPE && item.definition.getHash() === shape; } - createBlueprintOptions(count: any): any { + createBlueprintOptions(count) { return { - init: ({ key }: any): any => this.unlock(key, ShapeDefinition.fromShortKey(SHAPE_BP)), - isValid: (definition: any): any => definition.cachedHash === SHAPE_BP && this.root.hubGoals.storedShapes[SHAPE_BP] >= count, + init: ({ key }) => this.unlock(key, ShapeDefinition.fromShortKey(SHAPE_BP)), + isValid: definition => definition.cachedHash === SHAPE_BP && this.root.hubGoals.storedShapes[SHAPE_BP] >= count, signal: "shapeDelivered", }; } - createLevelOptions(level: any): any { + createLevelOptions(level) { return { - init: ({ key }: any): any => this.unlock(key, this.root.hubGoals.level), - isValid: (currentLevel: any): any => currentLevel > level, + init: ({ key }) => this.unlock(key, this.root.hubGoals.level), + isValid: currentLevel => currentLevel > level, signal: "storyGoalCompleted", }; } - createRateOptions(shape: any, rate: any): any { + createRateOptions(shape, rate) { return { - isValid: (): any => { + isValid: () => { return (this.root.productionAnalytics.getCurrentShapeRateRaw(enumAnalyticsDataSource.delivered, this.root.shapeDefinitionMgr.getShapeFromShortKey(shape)) / globalConfig.analyticsSliceDurationSeconds >= rate); }, }; } - createShapeOptions(shape: any): any { + createShapeOptions(shape) { return { - isValid: (item: any): any => this.isShape(item, shape), + isValid: item => this.isShape(item, shape), signal: "itemProduced", }; } - createSpeedOptions(level: any, time: any): any { + createSpeedOptions(level, time) { return { - isValid: (currentLevel: any): any => currentLevel >= level && this.root.time.now() < time, + isValid: currentLevel => currentLevel >= level && this.root.time.now() < time, signal: "storyGoalCompleted", }; } - createTimeOptions(duration: any): any { + createTimeOptions(duration) { return { - isValid: (): any => this.root.time.now() >= duration, + isValid: () => this.root.time.now() >= duration, }; } - createUpgradeOptions(tier: any): any { + createUpgradeOptions(tier) { return { - init: ({ key }: any): any => this.unlock(key, null), - isValid: (): any => this.hasAllUpgradesAtLeastAtTier(tier), + init: ({ key }) => this.unlock(key, null), + isValid: () => this.hasAllUpgradesAtLeastAtTier(tier), signal: "upgradePurchased", }; } @@ -413,17 +413,17 @@ export class AchievementCollection { } /** {} */ isIrrelevantShapeValid(definition: ShapeDefinition): boolean { - const levels: any = this.root.gameMode.getLevelDefinitions(); - for (let i: any = 0; i < levels.length; i++) { + const levels = this.root.gameMode.getLevelDefinitions(); + for (let i = 0; i < levels.length; i++) { if (definition.cachedHash === levels[i].shape) { return false; } } - const upgrades: any = this.root.gameMode.getUpgrades(); - for (let upgradeId: any in upgrades) { - for (const tier: any in upgrades[upgradeId]) { - const requiredShapes: any = upgrades[upgradeId][tier].required; - for (let i: any = 0; i < requiredShapes.length; i++) { + const upgrades = this.root.gameMode.getUpgrades(); + for (let upgradeId in upgrades) { + for (const tier in upgrades[upgradeId]) { + const requiredShapes = upgrades[upgradeId][tier].required; + for (let i = 0; i < requiredShapes.length; i++) { if (definition.cachedHash === requiredShapes[i].shape) { return false; } @@ -450,14 +450,14 @@ export class AchievementCollection { isNoBeltUpgradesUntilBpValid(level: number): boolean { return level >= 12 && this.root.hubGoals.upgradeLevels.belt === 0; } - initNoInverseRotater(): any { + initNoInverseRotater() { if (this.root.savegame.currentData.stats.usedInverseRotater === true) { return; } - const entities: any = this.root.entityMgr.componentToEntity.StaticMapEntity; - let usedInverseRotater: any = false; - for (var i: any = 0; i < entities.length; i++) { - const entity: any = entities[i].components.StaticMapEntity; + const entities = this.root.entityMgr.componentToEntity.StaticMapEntity; + let usedInverseRotater = false; + for (var i = 0; i < entities.length; i++) { + const entity = entities[i].components.StaticMapEntity; if (entity.code === ROTATER_CCW_CODE || entity.code === ROTATER_180_CODE) { usedInverseRotater = true; break; @@ -491,30 +491,30 @@ export class AchievementCollection { isStack4LayersValid(item: ShapeItem): boolean { return item.getItemType() === ITEM_SHAPE && item.definition.layers.length === 4; } - initStore100Unique({ key }: Achievement): any { + initStore100Unique({ key }: Achievement) { this.unlock(key, null); } /** {} */ isStore100UniqueValid(): boolean { return Object.keys(this.root.hubGoals.storedShapes).length >= 100; } - initStoreShape({ key }: Achievement): any { + initStoreShape({ key }: Achievement) { this.unlock(key, null); } /** {} */ isStoreShapeValid(): boolean { - const entities: any = this.root.systemMgr.systems.storage.allEntities; + const entities = this.root.systemMgr.systems.storage.allEntities; if (entities.length === 0) { return false; } - for (var i: any = 0; i < entities.length; i++) { + for (var i = 0; i < entities.length; i++) { if (entities[i].components.Storage.storedCount > 0) { return true; } } return false; } - initTrash1000({ key }: Achievement): any { + initTrash1000({ key }: Achievement) { if (Number(this.root.savegame.currentData.stats.trashedCount)) { this.unlock(key, 0); return; diff --git a/src/ts/platform/ad_provider.ts b/src/ts/platform/ad_provider.ts index e9c5021a..0ff69528 100644 --- a/src/ts/platform/ad_provider.ts +++ b/src/ts/platform/ad_provider.ts @@ -39,5 +39,5 @@ export class AdProviderInterface { showVideoAd(): Promise { return Promise.resolve(); } - setPlayStatus(playing: any): any { } + setPlayStatus(playing) { } } diff --git a/src/ts/platform/ad_providers/adinplay.ts b/src/ts/platform/ad_providers/adinplay.ts index 64cdb703..b5df74e0 100644 --- a/src/ts/platform/ad_providers/adinplay.ts +++ b/src/ts/platform/ad_providers/adinplay.ts @@ -6,8 +6,8 @@ import { createLogger } from "../../core/logging"; import { ClickDetector } from "../../core/click_detector"; import { clamp } from "../../core/utils"; import { T } from "../../translations"; -const logger: any = createLogger("adprovider/adinplay"); -const minimumTimeBetweenVideoAdsMs: any = G_IS_DEV ? 1 : 15 * 60 * 1000; +const logger = createLogger("adprovider/adinplay"); +const minimumTimeBetweenVideoAdsMs = G_IS_DEV ? 1 : 15 * 60 * 1000; export class AdinplayAdProvider extends AdProviderInterface { public getOnSteamClickDetector: ClickDetector = null; public adContainerMainElement: Element = null; @@ -18,15 +18,15 @@ export class AdinplayAdProvider extends AdProviderInterface { constructor(app) { super(app); } - getHasAds(): any { + getHasAds() { return true; } - getCanShowVideoAd(): any { + getCanShowVideoAd() { return (this.getHasAds() && !this.videoAdResolveFunction && performance.now() - this.lastVideoAdShowTime > minimumTimeBetweenVideoAdsMs); } - initialize(): any { + initialize() { // No point to initialize everything if ads are not supported if (!this.getHasAds()) { return Promise.resolve(); @@ -43,7 +43,7 @@ export class AdinplayAdProvider extends AdProviderInterface { `; // Add the setup script - const setupScript: any = document.createElement("script"); + const setupScript = document.createElement("script"); setupScript.textContent = ` var aiptag = aiptag || {}; aiptag.cmd = aiptag.cmd || []; @@ -54,34 +54,34 @@ export class AdinplayAdProvider extends AdProviderInterface { window.aiptag.gdprShowConsentTool = 0; window.aiptag.gdprAlternativeConsentTool = 1; window.aiptag.gdprConsent = 1; - const scale: any = this.app.getEffectiveUiScale(); - const targetW: any = 960; - const targetH: any = 540; - const maxScaleX: any = (window.innerWidth - 100 * scale) / targetW; - const maxScaleY: any = (window.innerHeight - 150 * scale) / targetH; - const scaleFactor: any = clamp(Math.min(maxScaleX, maxScaleY), 0.25, 2); - const w: any = Math.round(targetW * scaleFactor); - const h: any = Math.round(targetH * scaleFactor); + const scale = this.app.getEffectiveUiScale(); + const targetW = 960; + const targetH = 540; + const maxScaleX = (window.innerWidth - 100 * scale) / targetW; + const maxScaleY = (window.innerHeight - 150 * scale) / targetH; + const scaleFactor = clamp(Math.min(maxScaleX, maxScaleY), 0.25, 2); + const w = Math.round(targetW * scaleFactor); + const h = Math.round(targetH * scaleFactor); // Add the player - const videoElement: any = this.adContainerMainElement.querySelector(".videoInner"); + const videoElement = this.adContainerMainElement.querySelector(".videoInner"); const adInnerElement: HTMLElement = this.adContainerMainElement.querySelector(".adInner"); adInnerElement.style.maxWidth = w + "px"; - const self: any = this; - window.aiptag.cmd.player.push(function (): any { + const self = this; + window.aiptag.cmd.player.push(function () { window.adPlayer = new window.aipPlayer({ AD_WIDTH: w, AD_HEIGHT: h, AD_FULLSCREEN: false, AD_CENTERPLAYER: false, LOADING_TEXT: T.global.loading, - PREROLL_ELEM: function (): any { + PREROLL_ELEM: function () { return videoElement; }, - AIP_COMPLETE: function (): any { + AIP_COMPLETE: function () { logger.log("🎬 ADINPLAY AD: completed"); self.adContainerMainElement.classList.add("waitingForFinish"); }, - AIP_REMOVE: function (): any { + AIP_REMOVE: function () { logger.log("🎬 ADINPLAY AD: remove"); if (self.videoAdResolveFunction) { self.videoAdResolveFunction(); @@ -90,13 +90,13 @@ export class AdinplayAdProvider extends AdProviderInterface { }); }); // Load the ads - const aipScript: any = document.createElement("script"); + const aipScript = document.createElement("script"); aipScript.src = "https://api.adinplay.com/libs/aiptag/pub/YRG/shapez.io/tag.min.js"; aipScript.setAttribute("async", ""); document.head.appendChild(aipScript); return Promise.resolve(); } - showVideoAd(): any { + showVideoAd() { assert(this.getHasAds(), "Called showVideoAd but ads are not supported!"); assert(!this.videoAdResolveFunction, "Video ad still running, can not show again!"); this.lastVideoAdShowTime = performance.now(); @@ -105,20 +105,20 @@ export class AdinplayAdProvider extends AdProviderInterface { this.adContainerMainElement.classList.remove("waitingForFinish"); try { // @ts-ignore - window.aiptag.cmd.player.push(function (): any { + window.aiptag.cmd.player.push(function () { console.log("🎬 ADINPLAY AD: Start pre roll"); window.adPlayer.startPreRoll(); }); } - catch (ex: any) { + catch (ex) { logger.warn("🎬 Failed to play video ad:", ex); document.body.removeChild(this.adContainerMainElement); this.adContainerMainElement.classList.remove("visible"); return Promise.resolve(); } - return new Promise((resolve: any): any => { + return new Promise(resolve => { // So, wait for the remove call but also remove after N seconds - this.videoAdResolveFunction = (): any => { + this.videoAdResolveFunction = () => { this.videoAdResolveFunction = null; clearTimeout(this.videoAdResolveTimer); this.videoAdResolveTimer = null; @@ -126,17 +126,17 @@ export class AdinplayAdProvider extends AdProviderInterface { this.lastVideoAdShowTime = performance.now(); resolve(); }; - this.videoAdResolveTimer = setTimeout((): any => { + this.videoAdResolveTimer = setTimeout(() => { logger.warn(this, "Automatically closing ad after not receiving callback"); if (this.videoAdResolveFunction) { this.videoAdResolveFunction(); } }, 120 * 1000); }) - .catch((err: any): any => { + .catch(err => { logger.error("Error while resolving video ad:", err); }) - .then((): any => { + .then(() => { document.body.removeChild(this.adContainerMainElement); this.adContainerMainElement.classList.remove("visible"); }); diff --git a/src/ts/platform/ad_providers/crazygames.ts b/src/ts/platform/ad_providers/crazygames.ts index be23453e..525b2b11 100644 --- a/src/ts/platform/ad_providers/crazygames.ts +++ b/src/ts/platform/ad_providers/crazygames.ts @@ -1,55 +1,55 @@ import { AdProviderInterface } from "../ad_provider"; import { createLogger } from "../../core/logging"; import { timeoutPromise } from "../../core/utils"; -const logger: any = createLogger("crazygames"); +const logger = createLogger("crazygames"); export class CrazygamesAdProvider extends AdProviderInterface { - getHasAds(): any { + getHasAds() { return true; } - getCanShowVideoAd(): any { + getCanShowVideoAd() { return this.getHasAds() && this.sdkInstance; } get sdkInstance() { try { return window.CrazyGames.CrazySDK.getInstance(); } - catch (ex: any) { + catch (ex) { return null; } } - initialize(): any { + initialize() { if (!this.getHasAds()) { return Promise.resolve(); } logger.log("🎬 Initializing crazygames SDK"); - const scriptTag: any = document.createElement("script"); + const scriptTag = document.createElement("script"); scriptTag.type = "text/javascript"; - return timeoutPromise(new Promise((resolve: any, reject: any): any => { + return timeoutPromise(new Promise((resolve, reject) => { scriptTag.onload = resolve; scriptTag.onerror = reject; scriptTag.src = "https://sdk.crazygames.com/crazygames-sdk-v1.js"; document.head.appendChild(scriptTag); }) - .then((): any => { + .then(() => { logger.log("🎬 Crazygames SDK loaded, now initializing"); this.sdkInstance.init(); }) - .catch((ex: any): any => { + .catch(ex => { console.warn("Failed to init crazygames SDK:", ex); })); } - showVideoAd(): any { - const instance: any = this.sdkInstance; + showVideoAd() { + const instance = this.sdkInstance; if (!instance) { return Promise.resolve(); } logger.log("Set sound volume to 0"); this.app.sound.setMusicVolume(0); this.app.sound.setSoundVolume(0); - return timeoutPromise(new Promise((resolve: any): any => { + return timeoutPromise(new Promise(resolve => { console.log("🎬 crazygames: Start ad"); document.body.classList.add("externalAdOpen"); - const finish: any = (): any => { + const finish = () => { instance.removeEventListener("adError", finish); instance.removeEventListener("adFinished", finish); resolve(); @@ -58,17 +58,17 @@ export class CrazygamesAdProvider extends AdProviderInterface { instance.addEventListener("adFinished", finish); instance.requestAd(); }), 60000) - .catch((ex: any): any => { + .catch(ex => { console.warn("Error while resolving video ad:", ex); }) - .then((): any => { + .then(() => { document.body.classList.remove("externalAdOpen"); logger.log("Restored sound volume"); this.app.sound.setMusicVolume(this.app.settings.getSetting("musicVolume")); this.app.sound.setSoundVolume(this.app.settings.getSetting("soundVolume")); }); } - setPlayStatus(playing: any): any { + setPlayStatus(playing) { console.log("crazygames::playing:", playing); if (playing) { this.sdkInstance.gameplayStart(); diff --git a/src/ts/platform/ad_providers/gamedistribution.ts b/src/ts/platform/ad_providers/gamedistribution.ts index a5c72610..1f641900 100644 --- a/src/ts/platform/ad_providers/gamedistribution.ts +++ b/src/ts/platform/ad_providers/gamedistribution.ts @@ -3,8 +3,8 @@ import type { Application } from "../../application"; /* typehints:end */ import { AdProviderInterface } from "../ad_provider"; import { createLogger } from "../../core/logging"; -const minimumTimeBetweenVideoAdsMs: any = G_IS_DEV ? 1 : 5 * 60 * 1000; -const logger: any = createLogger("gamedistribution"); +const minimumTimeBetweenVideoAdsMs = G_IS_DEV ? 1 : 5 * 60 * 1000; +const logger = createLogger("gamedistribution"); export class GamedistributionAdProvider extends AdProviderInterface { public videoAdResolveFunction: Function = null; public videoAdResolveTimer = null; @@ -13,15 +13,15 @@ export class GamedistributionAdProvider extends AdProviderInterface { constructor(app) { super(app); } - getHasAds(): any { + getHasAds() { return true; } - getCanShowVideoAd(): any { + getCanShowVideoAd() { return (this.getHasAds() && !this.videoAdResolveFunction && performance.now() - this.lastVideoAdShowTime > minimumTimeBetweenVideoAdsMs); } - initialize(): any { + initialize() { // No point to initialize everything if ads are not supported if (!this.getHasAds()) { return Promise.resolve(); @@ -30,10 +30,10 @@ export class GamedistributionAdProvider extends AdProviderInterface { try { parent.postMessage("shapezio://gd.game_loaded", "*"); } - catch (ex: any) { + catch (ex) { return Promise.reject("Frame communication not allowed"); } - window.addEventListener("message", (event: any): any => { + window.addEventListener("message", event => { if (event.data === "shapezio://gd.ad_started") { console.log("🎬 Got ad started callback"); } @@ -46,7 +46,7 @@ export class GamedistributionAdProvider extends AdProviderInterface { }, false); return Promise.resolve(); } - showVideoAd(): any { + showVideoAd() { assert(this.getHasAds(), "Called showVideoAd but ads are not supported!"); assert(!this.videoAdResolveFunction, "Video ad still running, can not show again!"); this.lastVideoAdShowTime = performance.now(); @@ -54,7 +54,7 @@ export class GamedistributionAdProvider extends AdProviderInterface { try { parent.postMessage("shapezio://gd.show_ad", "*"); } - catch (ex: any) { + catch (ex) { logger.warn("🎬 Failed to send message for gd ad:", ex); return Promise.resolve(); } @@ -62,9 +62,9 @@ export class GamedistributionAdProvider extends AdProviderInterface { logger.log("Set sound volume to 0"); this.app.sound.setMusicVolume(0); this.app.sound.setSoundVolume(0); - return new Promise((resolve: any): any => { + return new Promise(resolve => { // So, wait for the remove call but also remove after N seconds - this.videoAdResolveFunction = (): any => { + this.videoAdResolveFunction = () => { this.videoAdResolveFunction = null; clearTimeout(this.videoAdResolveTimer); this.videoAdResolveTimer = null; @@ -72,17 +72,17 @@ export class GamedistributionAdProvider extends AdProviderInterface { this.lastVideoAdShowTime = performance.now(); resolve(); }; - this.videoAdResolveTimer = setTimeout((): any => { + this.videoAdResolveTimer = setTimeout(() => { logger.warn("Automatically closing ad after not receiving callback"); if (this.videoAdResolveFunction) { this.videoAdResolveFunction(); } }, 35000); }) - .catch((err: any): any => { + .catch(err => { logger.error(this, "Error while resolving video ad:", err); }) - .then((): any => { + .then(() => { document.body.classList.remove("externalAdOpen"); logger.log("Restored sound volume"); this.app.sound.setMusicVolume(this.app.settings.getSetting("musicVolume")); diff --git a/src/ts/platform/ad_providers/no_ad_provider.ts b/src/ts/platform/ad_providers/no_ad_provider.ts index d5cfecf5..fe5ec169 100644 --- a/src/ts/platform/ad_providers/no_ad_provider.ts +++ b/src/ts/platform/ad_providers/no_ad_provider.ts @@ -1,9 +1,9 @@ import { AdProviderInterface } from "../ad_provider"; export class NoAdProvider extends AdProviderInterface { - getHasAds(): any { + getHasAds() { return false; } - getCanShowVideoAd(): any { + getCanShowVideoAd() { return false; } } diff --git a/src/ts/platform/analytics.ts b/src/ts/platform/analytics.ts index e71d0906..db7c42d3 100644 --- a/src/ts/platform/analytics.ts +++ b/src/ts/platform/analytics.ts @@ -18,15 +18,15 @@ export class AnalyticsInterface { /** * Sets the player name for analytics */ - setUserContext(userName: string): any { } + setUserContext(userName: string) { } /** * Tracks when a new state is entered */ - trackStateEnter(stateId: string): any { } + trackStateEnter(stateId: string) { } /** * Tracks a new user decision */ - trackDecision(name: string): any { } + trackDecision(name: string) { } // LEGACY 1.5.3 - trackUiClick(): any { } + trackUiClick() { } } diff --git a/src/ts/platform/api.ts b/src/ts/platform/api.ts index 79ece34e..18b4b685 100644 --- a/src/ts/platform/api.ts +++ b/src/ts/platform/api.ts @@ -5,14 +5,14 @@ import { createLogger } from "../core/logging"; import { compressX64 } from "../core/lzstring"; import { timeoutPromise } from "../core/utils"; import { T } from "../translations"; -const logger: any = createLogger("puzzle-api"); +const logger = createLogger("puzzle-api"); export class ClientAPI { public app = app; public token: string | null = null; constructor(app) { } - getEndpoint(): any { + getEndpoint() { if (G_IS_DEV) { return "http://localhost:15001"; } @@ -21,14 +21,14 @@ export class ClientAPI { } return "https://api.shapez.io"; } - isLoggedIn(): any { + isLoggedIn() { return Boolean(this.token); } _request(endpoint: string, options: { method: "GET" | "POST"=; body: any=; - }): any { - const headers: any = { + }) { + const headers = { "x-api-key": "d5c54aaa491f200709afff082c153ef2", "Content-Type": "application/json", }; @@ -42,32 +42,32 @@ export class ClientAPI { method: options.method || "GET", body: options.body ? JSON.stringify(options.body) : undefined, }), 15000) - .then((res: any): any => { + .then(res => { if (res.status !== 200) { throw "bad-status: " + res.status + " / " + res.statusText; } return res; }) - .then((res: any): any => res.json()) - .then((data: any): any => { + .then(res => res.json()) + .then(data => { if (data && data.error) { logger.warn("Got error from api:", data); throw T.backendErrors[data.error] || data.error; } return data; }) - .catch((err: any): any => { + .catch(err => { logger.warn("Failure:", endpoint, ":", err); throw err; }); } - tryLogin(): any { + tryLogin() { return this.apiTryLogin() - .then(({ token }: any): any => { + .then(({ token }) => { this.token = token; return true; }) - .catch((err: any): any => { + .catch(err => { logger.warn("Failed to login:", err); return false; }); @@ -79,14 +79,14 @@ export class ClientAPI { token: string; }> { if (!G_IS_STANDALONE) { - let token: any = window.localStorage.getItem("steam_sso_auth_token"); + let token = window.localStorage.getItem("steam_sso_auth_token"); if (!token && G_IS_DEV) { token = window.prompt("Please enter the auth token for the puzzle DLC (If you have none, you can't login):"); window.localStorage.setItem("dev_api_auth_token", token); } return Promise.resolve({ token }); } - return timeoutPromise(ipcRenderer.invoke("steam:get-ticket"), 15000).then((ticket: any): any => { + return timeoutPromise(ipcRenderer.invoke("steam:get-ticket"), 15000).then(ticket => { logger.log("Got auth ticket:", ticket); return this._request("/v1/public/login", { method: "POST", @@ -94,7 +94,7 @@ export class ClientAPI { token: ticket, }, }); - }, (err: any): any => { + }, err => { logger.error("Failed to get auth ticket from steam: ", err); throw err; }); @@ -147,7 +147,7 @@ export class ClientAPI { /** * {} */ - apiReportPuzzle(puzzleId: number, reason: any): Promise { + apiReportPuzzle(puzzleId: number, reason): Promise { if (!this.isLoggedIn()) { return Promise.reject("not-logged-in"); } diff --git a/src/ts/platform/browser/game_analytics.ts b/src/ts/platform/browser/game_analytics.ts index 9ccde8fd..5e37a1e6 100644 --- a/src/ts/platform/browser/game_analytics.ts +++ b/src/ts/platform/browser/game_analytics.ts @@ -11,12 +11,12 @@ import { SteamAchievementProvider } from "../electron/steam_achievement_provider import { GameAnalyticsInterface } from "../game_analytics"; import { FILE_NOT_FOUND } from "../storage"; import { WEB_STEAM_SSO_AUTHENTICATED } from "../../core/steam_sso"; -const logger: any = createLogger("game_analytics"); -const analyticsUrl: any = G_IS_DEV ? "http://localhost:8001" : "https://analytics.shapez.io"; +const logger = createLogger("game_analytics"); +const analyticsUrl = G_IS_DEV ? "http://localhost:8001" : "https://analytics.shapez.io"; // Be sure to increment the ID whenever it changes -const analyticsLocalFile: any = "shapez_token_123.bin"; -const CURRENT_ABT: any = "abt_bsl2"; -const CURRENT_ABT_COUNT: any = 1; +const analyticsLocalFile = "shapez_token_123.bin"; +const CURRENT_ABT = "abt_bsl2"; +const CURRENT_ABT_COUNT = 1; export class ShapezGameAnalytics extends GameAnalyticsInterface { public abtVariant = "0"; @@ -43,8 +43,8 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { return "beta"; } } - fetchABVariant(): any { - return this.app.storage.readFileAsync("shapez_" + CURRENT_ABT + ".bin").then((abt: any): any => { + fetchABVariant() { + return this.app.storage.readFileAsync("shapez_" + CURRENT_ABT + ".bin").then(abt => { if (typeof queryParamOptions.abtVariant === "string") { this.abtVariant = queryParamOptions.abtVariant; logger.log("Set", CURRENT_ABT, "to (OVERRIDE) ", this.abtVariant); @@ -53,7 +53,7 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { this.abtVariant = abt; logger.log("Read abtVariant:", abt); } - }, (err: any): any => { + }, err => { if (err === FILE_NOT_FOUND) { if (typeof queryParamOptions.abtVariant === "string") { this.abtVariant = queryParamOptions.abtVariant; @@ -67,7 +67,7 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { } }); } - note(action: any): any { + note(action) { if (this.app.restrictionMgr.isLimitedVersion()) { fetch("https://analytics.shapez.io/campaign/" + "action_" + @@ -84,22 +84,22 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { cache: "no-cache", referrer: "no-referrer", credentials: "omit", - }).catch((err: any): any => { }); + }).catch(err => { }); } } - noteMinor(action: any, payload: any = ""): any { } + noteMinor(action, payload = "") { } /** * {} */ initialize(): Promise { this.syncKey = null; - window.setAbt = (abt: any): any => { + window.setAbt = abt => { this.app.storage.writeFileAsync("shapez_" + CURRENT_ABT + ".bin", String(abt)); window.location.reload(); }; // Retrieve sync key from player - return this.fetchABVariant().then((): any => { - setInterval((): any => this.sendTimePoints(), 60 * 1000); + return this.fetchABVariant().then(() => { + setInterval(() => this.sendTimePoints(), 60 * 1000); if (this.app.restrictionMgr.isLimitedVersion() && !G_IS_DEV) { fetch("https://analytics.shapez.io/campaign/" + this.environment + @@ -113,22 +113,22 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { cache: "no-cache", referrer: "no-referrer", credentials: "omit", - }).catch((err: any): any => { }); + }).catch(err => { }); } - return this.app.storage.readFileAsync(analyticsLocalFile).then((syncKey: any): any => { + return this.app.storage.readFileAsync(analyticsLocalFile).then(syncKey => { this.syncKey = syncKey; logger.log("Player sync key read:", this.syncKey); - }, (error: any): any => { + }, error => { // File was not found, retrieve new key if (error === FILE_NOT_FOUND) { logger.log("Retrieving new player key"); - let authTicket: any = Promise.resolve(undefined); + let authTicket = Promise.resolve(undefined); if (G_IS_STANDALONE) { logger.log("Will retrieve auth ticket"); authTicket = ipcRenderer.invoke("steam:get-ticket"); } authTicket - .then((ticket: any): any => { + .then(ticket => { logger.log("Got ticket:", ticket); // Perform call to get a new key from the API return this.sendToApi("/v1/register", { @@ -138,10 +138,10 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { commit: G_BUILD_COMMIT_HASH, ticket, }); - }, (err: any): any => { + }, err => { logger.warn("Failed to get steam auth ticket for register:", err); }) - .then((res: any): any => { + .then(res => { // Try to read and parse the key from the api if (res.key && typeof res.key === "string" && res.key.length === 40) { this.syncKey = res.key; @@ -152,7 +152,7 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { throw new Error("Bad response from analytics server: " + res); } }) - .catch((err: any): any => { + .catch(err => { logger.error("Failed to register on analytics api:", err); }); } @@ -166,7 +166,7 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { /** * Makes sure a DLC is activated on steam */ - activateDlc(dlc: string): any { + activateDlc(dlc: string) { logger.log("Activating dlc:", dlc); return this.sendToApi("/v1/activate-dlc/" + dlc, {}); } @@ -175,8 +175,8 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { * {} */ sendToApi(endpoint: string, data: object): Promise { - return new Promise((resolve: any, reject: any): any => { - const timeout: any = setTimeout((): any => reject("Request to " + endpoint + " timed out"), 20000); + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject("Request to " + endpoint + " timed out"), 20000); fetch(analyticsUrl + endpoint, { method: "POST", mode: "cors", @@ -190,7 +190,7 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { }, body: JSON.stringify(data), }) - .then((res: any): any => { + .then(res => { clearTimeout(timeout); if (!res.ok || res.status !== 200) { reject("Fetch error: Bad status " + res.status); @@ -200,7 +200,7 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { } }) .then(resolve) - .catch((reason: any): any => { + .catch(reason => { clearTimeout(timeout); reject(reason); }); @@ -209,7 +209,7 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { /** * Sends a game event to the analytics */ - sendGameEvent(category: string, value: string): any { + sendGameEvent(category: string, value: string) { if (G_IS_DEV) { return; } @@ -217,22 +217,22 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { logger.warn("Can not send event due to missing sync key"); return; } - const gameState: any = this.app.stateMgr.currentState; + const gameState = this.app.stateMgr.currentState; if (!(gameState instanceof InGameState)) { logger.warn("Trying to send analytics event outside of ingame state"); return; } - const savegame: any = gameState.savegame; + const savegame = gameState.savegame; if (!savegame) { logger.warn("Ingame state has empty savegame"); return; } - const savegameId: any = savegame.internalId; + const savegameId = savegame.internalId; if (!gameState.core) { logger.warn("Game state has no core"); return; } - const root: any = gameState.core.root; + const root = gameState.core.root; if (!root) { logger.warn("Root is not initialized"); return; @@ -251,12 +251,12 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { version: G_BUILD_VERSION, level: root.hubGoals.level, gameDump: this.generateGameDump(root), - }).catch((err: any): any => { + }).catch(err => { console.warn("Request failed", err); }); } - sendTimePoints(): any { - const gameState: any = this.app.stateMgr.currentState; + sendTimePoints() { + const gameState = this.app.stateMgr.currentState; if (gameState instanceof InGameState) { logger.log("Syncing analytics"); this.sendGameEvent("sync", ""); @@ -265,25 +265,25 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { /** * Returns true if the shape is interesting */ - isInterestingShape(root: GameRoot, key: string): any { + isInterestingShape(root: GameRoot, key: string) { if (key === root.gameMode.getBlueprintShapeKey()) { return true; } // Check if its a story goal - const levels: any = root.gameMode.getLevelDefinitions(); - for (let i: any = 0; i < levels.length; ++i) { + const levels = root.gameMode.getLevelDefinitions(); + for (let i = 0; i < levels.length; ++i) { if (key === levels[i].shape) { return true; } } // Check if its required to unlock an upgrade - const upgrades: any = root.gameMode.getUpgrades(); - for (const upgradeKey: any in upgrades) { - const upgradeTiers: any = upgrades[upgradeKey]; - for (let i: any = 0; i < upgradeTiers.length; ++i) { - const tier: any = upgradeTiers[i]; - const required: any = tier.required; - for (let k: any = 0; k < required.length; ++k) { + const upgrades = root.gameMode.getUpgrades(); + for (const upgradeKey in upgrades) { + const upgradeTiers = upgrades[upgradeKey]; + for (let i = 0; i < upgradeTiers.length; ++i) { + const tier = upgradeTiers[i]; + const required = tier.required; + for (let k = 0; k < required.length; ++k) { if (required[k].shape === key) { return true; } @@ -295,10 +295,10 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { /** * Generates a game dump */ - generateGameDump(root: GameRoot): any { - const shapeIds: any = Object.keys(root.hubGoals.storedShapes).filter((key: any): any => this.isInterestingShape(root, key)); - let shapes: any = {}; - for (let i: any = 0; i < shapeIds.length; ++i) { + generateGameDump(root: GameRoot) { + const shapeIds = Object.keys(root.hubGoals.storedShapes).filter(key => this.isInterestingShape(root, key)); + let shapes = {}; + for (let i = 0; i < shapeIds.length; ++i) { shapes[shapeIds[i]] = root.hubGoals.storedShapes[shapeIds[i]]; } return { @@ -310,24 +310,24 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { }; } - handleGameStarted(): any { + handleGameStarted() { this.sendGameEvent("game_start", ""); } - handleGameResumed(): any { + handleGameResumed() { this.sendTimePoints(); } /** * Handles the given level completed */ - handleLevelCompleted(level: number): any { + handleLevelCompleted(level: number) { logger.log("Complete level", level); this.sendGameEvent("level_complete", "" + level); } /** * Handles the given upgrade completed */ - handleUpgradeUnlocked(id: string, level: number): any { + handleUpgradeUnlocked(id: string, level: number) { logger.log("Unlock upgrade", id, level); this.sendGameEvent("upgrade_unlock", id + "@" + level); } diff --git a/src/ts/platform/browser/google_analytics.ts b/src/ts/platform/browser/google_analytics.ts index 42249882..365e8c1f 100644 --- a/src/ts/platform/browser/google_analytics.ts +++ b/src/ts/platform/browser/google_analytics.ts @@ -1,14 +1,14 @@ import { AnalyticsInterface } from "../analytics"; import { createLogger } from "../../core/logging"; -const logger: any = createLogger("ga"); +const logger = createLogger("ga"); export class GoogleAnalyticsImpl extends AnalyticsInterface { - initialize(): any { + initialize() { this.lastUiClickTracked = -1000; - setInterval((): any => this.internalTrackAfkEvent(), 120 * 1000); + setInterval(() => this.internalTrackAfkEvent(), 120 * 1000); // Analytics is already loaded in the html return Promise.resolve(); } - setUserContext(userName: any): any { + setUserContext(userName) { try { if (window.gtag) { logger.log("📊 Setting user context:", userName); @@ -17,12 +17,12 @@ export class GoogleAnalyticsImpl extends AnalyticsInterface { }); } } - catch (ex: any) { + catch (ex) { logger.warn("📊 Failed to set user context:", ex); } } - trackStateEnter(stateId: any): any { - const nonInteractionStates: any = [ + trackStateEnter(stateId) { + const nonInteractionStates = [ "LoginState", "MainMenuState", "PreloadState", @@ -39,11 +39,11 @@ export class GoogleAnalyticsImpl extends AnalyticsInterface { }); } } - catch (ex: any) { + catch (ex) { logger.warn("📊 Failed to track state analytcis:", ex); } } - trackDecision(decisionName: any): any { + trackDecision(decisionName) { try { if (window.gtag) { logger.log("📊 Tracking decision:", decisionName); @@ -54,14 +54,14 @@ export class GoogleAnalyticsImpl extends AnalyticsInterface { }); } } - catch (ex: any) { + catch (ex) { logger.warn("📊 Failed to track state analytcis:", ex); } } /** * Tracks an event so GA keeps track of the user */ - internalTrackAfkEvent(): any { + internalTrackAfkEvent() { if (window.gtag) { window.gtag("event", "afk", { event_category: "ping", diff --git a/src/ts/platform/browser/no_achievement_provider.ts b/src/ts/platform/browser/no_achievement_provider.ts index 52c2d5b9..5db8898e 100644 --- a/src/ts/platform/browser/no_achievement_provider.ts +++ b/src/ts/platform/browser/no_achievement_provider.ts @@ -1,18 +1,18 @@ import { AchievementProviderInterface } from "../achievement_provider"; export class NoAchievementProvider extends AchievementProviderInterface { - hasAchievements(): any { + hasAchievements() { return false; } - hasLoaded(): any { + hasLoaded() { return false; } - initialize(): any { + initialize() { return Promise.resolve(); } - onLoad(): any { + onLoad() { return Promise.reject(new Error("No achievements to load")); } - activate(): any { + activate() { return Promise.resolve(); } } diff --git a/src/ts/platform/browser/sound.ts b/src/ts/platform/browser/sound.ts index 2d57fe3a..05928eec 100644 --- a/src/ts/platform/browser/sound.ts +++ b/src/ts/platform/browser/sound.ts @@ -2,21 +2,21 @@ import { MusicInstanceInterface, SoundInstanceInterface, SoundInterface, MUSIC, import { cachebust } from "../../core/cachebust"; import { createLogger } from "../../core/logging"; import { globalConfig } from "../../core/config"; -const { Howl, Howler }: any = require("howler"); -const logger: any = createLogger("sound/browser"); +const { Howl, Howler } = require("howler"); +const logger = createLogger("sound/browser"); // @ts-ignore -const sprites: any = require("../../built-temp/sfx.json"); +const sprites = require("../../built-temp/sfx.json"); class SoundSpritesContainer { public howl = null; public loadingPromise = null; constructor() { } - load(): any { + load() { if (this.loadingPromise) { return this.loadingPromise; } - return (this.loadingPromise = new Promise((resolve: any): any => { + return (this.loadingPromise = new Promise(resolve => { this.howl = new Howl({ src: cachebust("res/sounds/sfx.mp3"), sprite: sprites.sprite, @@ -25,27 +25,27 @@ class SoundSpritesContainer { volume: 0, preload: true, pool: 20, - onload: (): any => { + onload: () => { resolve(); }, - onloaderror: (id: any, err: any): any => { + onloaderror: (id, err) => { logger.warn("SFX failed to load:", id, err); this.howl = null; resolve(); }, - onplayerror: (id: any, err: any): any => { + onplayerror: (id, err) => { logger.warn("SFX failed to play:", id, err); }, }); })); } - play(volume: any, key: any): any { + play(volume, key) { if (this.howl) { - const instance: any = this.howl.play(key); + const instance = this.howl.play(key); this.howl.volume(volume, instance); } } - deinitialize(): any { + deinitialize() { if (this.howl) { this.howl.unload(); this.howl = null; @@ -62,10 +62,10 @@ class WrappedSoundInstance extends SoundInstanceInterface { load(): Promise { return this.spriteContainer.load(); } - play(volume: any): any { + play(volume) { this.spriteContainer.play(volume, this.key); } - deinitialize(): any { + deinitialize() { return this.spriteContainer.deinitialize(); } } @@ -77,8 +77,8 @@ class MusicInstance extends MusicInstanceInterface { constructor(key, url) { super(key, url); } - load(): any { - return new Promise((resolve: any, reject: any): any => { + load() { + return new Promise((resolve, reject) => { this.howl = new Howl({ src: cachebust("res/sounds/music/" + this.url + ".mp3"), autoplay: false, @@ -87,36 +87,36 @@ class MusicInstance extends MusicInstanceInterface { volume: 1, preload: true, pool: 2, - onunlock: (): any => { + onunlock: () => { if (this.playing) { logger.log("Playing music after manual unlock"); this.play(); } }, - onload: (): any => { + onload: () => { resolve(); }, - onloaderror: (id: any, err: any): any => { + onloaderror: (id, err) => { logger.warn(this, "Music", this.url, "failed to load:", id, err); this.howl = null; resolve(); }, - onplayerror: (id: any, err: any): any => { + onplayerror: (id, err) => { logger.warn(this, "Music", this.url, "failed to play:", id, err); }, }); }); } - stop(): any { + stop() { if (this.howl && this.instance) { this.playing = false; this.howl.pause(this.instance); } } - isPlaying(): any { + isPlaying() { return this.playing; } - play(volume: any): any { + play(volume) { if (this.howl) { this.playing = true; this.howl.volume(volume); @@ -128,12 +128,12 @@ class MusicInstance extends MusicInstanceInterface { } } } - setVolume(volume: any): any { + setVolume(volume) { if (this.howl) { this.howl.volume(volume); } } - deinitialize(): any { + deinitialize() { if (this.howl) { this.howl.unload(); this.howl = null; @@ -151,18 +151,18 @@ export class SoundImplBrowser extends SoundInterface { Howler.pos(0, 0, 0); super(app, WrappedSoundInstance, MusicInstance); } - initialize(): any { + initialize() { // NOTICE: We override the initialize() method here with custom logic because // we have a sound sprites instance this.sfxHandle = new SoundSpritesContainer(); // @ts-ignore - const keys: any = Object.values(SOUNDS); - keys.forEach((key: any): any => { + const keys = Object.values(SOUNDS); + keys.forEach(key => { this.sounds[key] = new WrappedSoundInstance(this.sfxHandle, key); }); - for (const musicKey: any in MUSIC) { - const musicPath: any = MUSIC[musicKey]; - const music: any = new this.musicClass(musicKey, musicPath); + for (const musicKey in MUSIC) { + const musicPath = MUSIC[musicKey]; + const music = new this.musicClass(musicKey, musicPath); this.music[musicPath] = music; } this.musicVolume = this.app.settings.getAllSettings().musicVolume; @@ -172,7 +172,7 @@ export class SoundImplBrowser extends SoundInterface { } return Promise.resolve(); } - deinitialize(): any { - return super.deinitialize().then((): any => Howler.unload()); + deinitialize() { + return super.deinitialize().then(() => Howler.unload()); } } diff --git a/src/ts/platform/browser/storage.ts b/src/ts/platform/browser/storage.ts index ee1adb96..5a46a8f5 100644 --- a/src/ts/platform/browser/storage.ts +++ b/src/ts/platform/browser/storage.ts @@ -1,9 +1,9 @@ import { FILE_NOT_FOUND, StorageInterface } from "../storage"; import { createLogger } from "../../core/logging"; -const logger: any = createLogger("storage/browser"); -const LOCAL_STORAGE_UNAVAILABLE: any = "local-storage-unavailable"; -const LOCAL_STORAGE_NO_WRITE_PERMISSION: any = "local-storage-no-write-permission"; -let randomDelay: any = (): any => 0; +const logger = createLogger("storage/browser"); +const LOCAL_STORAGE_UNAVAILABLE = "local-storage-unavailable"; +const LOCAL_STORAGE_NO_WRITE_PERMISSION = "local-storage-no-write-permission"; +let randomDelay = () => 0; if (G_IS_DEV) { // Random delay for testing // randomDelay = () => 500; @@ -14,9 +14,9 @@ export class StorageImplBrowser extends StorageInterface { constructor(app) { super(app); } - initialize(): any { + initialize() { logger.error("Using localStorage, please update to a newer browser"); - return new Promise((resolve: any, reject: any): any => { + return new Promise((resolve, reject) => { // Check for local storage availability in general if (!window.localStorage) { alert("Local storage is not available! Please upgrade to a newer browser!"); @@ -27,7 +27,7 @@ export class StorageImplBrowser extends StorageInterface { window.localStorage.setItem("storage_availability_test", "1"); window.localStorage.removeItem("storage_availability_test"); } - catch (e: any) { + catch (e) { alert("It seems we don't have permission to write to local storage! Please update your browsers settings or use a different browser!"); reject(LOCAL_STORAGE_NO_WRITE_PERMISSION); return; @@ -35,42 +35,42 @@ export class StorageImplBrowser extends StorageInterface { setTimeout(resolve, 0); }); } - writeFileAsync(filename: any, contents: any): any { + writeFileAsync(filename, contents) { if (this.currentBusyFilename === filename) { logger.warn("Attempt to write", filename, "while write process is not finished!"); } this.currentBusyFilename = filename; window.localStorage.setItem(filename, contents); - return new Promise((resolve: any, reject: any): any => { - setTimeout((): any => { + return new Promise((resolve, reject) => { + setTimeout(() => { this.currentBusyFilename = false; resolve(); }, 0); }); } - readFileAsync(filename: any): any { + readFileAsync(filename) { if (this.currentBusyFilename === filename) { logger.warn("Attempt to read", filename, "while write progress on it is ongoing!"); } - return new Promise((resolve: any, reject: any): any => { - const contents: any = window.localStorage.getItem(filename); + return new Promise((resolve, reject) => { + const contents = window.localStorage.getItem(filename); if (!contents) { // File not found - setTimeout((): any => reject(FILE_NOT_FOUND), randomDelay()); + setTimeout(() => reject(FILE_NOT_FOUND), randomDelay()); return; } // File read, simulate delay - setTimeout((): any => resolve(contents), 0); + setTimeout(() => resolve(contents), 0); }); } - deleteFileAsync(filename: any): any { + deleteFileAsync(filename) { if (this.currentBusyFilename === filename) { logger.warn("Attempt to delete", filename, "while write progres on it is ongoing!"); } this.currentBusyFilename = filename; - return new Promise((resolve: any, reject: any): any => { + return new Promise((resolve, reject) => { window.localStorage.removeItem(filename); - setTimeout((): any => { + setTimeout(() => { this.currentBusyFilename = false; resolve(); }, 0); diff --git a/src/ts/platform/browser/storage_indexed_db.ts b/src/ts/platform/browser/storage_indexed_db.ts index f2df82b3..397a3ef0 100644 --- a/src/ts/platform/browser/storage_indexed_db.ts +++ b/src/ts/platform/browser/storage_indexed_db.ts @@ -1,9 +1,9 @@ import { FILE_NOT_FOUND, StorageInterface } from "../storage"; import { createLogger } from "../../core/logging"; -const logger: any = createLogger("storage/browserIDB"); -const LOCAL_STORAGE_UNAVAILABLE: any = "local-storage-unavailable"; -const LOCAL_STORAGE_NO_WRITE_PERMISSION: any = "local-storage-no-write-permission"; -let randomDelay: any = (): any => 0; +const logger = createLogger("storage/browserIDB"); +const LOCAL_STORAGE_UNAVAILABLE = "local-storage-unavailable"; +const LOCAL_STORAGE_NO_WRITE_PERMISSION = "local-storage-no-write-permission"; +let randomDelay = () => 0; if (G_IS_DEV) { // Random delay for testing // randomDelay = () => 500; @@ -15,38 +15,38 @@ export class StorageImplBrowserIndexedDB extends StorageInterface { constructor(app) { super(app); } - initialize(): any { + initialize() { logger.log("Using indexed DB storage"); - return new Promise((resolve: any, reject: any): any => { - const request: any = window.indexedDB.open("app_storage", 10); - request.onerror = (event: any): any => { + return new Promise((resolve, reject) => { + const request = window.indexedDB.open("app_storage", 10); + request.onerror = event => { logger.error("IDB error:", event); alert("Sorry, it seems your browser has blocked the access to the storage system. This might be the case if you are browsing in private mode for example. I recommend to use google chrome or disable private browsing."); reject("Indexed DB access error"); }; // @ts-ignore - request.onsuccess = (event: any): any => resolve(event.target.result); - request.onupgradeneeded = vent: any): any => { + request.onsuccess = event => resolve(event.target.result); + request.onupgradeneeded = ent => { // @ts-ignore const database: IDBDatabase = event.target.result; - const objectStore: any = database.createObjectStore("files", { + const objectStore = database.createObjectStore("files", { keyPath: "filename", }); objectStore.createIndex("filename", "filename", { unique: true }); - objectStore.transaction.onerror = (event: any): any => { + objectStore.transaction.onerror = event => { logger.error("IDB transaction error:", event); reject("Indexed DB transaction error during migration, check console output."); }; - objectStore.transaction.oncomplete = (event: any): any => { + objectStore.transaction.oncomplete = event => { logger.log("Object store completely initialized"); resolve(database); }; }; - }).then((database: any): any => { + }).then(database => { this.database = database; }); } - writeFileAsync(filename: any, contents: any): any { + writeFileAsync(filename, contents) { if (this.currentBusyFilename === filename) { logger.warn("Attempt to write", filename, "while write process is not finished!"); } @@ -54,34 +54,34 @@ export class StorageImplBrowserIndexedDB extends StorageInterface { return Promise.reject("Storage not ready"); } this.currentBusyFilename = filename; - const transaction: any = this.database.transaction(["files"], "readwrite"); - return new Promise((resolve: any, reject: any): any => { - transaction.oncomplete = (): any => { + const transaction = this.database.transaction(["files"], "readwrite"); + return new Promise((resolve, reject) => { + transaction.oncomplete = () => { this.currentBusyFilename = null; resolve(); }; - transaction.onerror = (error: any): any => { + transaction.onerror = error => { this.currentBusyFilename = null; logger.error("Error while writing", filename, ":", error); reject(error); }; - const store: any = transaction.objectStore("files"); + const store = transaction.objectStore("files"); store.put({ filename, contents, }); }); } - readFileAsync(filename: any): any { + readFileAsync(filename) { if (!this.database) { return Promise.reject("Storage not ready"); } this.currentBusyFilename = filename; - const transaction: any = this.database.transaction(["files"], "readonly"); - return new Promise((resolve: any, reject: any): any => { - const store: any = transaction.objectStore("files"); - const request: any = store.get(filename); - request.onsuccess = (event: any): any => { + const transaction = this.database.transaction(["files"], "readonly"); + return new Promise((resolve, reject) => { + const store = transaction.objectStore("files"); + const request = store.get(filename); + request.onsuccess = event => { this.currentBusyFilename = null; if (!request.result) { reject(FILE_NOT_FOUND); @@ -89,14 +89,14 @@ export class StorageImplBrowserIndexedDB extends StorageInterface { } resolve(request.result.contents); }; - request.onerror = (error: any): any => { + request.onerror = error => { this.currentBusyFilename = null; logger.error("Error while reading", filename, ":", error); reject(error); }; }); } - deleteFileAsync(filename: any): any { + deleteFileAsync(filename) { if (this.currentBusyFilename === filename) { logger.warn("Attempt to delete", filename, "while write progres on it is ongoing!"); } @@ -104,18 +104,18 @@ export class StorageImplBrowserIndexedDB extends StorageInterface { return Promise.reject("Storage not ready"); } this.currentBusyFilename = filename; - const transaction: any = this.database.transaction(["files"], "readwrite"); - return new Promise((resolve: any, reject: any): any => { - transaction.oncomplete = (): any => { + const transaction = this.database.transaction(["files"], "readwrite"); + return new Promise((resolve, reject) => { + transaction.oncomplete = () => { this.currentBusyFilename = null; resolve(); }; - transaction.onerror = (error: any): any => { + transaction.onerror = error => { this.currentBusyFilename = null; logger.error("Error while deleting", filename, ":", error); reject(error); }; - const store: any = transaction.objectStore("files"); + const store = transaction.objectStore("files"); store.delete(filename); }); } diff --git a/src/ts/platform/browser/wrapper.ts b/src/ts/platform/browser/wrapper.ts index 03522cd3..c4dc1fe5 100644 --- a/src/ts/platform/browser/wrapper.ts +++ b/src/ts/platform/browser/wrapper.ts @@ -11,9 +11,9 @@ import { PlatformWrapperInterface } from "../wrapper"; import { NoAchievementProvider } from "./no_achievement_provider"; import { StorageImplBrowser } from "./storage"; import { StorageImplBrowserIndexedDB } from "./storage_indexed_db"; -const logger: any = createLogger("platform/browser"); +const logger = createLogger("platform/browser"); export class PlatformWrapperImplBrowser extends PlatformWrapperInterface { - initialize(): any { + initialize() { this.recaptchaTokenCallback = null; this.embedProvider = { id: "shapezio-website", @@ -22,7 +22,7 @@ export class PlatformWrapperImplBrowser extends PlatformWrapperInterface { externalLinks: true, }; if (!G_IS_STANDALONE && !WEB_STEAM_SSO_AUTHENTICATED && queryParamOptions.embedProvider) { - const providerId: any = queryParamOptions.embedProvider; + const providerId = queryParamOptions.embedProvider; this.embedProvider.iframed = true; switch (providerId) { case "armorgames": { @@ -59,12 +59,12 @@ export class PlatformWrapperImplBrowser extends PlatformWrapperInterface { } logger.log("Embed provider:", this.embedProvider.id); return this.detectStorageImplementation() - .then((): any => this.initializeAdProvider()) - .then((): any => this.initializeAchievementProvider()) - .then((): any => super.initialize()); + .then(() => this.initializeAdProvider()) + .then(() => this.initializeAchievementProvider()) + .then(() => super.initialize()); } - detectStorageImplementation(): any { - return new Promise((resolve: any): any => { + detectStorageImplementation() { + return new Promise(resolve => { logger.log("Detecting storage"); if (!window.indexedDB) { logger.log("Indexed DB not supported"); @@ -73,50 +73,50 @@ export class PlatformWrapperImplBrowser extends PlatformWrapperInterface { return; } // Try accessing the indexedb - let request: any; + let request; try { request = window.indexedDB.open("indexeddb_feature_detection", 1); } - catch (ex: any) { + catch (ex) { logger.warn("Error while opening indexed db:", ex); this.app.storage = new StorageImplBrowser(this.app); resolve(); return; } - request.onerror = (err: any): any => { + request.onerror = err => { logger.log("Indexed DB can *not* be accessed: ", err); logger.log("Using fallback to local storage"); this.app.storage = new StorageImplBrowser(this.app); resolve(); }; - request.onsuccess = (): any => { + request.onsuccess = () => { logger.log("Indexed DB *can* be accessed"); this.app.storage = new StorageImplBrowserIndexedDB(this.app); resolve(); }; }); } - getId(): any { + getId() { return "browser@" + this.embedProvider.id; } - getUiScale(): any { + getUiScale() { if (IS_MOBILE) { return 1; } - const avgDims: any = Math.min(this.app.screenWidth, this.app.screenHeight); + const avgDims = Math.min(this.app.screenWidth, this.app.screenHeight); return clamp((avgDims / 1000.0) * 1.9, 0.1, 10); } - getSupportsRestart(): any { + getSupportsRestart() { return true; } - getTouchPanStrength(): any { + getTouchPanStrength() { return IS_MOBILE ? 1 : 0.5; } - openExternalLink(url: any, force: any = false): any { + openExternalLink(url, force = false) { logger.log("Opening external:", url); window.open(url); } - performRestart(): any { + performRestart() { logger.log("Performing restart"); window.location.reload(true); } @@ -126,55 +126,55 @@ export class PlatformWrapperImplBrowser extends PlatformWrapperInterface { */ detectAdblock(): Promise { return Promise.race([ - new Promise((resolve: any): any => { + new Promise(resolve => { // If the request wasn't blocked within a very short period of time, this means // the adblocker is not active and the request was actually made -> ignore it then - setTimeout((): any => resolve(false), 30); + setTimeout(() => resolve(false), 30); }), - new Promise((resolve: any): any => { + new Promise(resolve => { fetch("https://googleads.g.doubleclick.net/pagead/id", { method: "HEAD", mode: "no-cors", }) - .then((res: any): any => { + .then(res => { resolve(false); }) - .catch((err: any): any => { + .catch(err => { resolve(true); }); }), ]); } - initializeAdProvider(): any { + initializeAdProvider() { if (G_IS_DEV && !globalConfig.debug.testAds) { logger.log("Ads disabled in local environment"); return Promise.resolve(); } // First, detect adblocker - return this.detectAdblock().then((hasAdblocker: any): any => { + return this.detectAdblock().then(hasAdblocker => { if (hasAdblocker) { logger.log("Adblock detected"); return; } - const adProvider: any = this.embedProvider.adProvider; + const adProvider = this.embedProvider.adProvider; this.app.adProvider = new adProvider(this.app); - return this.app.adProvider.initialize().catch((err: any): any => { + return this.app.adProvider.initialize().catch(err => { logger.error("Failed to initialize ad provider, disabling ads:", err); this.app.adProvider = new NoAdProvider(this.app); }); }); } - initializeAchievementProvider(): any { + initializeAchievementProvider() { if (G_IS_DEV && globalConfig.debug.testAchievements) { this.app.achievementProvider = new SteamAchievementProvider(this.app); - return this.app.achievementProvider.initialize().catch((err: any): any => { + return this.app.achievementProvider.initialize().catch(err => { logger.error("Failed to initialize achievement provider, disabling:", err); this.app.achievementProvider = new NoAchievementProvider(this.app); }); } return this.app.achievementProvider.initialize(); } - exitApp(): any { + exitApp() { // Can not exit app } } diff --git a/src/ts/platform/electron/steam_achievement_provider.ts b/src/ts/platform/electron/steam_achievement_provider.ts index 4d8d614c..bafa5833 100644 --- a/src/ts/platform/electron/steam_achievement_provider.ts +++ b/src/ts/platform/electron/steam_achievement_provider.ts @@ -4,8 +4,8 @@ import type { GameRoot } from "../../game/root"; /* typehints:end */ import { createLogger } from "../../core/logging"; import { ACHIEVEMENTS, AchievementCollection, AchievementProviderInterface } from "../achievement_provider"; -const logger: any = createLogger("achievements/steam"); -const ACHIEVEMENT_IDS: any = { +const logger = createLogger("achievements/steam"); +const ACHIEVEMENT_IDS = { [ACHIEVEMENTS.belt500Tiles]: "belt_500_tiles", [ACHIEVEMENTS.blueprint100k]: "blueprint_100k", [ACHIEVEMENTS.blueprint1m]: "blueprint_1m", @@ -59,7 +59,7 @@ export class SteamAchievementProvider extends AchievementProviderInterface { constructor(app) { super(app); if (G_IS_DEV) { - for (let key: any in ACHIEVEMENT_IDS) { + for (let key in ACHIEVEMENT_IDS) { assert(this.collection.map.has(key), "Key not found in collection: " + key); } } @@ -80,7 +80,7 @@ export class SteamAchievementProvider extends AchievementProviderInterface { logger.log("Initialized", this.collection.map.size, "relevant achievements"); return Promise.resolve(); } - catch (err: any) { + catch (err) { logger.error("Failed to initialize the collection"); return Promise.reject(err); } @@ -91,7 +91,7 @@ export class SteamAchievementProvider extends AchievementProviderInterface { logger.warn("Steam unavailable. Achievements won't sync."); return Promise.resolve(); } - return ipcRenderer.invoke("steam:is-initialized").then((initialized: any): any => { + return ipcRenderer.invoke("steam:is-initialized").then(initialized => { this.initialized = initialized; if (!this.initialized) { logger.warn("Steam failed to intialize. Achievements won't sync."); @@ -105,7 +105,7 @@ export class SteamAchievementProvider extends AchievementProviderInterface { * {} */ activate(key: string): Promise { - let promise: any; + let promise; if (!this.initialized) { promise = Promise.resolve(); } @@ -113,10 +113,10 @@ export class SteamAchievementProvider extends AchievementProviderInterface { promise = ipcRenderer.invoke("steam:activate-achievement", ACHIEVEMENT_IDS[key]); } return promise - .then((): any => { + .then(() => { logger.log("Achievement activated:", key); }) - .catch((err: any): any => { + .catch(err => { logger.error("Failed to activate achievement:", key, err); throw err; }); diff --git a/src/ts/platform/electron/storage.ts b/src/ts/platform/electron/storage.ts index a776df9d..1808b0d3 100644 --- a/src/ts/platform/electron/storage.ts +++ b/src/ts/platform/electron/storage.ts @@ -4,30 +4,30 @@ export class StorageImplElectron extends StorageInterface { constructor(app) { super(app); } - initialize(): any { + initialize() { return Promise.resolve(); } - writeFileAsync(filename: any, contents: any): any { + writeFileAsync(filename, contents) { return ipcRenderer.invoke("fs-job", { type: "write", filename, contents, }); } - readFileAsync(filename: any): any { + readFileAsync(filename) { return ipcRenderer .invoke("fs-job", { type: "read", filename, }) - .then((res: any): any => { + .then(res => { if (res && res.error === FILE_NOT_FOUND) { throw FILE_NOT_FOUND; } return res; }); } - deleteFileAsync(filename: any): any { + deleteFileAsync(filename) { return ipcRenderer.invoke("fs-job", { type: "delete", filename, diff --git a/src/ts/platform/electron/wrapper.ts b/src/ts/platform/electron/wrapper.ts index ad603935..c3cce610 100644 --- a/src/ts/platform/electron/wrapper.ts +++ b/src/ts/platform/electron/wrapper.ts @@ -4,9 +4,9 @@ import { createLogger } from "../../core/logging"; import { StorageImplElectron } from "./storage"; import { SteamAchievementProvider } from "./steam_achievement_provider"; import { PlatformWrapperInterface } from "../wrapper"; -const logger: any = createLogger("electron-wrapper"); +const logger = createLogger("electron-wrapper"); export class PlatformWrapperImplElectron extends PlatformWrapperImplBrowser { - initialize(): any { + initialize() { this.dlcs = { puzzle: false, }; @@ -20,65 +20,65 @@ export class PlatformWrapperImplElectron extends PlatformWrapperImplBrowser { this.app.storage = new StorageImplElectron(this); this.app.achievementProvider = new SteamAchievementProvider(this.app); return this.initializeAchievementProvider() - .then((): any => this.initializeDlcStatus()) - .then((): any => PlatformWrapperInterface.prototype.initialize.call(this)); + .then(() => this.initializeDlcStatus()) + .then(() => PlatformWrapperInterface.prototype.initialize.call(this)); } - steamOverlayFixRedrawCanvas(): any { + steamOverlayFixRedrawCanvas() { this.steamOverlayContextFix.clearRect(0, 0, 1, 1); } - getId(): any { + getId() { return "electron"; } - getSupportsRestart(): any { + getSupportsRestart() { return true; } - openExternalLink(url: any): any { + openExternalLink(url) { logger.log(this, "Opening external:", url); window.open(url, "about:blank"); } - getSupportsAds(): any { + getSupportsAds() { return false; } - performRestart(): any { + performRestart() { logger.log(this, "Performing restart"); window.location.reload(true); } - initializeAdProvider(): any { + initializeAdProvider() { return Promise.resolve(); } - initializeAchievementProvider(): any { - return this.app.achievementProvider.initialize().catch((err: any): any => { + initializeAchievementProvider() { + return this.app.achievementProvider.initialize().catch(err => { logger.error("Failed to initialize achievement provider, disabling:", err); this.app.achievementProvider = new NoAchievementProvider(this.app); }); } - initializeDlcStatus(): any { + initializeDlcStatus() { logger.log("Checking DLC ownership ..."); // @todo: Don't hardcode the app id - return ipcRenderer.invoke("steam:check-app-ownership", 1625400).then((res: any): any => { + return ipcRenderer.invoke("steam:check-app-ownership", 1625400).then(res => { logger.log("Got DLC ownership:", res); this.dlcs.puzzle = Boolean(res); if (this.dlcs.puzzle && !G_IS_DEV) { - this.app.gameAnalytics.activateDlc("puzzle").then((): any => { + this.app.gameAnalytics.activateDlc("puzzle").then(() => { logger.log("Puzzle DLC successfully activated"); - }, (error: any): any => { + }, error => { logger.error("Failed to activate puzzle DLC:", error); }); } - }, (err: any): any => { + }, err => { logger.error("Failed to get DLC ownership:", err); }); } - getSupportsFullscreen(): any { + getSupportsFullscreen() { return true; } - setFullscreen(flag: any): any { + setFullscreen(flag) { ipcRenderer.send("set-fullscreen", flag); } - getSupportsAppExit(): any { + getSupportsAppExit() { return true; } - exitApp(): any { + exitApp() { logger.log(this, "Sending app exit signal"); ipcRenderer.send("exit-app"); } diff --git a/src/ts/platform/game_analytics.ts b/src/ts/platform/game_analytics.ts index 2c5082fb..cf35bb50 100644 --- a/src/ts/platform/game_analytics.ts +++ b/src/ts/platform/game_analytics.ts @@ -17,24 +17,24 @@ export class GameAnalyticsInterface { /** * Handles a new game which was started */ - handleGameStarted(): any { } + handleGameStarted() { } /** * Handles a resumed game */ - handleGameResumed(): any { } + handleGameResumed() { } /** * Handles the given level completed */ - handleLevelCompleted(level: number): any { } + handleLevelCompleted(level: number) { } /** * Handles the given upgrade completed */ - handleUpgradeUnlocked(id: string, level: number): any { } + handleUpgradeUnlocked(id: string, level: number) { } /** * Activates a DLC * @abstract */ - activateDlc(dlc: string): any { + activateDlc(dlc: string) { abstract; return Promise.resolve(); } diff --git a/src/ts/platform/sound.ts b/src/ts/platform/sound.ts index 978133ed..de5ccdba 100644 --- a/src/ts/platform/sound.ts +++ b/src/ts/platform/sound.ts @@ -6,8 +6,8 @@ import type { GameRoot } from "../game/root"; import { newEmptyMap, clamp } from "../core/utils"; import { createLogger } from "../core/logging"; import { globalConfig } from "../core/config"; -const logger: any = createLogger("sound"); -export const SOUNDS: any = { +const logger = createLogger("sound"); +export const SOUNDS = { // Menu and such uiClick: "ui_click", uiError: "ui_error", @@ -24,7 +24,7 @@ export const SOUNDS: any = { unlockUpgrade: "unlock_upgrade", tutorialStep: "tutorial_step", }; -export const MUSIC: any = { +export const MUSIC = { // The theme always depends on the standalone only, even if running the full // version in the browser theme: G_IS_STANDALONE ? "theme-full" : "theme-short", @@ -46,10 +46,10 @@ export class SoundInstanceInterface { abstract; return Promise.resolve(); } - play(volume: any): any { + play(volume) { abstract; } - deinitialize(): any { } + deinitialize() { } } export class MusicInstanceInterface { public key = key; @@ -57,13 +57,13 @@ export class MusicInstanceInterface { constructor(key, url) { } - stop(): any { + stop() { abstract; } - play(volume: any): any { + play(volume) { abstract; } - setVolume(volume: any): any { + setVolume(volume) { abstract; } /** {} */ @@ -76,7 +76,7 @@ export class MusicInstanceInterface { abstract; return false; } - deinitialize(): any { } + deinitialize() { } } export class SoundInterface { public app: Application = app; @@ -100,14 +100,14 @@ export class SoundInterface { * {} */ initialize(): Promise { - for (const soundKey: any in SOUNDS) { - const soundPath: any = SOUNDS[soundKey]; - const sound: any = new this.soundClass(soundKey, soundPath); + for (const soundKey in SOUNDS) { + const soundPath = SOUNDS[soundKey]; + const sound = new this.soundClass(soundKey, soundPath); this.sounds[soundPath] = sound; } - for (const musicKey: any in MUSIC) { - const musicPath: any = MUSIC[musicKey]; - const music: any = new this.musicClass(musicKey, musicPath); + for (const musicKey in MUSIC) { + const musicPath = MUSIC[musicKey]; + const music = new this.musicClass(musicKey, musicPath); this.music[musicPath] = music; } this.musicVolume = this.app.settings.getAllSettings().musicVolume; @@ -140,11 +140,11 @@ export class SoundInterface { * {} */ deinitialize(): Promise { - const promises: any = []; - for (const key: any in this.sounds) { + const promises = []; + for (const key in this.sounds) { promises.push(this.sounds[key].deinitialize()); } - for (const key: any in this.music) { + for (const key in this.music) { promises.push(this.music[key].deinitialize()); } // @ts-ignore @@ -167,7 +167,7 @@ export class SoundInterface { /** * Sets the music volume */ - setMusicVolume(volume: number): any { + setMusicVolume(volume: number) { this.musicVolume = clamp(volume, 0, 1); if (this.currentMusic) { this.currentMusic.setVolume(this.musicVolume); @@ -176,13 +176,13 @@ export class SoundInterface { /** * Sets the sound volume */ - setSoundVolume(volume: number): any { + setSoundVolume(volume: number) { this.soundVolume = clamp(volume, 0, 1); } /** * Focus change handler, called by the pap */ - onPageRenderableStateChanged(pageIsVisible: boolean): any { + onPageRenderableStateChanged(pageIsVisible: boolean) { this.pageIsVisible = pageIsVisible; if (this.currentMusic) { if (pageIsVisible) { @@ -195,14 +195,14 @@ export class SoundInterface { } } } - playUiSound(key: string): any { + playUiSound(key: string) { if (!this.sounds[key]) { logger.warn("Sound", key, "not found, probably not loaded yet"); return; } this.sounds[key].play(this.soundVolume); } - play3DSound(key: string, worldPosition: Vector, root: GameRoot): any { + play3DSound(key: string, worldPosition: Vector, root: GameRoot) { if (!this.sounds[key]) { logger.warn("Music", key, "not found, probably not loaded yet"); return; @@ -214,15 +214,15 @@ export class SoundInterface { if (root.time.getIsPaused()) { return; } - let volume: any = this.soundVolume; + let volume = this.soundVolume; if (!root.camera.isWorldPointOnScreen(worldPosition)) { volume = this.soundVolume / 5; // In the old implementation this value was fixed to 0.2 => 20% of 1.0 } volume *= clamp(root.camera.zoomLevel / 3); this.sounds[key].play(clamp(volume)); } - playThemeMusic(key: string): any { - const music: any = this.music[key]; + playThemeMusic(key: string) { + const music = this.music[key]; if (key && !music) { logger.warn("Music", key, "not found"); } diff --git a/src/ts/platform/storage.ts b/src/ts/platform/storage.ts index f306f650..f62cfb38 100644 --- a/src/ts/platform/storage.ts +++ b/src/ts/platform/storage.ts @@ -1,7 +1,7 @@ /* typehints:start */ import type { Application } from "../application"; /* typehints:end */ -export const FILE_NOT_FOUND: any = "file_not_found"; +export const FILE_NOT_FOUND = "file_not_found"; export class StorageInterface { public app: Application = app; diff --git a/src/ts/platform/wrapper.ts b/src/ts/platform/wrapper.ts index 8c0b736a..31ea7796 100644 --- a/src/ts/platform/wrapper.ts +++ b/src/ts/platform/wrapper.ts @@ -26,7 +26,7 @@ export class PlatformWrapperInterface { /** * Returns the strength of touch pans with the mouse */ - getTouchPanStrength(): any { + getTouchPanStrength() { return 1; } /** {} */ @@ -55,59 +55,59 @@ export class PlatformWrapperInterface { getMaximumZoom(): number { return 3.5 * this.getScreenScale(); } - getScreenScale(): any { + getScreenScale() { return Math.min(window.innerWidth, window.innerHeight) / 1024.0; } /** * Should return if this platform supports ads at all */ - getSupportsAds(): any { + getSupportsAds() { return false; } /** * Attempt to open an external url * @abstract */ - openExternalLink(url: string, force: boolean= = false): any { + openExternalLink(url: string, force: boolean= = false) { abstract; } /** * Attempt to restart the app * @abstract */ - performRestart(): any { + performRestart() { abstract; } /** * Returns whether this platform supports a toggleable fullscreen */ - getSupportsFullscreen(): any { + getSupportsFullscreen() { return false; } /** * Should set the apps fullscreen state to the desired state * @abstract */ - setFullscreen(flag: boolean): any { + setFullscreen(flag: boolean) { abstract; } /** * Returns whether this platform supports quitting the app */ - getSupportsAppExit(): any { + getSupportsAppExit() { return false; } /** * Attempts to quit the app * @abstract */ - exitApp(): any { + exitApp() { abstract; } /** * Whether this platform supports a keyboard */ - getSupportsKeyboard(): any { + getSupportsKeyboard() { return !IS_MOBILE; } } diff --git a/src/ts/profile/application_settings.ts b/src/ts/profile/application_settings.ts index 7bbb4553..2d32800e 100644 --- a/src/ts/profile/application_settings.ts +++ b/src/ts/profile/application_settings.ts @@ -8,17 +8,17 @@ import { ExplainedResult } from "../core/explained_result"; import { THEMES, applyGameTheme } from "../game/theme"; import { T } from "../translations"; import { LANGUAGES } from "../languages"; -const logger: any = createLogger("application_settings"); +const logger = createLogger("application_settings"); /** * @enum {string} */ -export const enumCategories: any = { +export const enumCategories = { general: "general", userInterface: "userInterface", performance: "performance", advanced: "advanced", }; -export const uiScales: any = [ +export const uiScales = [ { id: "super_small", size: 0.6, @@ -40,7 +40,7 @@ export const uiScales: any = [ size: 1.1, }, ]; -export const scrollWheelSensitivities: any = [ +export const scrollWheelSensitivities = [ { id: "super_slow", scale: 0.25, @@ -62,7 +62,7 @@ export const scrollWheelSensitivities: any = [ scale: 4, }, ]; -export const movementSpeeds: any = [ +export const movementSpeeds = [ { id: "super_slow", multiplier: 0.25, @@ -88,7 +88,7 @@ export const movementSpeeds: any = [ multiplier: 8, }, ]; -export const autosaveIntervals: any = [ +export const autosaveIntervals = [ { id: "one_minute", seconds: 60, @@ -114,7 +114,7 @@ export const autosaveIntervals: any = [ seconds: null, }, ]; -export const refreshRateOptions: any = ["30", "60", "120", "180", "240"]; +export const refreshRateOptions = ["30", "60", "120", "180", "240"]; if (G_IS_DEV) { refreshRateOptions.unshift("10"); refreshRateOptions.unshift("5"); @@ -128,101 +128,101 @@ function initializeSettings(): Array { return [ new EnumSetting("language", { options: Object.keys(LANGUAGES), - valueGetter: (key: any): any => key, - textGetter: (key: any): any => LANGUAGES[key].name, + valueGetter: key => key, + textGetter: key => LANGUAGES[key].name, category: enumCategories.general, restartRequired: true, - changeCb: (app: any, id: any): any => null, + changeCb: (app, id) => null, magicValue: "auto-detect", }), new EnumSetting("uiScale", { - options: uiScales.sort((a: any, b: any): any => a.size - b.size), - valueGetter: (scale: any): any => scale.id, - textGetter: (scale: any): any => T.settings.labels.uiScale.scales[scale.id], + options: uiScales.sort((a, b) => a.size - b.size), + valueGetter: scale => scale.id, + textGetter: scale => T.settings.labels.uiScale.scales[scale.id], category: enumCategories.userInterface, restartRequired: false, changeCb: - (app: Application, id: any): any => app.updateAfterUiScaleChanged(), + (app: Application, id) => app.updateAfterUiScaleChanged(), }), new RangeSetting("soundVolume", enumCategories.general, - (app: Application, value: any): any => app.sound.setSoundVolume(value)), + (app: Application, value) => app.sound.setSoundVolume(value)), new RangeSetting("musicVolume", enumCategories.general, - (app: Application, value: any): any => app.sound.setMusicVolume(value)), + (app: Application, value) => app.sound.setMusicVolume(value)), new BoolSetting("fullscreen", enumCategories.general, - (app: Application, value: any): any => { + (app: Application, value) => { if (app.platformWrapper.getSupportsFullscreen()) { app.platformWrapper.setFullscreen(value); } }, - app: Application): any => G_IS_STANDALONE), + app: Application) => G_IS_STANDALONE), new BoolSetting("enableColorBlindHelper", enumCategories.general, - (app: Application, value: any): any => null), - new BoolSetting("offerHints", enumCategories.userInterface, (app: any, value: any): any => { }), + (app: Application, value) => null), + new BoolSetting("offerHints", enumCategories.userInterface, (app, value) => { }), new EnumSetting("theme", { options: Object.keys(THEMES), - valueGetter: (theme: any): any => theme, - textGetter: (theme: any): any => T.settings.labels.theme.themes[theme], + valueGetter: theme => theme, + textGetter: theme => T.settings.labels.theme.themes[theme], category: enumCategories.userInterface, restartRequired: false, changeCb: - (app: Application, id: any): any => { + (app: Application, id) => { applyGameTheme(id); document.documentElement.setAttribute("data-theme", id); }, - enabledCb: pp: Application): any => app.restrictionMgr.getHasExtendedSettings(), + enabledCb: pp: Application) => app.restrictionMgr.getHasExtendedSettings(), }), new EnumSetting("autosaveInterval", { options: autosaveIntervals, - valueGetter: (interval: any): any => interval.id, - textGetter: (interval: any): any => T.settings.labels.autosaveInterval.intervals[interval.id], + valueGetter: interval => interval.id, + textGetter: interval => T.settings.labels.autosaveInterval.intervals[interval.id], category: enumCategories.advanced, restartRequired: false, changeCb: - (app: Application, id: any): any => null, + (app: Application, id) => null, }), new EnumSetting("scrollWheelSensitivity", { - options: scrollWheelSensitivities.sort((a: any, b: any): any => a.scale - b.scale), - valueGetter: (scale: any): any => scale.id, - textGetter: (scale: any): any => T.settings.labels.scrollWheelSensitivity.sensitivity[scale.id], + options: scrollWheelSensitivities.sort((a, b) => a.scale - b.scale), + valueGetter: scale => scale.id, + textGetter: scale => T.settings.labels.scrollWheelSensitivity.sensitivity[scale.id], category: enumCategories.advanced, restartRequired: false, changeCb: - (app: Application, id: any): any => app.updateAfterUiScaleChanged(), + (app: Application, id) => app.updateAfterUiScaleChanged(), }), new EnumSetting("movementSpeed", { - options: movementSpeeds.sort((a: any, b: any): any => a.multiplier - b.multiplier), - valueGetter: (multiplier: any): any => multiplier.id, - textGetter: (multiplier: any): any => T.settings.labels.movementSpeed.speeds[multiplier.id], + options: movementSpeeds.sort((a, b) => a.multiplier - b.multiplier), + valueGetter: multiplier => multiplier.id, + textGetter: multiplier => T.settings.labels.movementSpeed.speeds[multiplier.id], category: enumCategories.advanced, restartRequired: false, - changeCb: (app: any, id: any): any => { }, + changeCb: (app, id) => { }, }), - new BoolSetting("enableMousePan", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("shapeTooltipAlwaysOn", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("alwaysMultiplace", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("zoomToCursor", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("clearCursorOnDeleteWhilePlacing", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("enableTunnelSmartplace", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("vignette", enumCategories.userInterface, (app: any, value: any): any => { }), - new BoolSetting("compactBuildingInfo", enumCategories.userInterface, (app: any, value: any): any => { }), - new BoolSetting("disableCutDeleteWarnings", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("rotationByBuilding", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("displayChunkBorders", enumCategories.advanced, (app: any, value: any): any => { }), - new BoolSetting("pickMinerOnPatch", enumCategories.advanced, (app: any, value: any): any => { }), - new RangeSetting("mapResourcesScale", enumCategories.advanced, (): any => null), + new BoolSetting("enableMousePan", enumCategories.advanced, (app, value) => { }), + new BoolSetting("shapeTooltipAlwaysOn", enumCategories.advanced, (app, value) => { }), + new BoolSetting("alwaysMultiplace", enumCategories.advanced, (app, value) => { }), + new BoolSetting("zoomToCursor", enumCategories.advanced, (app, value) => { }), + new BoolSetting("clearCursorOnDeleteWhilePlacing", enumCategories.advanced, (app, value) => { }), + new BoolSetting("enableTunnelSmartplace", enumCategories.advanced, (app, value) => { }), + new BoolSetting("vignette", enumCategories.userInterface, (app, value) => { }), + new BoolSetting("compactBuildingInfo", enumCategories.userInterface, (app, value) => { }), + new BoolSetting("disableCutDeleteWarnings", enumCategories.advanced, (app, value) => { }), + new BoolSetting("rotationByBuilding", enumCategories.advanced, (app, value) => { }), + new BoolSetting("displayChunkBorders", enumCategories.advanced, (app, value) => { }), + new BoolSetting("pickMinerOnPatch", enumCategories.advanced, (app, value) => { }), + new RangeSetting("mapResourcesScale", enumCategories.advanced, () => null), new EnumSetting("refreshRate", { options: refreshRateOptions, - valueGetter: (rate: any): any => rate, - textGetter: (rate: any): any => T.settings.tickrateHz.replace("", rate), + valueGetter: rate => rate, + textGetter: rate => T.settings.tickrateHz.replace("", rate), category: enumCategories.performance, restartRequired: false, - changeCb: (app: any, id: any): any => { }, - enabledCb: pp: Application): any => app.restrictionMgr.getHasExtendedSettings(), + changeCb: (app, id) => { }, + enabledCb: pp: Application) => app.restrictionMgr.getHasExtendedSettings(), }), - new BoolSetting("lowQualityMapResources", enumCategories.performance, (app: any, value: any): any => { }), - new BoolSetting("disableTileGrid", enumCategories.performance, (app: any, value: any): any => { }), - new BoolSetting("lowQualityTextures", enumCategories.performance, (app: any, value: any): any => { }), - new BoolSetting("simplifiedBelts", enumCategories.performance, (app: any, value: any): any => { }), + new BoolSetting("lowQualityMapResources", enumCategories.performance, (app, value) => { }), + new BoolSetting("disableTileGrid", enumCategories.performance, (app, value) => { }), + new BoolSetting("lowQualityTextures", enumCategories.performance, (app, value) => { }), + new BoolSetting("simplifiedBelts", enumCategories.performance, (app, value) => { }), ]; } class SettingsStorage { @@ -268,24 +268,24 @@ export class ApplicationSettings extends ReadWriteProxy { constructor(app) { super(app, "app_settings.bin"); } - initialize(): any { + initialize() { // Read and directly write latest data back return this.readAsync() - .then((): any => { + .then(() => { // Apply default setting callbacks - const settings: any = this.getAllSettings(); - for (let i: any = 0; i < this.settingHandles.length; ++i) { - const handle: any = this.settingHandles[i]; + const settings = this.getAllSettings(); + for (let i = 0; i < this.settingHandles.length; ++i) { + const handle = this.settingHandles[i]; handle.apply(this.app, settings[handle.id]); } }) - .then((): any => this.writeAsync()); + .then(() => this.writeAsync()); } - save(): any { + save() { return this.writeAsync(); } - getSettingHandleById(id: any): any { - return this.settingHandles.find((setting: any): any => setting.id === id); + getSettingHandleById(id) { + return this.settingHandles.find(setting => setting.id === id); } // Getters /** @@ -294,23 +294,23 @@ export class ApplicationSettings extends ReadWriteProxy { getAllSettings(): SettingsStorage { return this.currentData.settings; } - getSetting(key: string): any { + getSetting(key: string) { assert(this.getAllSettings().hasOwnProperty(key), "Setting not known: " + key); return this.getAllSettings()[key]; } - getInterfaceScaleId(): any { + getInterfaceScaleId() { if (!this.currentData) { // Not initialized yet return "regular"; } return this.getAllSettings().uiScale; } - getDesiredFps(): any { + getDesiredFps() { return parseInt(this.getAllSettings().refreshRate); } - getInterfaceScaleValue(): any { - const id: any = this.getInterfaceScaleId(); - for (let i: any = 0; i < uiScales.length; ++i) { + getInterfaceScaleValue() { + const id = this.getInterfaceScaleId(); + for (let i = 0; i < uiScales.length; ++i) { if (uiScales[i].id === id) { return uiScales[i].size; } @@ -318,9 +318,9 @@ export class ApplicationSettings extends ReadWriteProxy { logger.error("Unknown ui scale id:", id); return 1; } - getScrollWheelSensitivity(): any { - const id: any = this.getAllSettings().scrollWheelSensitivity; - for (let i: any = 0; i < scrollWheelSensitivities.length; ++i) { + getScrollWheelSensitivity() { + const id = this.getAllSettings().scrollWheelSensitivity; + for (let i = 0; i < scrollWheelSensitivities.length; ++i) { if (scrollWheelSensitivities[i].id === id) { return scrollWheelSensitivities[i].scale; } @@ -328,9 +328,9 @@ export class ApplicationSettings extends ReadWriteProxy { logger.error("Unknown scroll wheel sensitivity id:", id); return 1; } - getMovementSpeed(): any { - const id: any = this.getAllSettings().movementSpeed; - for (let i: any = 0; i < movementSpeeds.length; ++i) { + getMovementSpeed() { + const id = this.getAllSettings().movementSpeed; + for (let i = 0; i < movementSpeeds.length; ++i) { if (movementSpeeds[i].id === id) { return movementSpeeds[i].multiplier; } @@ -338,9 +338,9 @@ export class ApplicationSettings extends ReadWriteProxy { logger.error("Unknown movement speed id:", id); return 1; } - getAutosaveIntervalSeconds(): any { - const id: any = this.getAllSettings().autosaveInterval; - for (let i: any = 0; i < autosaveIntervals.length; ++i) { + getAutosaveIntervalSeconds() { + const id = this.getAllSettings().autosaveInterval; + for (let i = 0; i < autosaveIntervals.length; ++i) { if (autosaveIntervals[i].id === id) { return autosaveIntervals[i].seconds; } @@ -348,22 +348,22 @@ export class ApplicationSettings extends ReadWriteProxy { logger.error("Unknown autosave interval id:", id); return 120; } - getIsFullScreen(): any { + getIsFullScreen() { return this.getAllSettings().fullscreen; } - getKeybindingOverrides(): any { + getKeybindingOverrides() { return this.getAllSettings().keybindingOverrides; } - getLanguage(): any { + getLanguage() { return this.getAllSettings().language; } // Setters - updateLanguage(id: any): any { + updateLanguage(id) { assert(LANGUAGES[id], "Language not known: " + id); return this.updateSetting("language", id); } - updateSetting(key: string, value: string | boolean | number): any { - const setting: any = this.getSettingHandleById(key); + updateSetting(key: string, value: string | boolean | number) { + const setting = this.getSettingHandleById(key); if (!setting) { assertAlways(false, "Unknown setting: " + key); } @@ -379,7 +379,7 @@ export class ApplicationSettings extends ReadWriteProxy { /** * Sets a new keybinding override */ - updateKeybindingOverride(keybindingId: string, keyCode: number): any { + updateKeybindingOverride(keybindingId: string, keyCode: number) { assert(Number.isInteger(keyCode), "Not a valid key code: " + keyCode); this.getAllSettings().keybindingOverrides[keybindingId] = keyCode; return this.writeAsync(); @@ -387,19 +387,19 @@ export class ApplicationSettings extends ReadWriteProxy { /** * Resets a given keybinding override */ - resetKeybindingOverride(id: string): any { + resetKeybindingOverride(id: string) { delete this.getAllSettings().keybindingOverrides[id]; return this.writeAsync(); } /** * Resets all keybinding overrides */ - resetKeybindingOverrides(): any { + resetKeybindingOverrides() { this.getAllSettings().keybindingOverrides = {}; return this.writeAsync(); } // RW Proxy impl - verify(data: any): any { + verify(data) { if (!data.settings) { return ExplainedResult.bad("missing key 'settings'"); } @@ -411,10 +411,10 @@ export class ApplicationSettings extends ReadWriteProxy { console.log("Resetting theme because its no longer available: " + data.settings.theme); data.settings.theme = "light"; } - const settings: any = data.settings; - for (let i: any = 0; i < this.settingHandles.length; ++i) { - const setting: any = this.settingHandles[i]; - const storedValue: any = settings[setting.id]; + const settings = data.settings; + for (let i = 0; i < this.settingHandles.length; ++i) { + const setting = this.settingHandles[i]; + const storedValue = settings[setting.id]; if (!setting.validate(storedValue)) { return ExplainedResult.bad("Bad setting value for " + setting.id + @@ -429,19 +429,19 @@ export class ApplicationSettings extends ReadWriteProxy { } return ExplainedResult.good(); } - getDefaultData(): any { + getDefaultData() { return { version: this.getCurrentVersion(), settings: new SettingsStorage(), }; } - getCurrentVersion(): any { + getCurrentVersion() { return 32; } migrate(data: { settings: SettingsStorage; version: number; - }): any { + }) { // Simply reset before if (data.version < 5) { data.settings = new SettingsStorage(); diff --git a/src/ts/profile/setting_types.ts b/src/ts/profile/setting_types.ts index 4b7b2867..1e798cf9 100644 --- a/src/ts/profile/setting_types.ts +++ b/src/ts/profile/setting_types.ts @@ -4,7 +4,7 @@ import type { Application } from "../application"; import { createLogger } from "../core/logging"; import { WEB_STEAM_SSO_AUTHENTICATED } from "../core/steam_sso"; import { T } from "../translations"; -const logger: any = createLogger("setting_types"); +const logger = createLogger("setting_types"); /* * *************************************************** * @@ -26,7 +26,7 @@ export class BaseSetting { constructor(id, categoryId, changeCb, enabledCb = null) { } - apply(app: Application, value: any): any { + apply(app: Application, value: any) { if (this.changeCb) { this.changeCb(app, value); } @@ -34,7 +34,7 @@ export class BaseSetting { /** * Binds all parameters */ - bind(app: Application, element: HTMLElement, dialogs: any): any { + bind(app: Application, element: HTMLElement, dialogs: any) { this.app = app; this.element = element; this.dialogs = dialogs; @@ -43,33 +43,33 @@ export class BaseSetting { * Returns the HTML for this setting * @abstract */ - getHtml(app: Application): any { + getHtml(app: Application) { abstract; return ""; } /** * Returns whether this setting is enabled and available */ - getIsAvailable(app: Application): any { + getIsAvailable(app: Application) { return this.enabledCb ? this.enabledCb(app) : true; } - syncValueToElement(): any { + syncValueToElement() { abstract; } /** * Attempts to modify the setting * @abstract */ - modify(): any { + modify() { abstract; } /** * Shows the dialog that a restart is required */ - showRestartRequiredDialog(): any { - const { restart }: any = this.dialogs.showInfo(T.dialogs.restartRequired.title, T.dialogs.restartRequired.text, this.app.platformWrapper.getSupportsRestart() ? ["later:grey", "restart:misc"] : ["ok:good"]); + showRestartRequiredDialog() { + const { restart } = this.dialogs.showInfo(T.dialogs.restartRequired.title, T.dialogs.restartRequired.text, this.app.platformWrapper.getSupportsRestart() ? ["later:grey", "restart:misc"] : ["ok:good"]); if (restart) { - restart.add((): any => this.app.platformWrapper.performRestart()); + restart.add(() => this.app.platformWrapper.performRestart()); } } /** @@ -86,7 +86,7 @@ export class EnumSetting extends BaseSetting { public options = options; public valueGetter = valueGetter; public textGetter = textGetter; - public descGetter = descGetter || ((): any => null); + public descGetter = descGetter || (() => null); public restartRequired = restartRequired; public iconPrefix = iconPrefix; public magicValue = magicValue; @@ -94,8 +94,8 @@ export class EnumSetting extends BaseSetting { constructor(id, { options, valueGetter, textGetter, descGetter = null, category, restartRequired = true, iconPrefix = null, changeCb = null, magicValue = null, enabledCb = null, }) { super(id, category, changeCb, enabledCb); } - getHtml(app: Application): any { - const available: any = this.getIsAvailable(app); + getHtml(app: Application) { + const available = this.getIsAvailable(app); return `
${available @@ -110,21 +110,21 @@ export class EnumSetting extends BaseSetting {
`; } - validate(value: any): any { + validate(value) { if (value === this.magicValue) { return true; } - const availableValues: any = this.options.map((option: any): any => this.valueGetter(option)); + const availableValues = this.options.map(option => this.valueGetter(option)); if (availableValues.indexOf(value) < 0) { logger.error("Value '" + value + "' is not contained in available values:", availableValues, "of", this.id); return false; } return true; } - syncValueToElement(): any { - const value: any = this.app.settings.getSetting(this.id); - let displayText: any = "???"; - const matchedInstance: any = this.options.find((data: any): any => this.valueGetter(data) === value); + syncValueToElement() { + const value = this.app.settings.getSetting(this.id); + let displayText = "???"; + const matchedInstance = this.options.find(data => this.valueGetter(data) === value); if (matchedInstance) { displayText = this.textGetter(matchedInstance); } @@ -133,17 +133,17 @@ export class EnumSetting extends BaseSetting { } this.element.innerText = displayText; } - modify(): any { - const { optionSelected }: any = this.dialogs.showOptionChooser(T.settings.labels[this.id].title, { + modify() { + const { optionSelected } = this.dialogs.showOptionChooser(T.settings.labels[this.id].title, { active: this.app.settings.getSetting(this.id), - options: this.options.map((option: any): any => ({ + options: this.options.map(option => ({ value: this.valueGetter(option), text: this.textGetter(option), desc: this.descGetter(option), iconPrefix: this.iconPrefix, })), }); - optionSelected.add((value: any): any => { + optionSelected.add(value => { this.app.settings.updateSetting(this.id, value); this.syncValueToElement(); if (this.restartRequired) { @@ -160,8 +160,8 @@ export class BoolSetting extends BaseSetting { constructor(id, category, changeCb = null, enabledCb = null) { super(id, category, changeCb, enabledCb); } - getHtml(app: Application): any { - const available: any = this.getIsAvailable(app); + getHtml(app: Application) { + const available = this.getIsAvailable(app); return `
${available @@ -179,19 +179,19 @@ export class BoolSetting extends BaseSetting {
`; } - syncValueToElement(): any { - const value: any = this.app.settings.getSetting(this.id); + syncValueToElement() { + const value = this.app.settings.getSetting(this.id); this.element.classList.toggle("checked", value); } - modify(): any { - const newValue: any = !this.app.settings.getSetting(this.id); + modify() { + const newValue = !this.app.settings.getSetting(this.id); this.app.settings.updateSetting(this.id, newValue); this.syncValueToElement(); if (this.changeCb) { this.changeCb(this.app, newValue); } } - validate(value: any): any { + validate(value) { return typeof value === "boolean"; } } @@ -204,8 +204,8 @@ export class RangeSetting extends BaseSetting { constructor(id, category, changeCb = null, defaultValue = 1.0, minValue = 0, maxValue = 1.0, stepSize = 0.0001, enabledCb = null) { super(id, category, changeCb, enabledCb); } - getHtml(app: Application): any { - const available: any = this.getIsAvailable(app); + getHtml(app: Application) { + const available = this.getIsAvailable(app); return `
${available @@ -224,32 +224,32 @@ export class RangeSetting extends BaseSetting {
`; } - bind(app: any, element: any, dialogs: any): any { + bind(app, element, dialogs) { this.app = app; this.element = element; this.dialogs = dialogs; - this.getRangeInputElement().addEventListener("input", (): any => { + this.getRangeInputElement().addEventListener("input", () => { this.updateLabels(); }); - this.getRangeInputElement().addEventListener("change", (): any => { + this.getRangeInputElement().addEventListener("change", () => { this.modify(); }); } - syncValueToElement(): any { - const value: any = this.app.settings.getSetting(this.id); + syncValueToElement() { + const value = this.app.settings.getSetting(this.id); this.setElementValue(value); } /** * Sets the elements value to the given value */ - setElementValue(value: number): any { - const rangeInput: any = this.getRangeInputElement(); - const rangeLabel: any = this.element.querySelector("label"); + setElementValue(value: number) { + const rangeInput = this.getRangeInputElement(); + const rangeLabel = this.element.querySelector("label"); rangeInput.value = String(value); rangeLabel.innerHTML = T.settings.rangeSliderPercentage.replace("", String(Math.round(value * 100.0))); } - updateLabels(): any { - const value: any = Number(this.getRangeInputElement().value); + updateLabels() { + const value = Number(this.getRangeInputElement().value); this.setElementValue(value); } /** @@ -258,9 +258,9 @@ export class RangeSetting extends BaseSetting { getRangeInputElement(): HTMLInputElement { return this.element.querySelector("input.rangeInput"); } - modify(): any { - const rangeInput: any = this.getRangeInputElement(); - const newValue: any = Math.round(Number(rangeInput.value) * 100.0) / 100.0; + modify() { + const rangeInput = this.getRangeInputElement(); + const newValue = Math.round(Number(rangeInput.value) * 100.0) / 100.0; this.app.settings.updateSetting(this.id, newValue); this.syncValueToElement(); console.log("SET", newValue); @@ -268,7 +268,7 @@ export class RangeSetting extends BaseSetting { this.changeCb(this.app, newValue); } } - validate(value: any): any { + validate(value) { return typeof value === "number" && value >= this.minValue && value <= this.maxValue; } } diff --git a/src/ts/savegame/puzzle_serializer.ts b/src/ts/savegame/puzzle_serializer.ts index 6a7646b2..6baff2b3 100644 --- a/src/ts/savegame/puzzle_serializer.ts +++ b/src/ts/savegame/puzzle_serializer.ts @@ -16,16 +16,16 @@ import { enumColors } from "../game/colors"; import { COLOR_ITEM_SINGLETONS } from "../game/items/color_item"; import { ShapeDefinition } from "../game/shape_definition"; import { MetaBlockBuilding } from "../game/buildings/block"; -const logger: any = createLogger("puzzle-serializer"); +const logger = createLogger("puzzle-serializer"); export class PuzzleSerializer { generateDumpFromGameRoot(root: GameRoot): import("./savegame_typedefs").PuzzleGameData { console.log("serializing", root); let buildings: import("./savegame_typedefs").PuzzleGameData["buildings"] = []; - for (const entity: any of root.entityMgr.getAllWithComponent(StaticMapEntityComponent)) { - const staticComp: any = entity.components.StaticMapEntity; - const signalComp: any = entity.components.ConstantSignal; + for (const entity of root.entityMgr.getAllWithComponent(StaticMapEntityComponent)) { + const staticComp = entity.components.StaticMapEntity; + const signalComp = entity.components.ConstantSignal; if (signalComp) { assert(["shape", "color"].includes(signalComp.signal.getItemType()), "not a shape signal"); buildings.push({ @@ -39,7 +39,7 @@ export class PuzzleSerializer { }); continue; } - const goalComp: any = entity.components.GoalAcceptor; + const goalComp = entity.components.GoalAcceptor; if (goalComp) { assert(goalComp.item, "goals is missing item"); assert(goalComp.item.getItemType() === "shape", "goal is not an item"); @@ -65,12 +65,12 @@ export class PuzzleSerializer { }); } } - const mode: any = (root.gameMode as PuzzleGameMode); - const handles: any = root.hud.parts.buildingsToolbar.buildingHandles; - const ids: any = gMetaBuildingRegistry.getAllIds(); + const mode = root.gameMode as PuzzleGameMode); + const handles = root.hud.parts.buildingsToolbar.buildingHandles; + const ids = gMetaBuildingRegistry.getAllIds(); let excludedBuildings: Array = []; - for (let i: any = 0; i < ids.length; ++i) { - const handle: any = handles[ids[i]]; + for (let i = 0; i < ids.length; ++i) { + const handle = handles[ids[i]]; if (handle && handle.puzzleLocked) { // @ts-ignore excludedBuildings.push(handle.metaBuilding.getId()); @@ -97,7 +97,7 @@ export class PuzzleSerializer { return null; } code = trim(code); - const codeLower: any = code.toLowerCase(); + const codeLower = code.toLowerCase(); if (enumColors[codeLower]) { return COLOR_ITEM_SINGLETONS[codeLower]; } @@ -107,18 +107,18 @@ export class PuzzleSerializer { return null; } - deserializePuzzle(root: GameRoot, puzzle: import("./savegame_typedefs").PuzzleGameData): any { + deserializePuzzle(root: GameRoot, puzzle: import("./savegame_typedefs").PuzzleGameData) { if (puzzle.version !== 1) { return "invalid-version"; } - for (const building: any of puzzle.buildings) { + for (const building of puzzle.buildings) { switch (building.type) { case "emitter": { - const item: any = this.parseItemCode(root, building.item); + const item = this.parseItemCode(root, building.item); if (!item) { return "bad-item:" + building.item; } - const entity: any = root.logic.tryPlaceBuilding({ + const entity = root.logic.tryPlaceBuilding({ origin: new Vector(building.pos.x, building.pos.y), building: gMetaBuildingRegistry.findByClass(MetaConstantProducerBuilding), originalRotation: building.pos.r, @@ -134,11 +134,11 @@ export class PuzzleSerializer { break; } case "goal": { - const item: any = this.parseItemCode(root, building.item); + const item = this.parseItemCode(root, building.item); if (!item) { return "bad-item:" + building.item; } - const entity: any = root.logic.tryPlaceBuilding({ + const entity = root.logic.tryPlaceBuilding({ origin: new Vector(building.pos.x, building.pos.y), building: gMetaBuildingRegistry.findByClass(MetaGoalAcceptorBuilding), originalRotation: building.pos.r, @@ -154,7 +154,7 @@ export class PuzzleSerializer { break; } case "block": { - const entity: any = root.logic.tryPlaceBuilding({ + const entity = root.logic.tryPlaceBuilding({ origin: new Vector(building.pos.x, building.pos.y), building: gMetaBuildingRegistry.findByClass(MetaBlockBuilding), originalRotation: building.pos.r, diff --git a/src/ts/savegame/savegame.ts b/src/ts/savegame/savegame.ts index 797d77ee..d2b8b3fc 100644 --- a/src/ts/savegame/savegame.ts +++ b/src/ts/savegame/savegame.ts @@ -16,7 +16,7 @@ import { SavegameInterface_V1008 } from "./schemas/1008"; import { SavegameInterface_V1009 } from "./schemas/1009"; import { MODS } from "../mods/modloader"; import { SavegameInterface_V1010 } from "./schemas/1010"; -const logger: any = createLogger("savegame"); +const logger = createLogger("savegame"); export type Application = import("../application").Application; export type GameRoot = import("../game/root").GameRoot; export type SavegameData = import("./savegame_typedefs").SavegameData; @@ -82,7 +82,7 @@ export class Savegame extends ReadWriteProxy { * @param {Application} app * @returns */ - static createPuzzleSavegame(app: Application): any { + static createPuzzleSavegame(app: Application) { return new Savegame(app, { internalId: "puzzle", metaDataRef: { @@ -121,7 +121,7 @@ export class Savegame extends ReadWriteProxy { /** * Migrates the savegames data */ - migrate(data: SavegameData): any { + migrate(data: SavegameData) { if (data.version < 1000) { return ExplainedResult.bad("Can not migrate savegame, too old"); } @@ -170,7 +170,7 @@ export class Savegame extends ReadWriteProxy { /** * Verifies the savegames data */ - verify(data: SavegameData): any { + verify(data: SavegameData) { if (!data.dump) { // Well, guess that works return ExplainedResult.good(); @@ -199,13 +199,13 @@ export class Savegame extends ReadWriteProxy { * Returns the *real* last update of the savegame, not the one of the metadata * which could also be the servers one */ - getRealLastUpdate(): any { + getRealLastUpdate() { return this.currentData.lastUpdate; } /** * Returns if this game has a serialized game dump */ - hasGameDump(): any { + hasGameDump() { return !!this.currentData.dump && this.currentData.dump.entities.length > 0; } /** @@ -224,14 +224,14 @@ export class Savegame extends ReadWriteProxy { logger.warn("Getting reader on null-savegame dump"); } - const cls: any = (this.constructor as typeof Savegame).getReaderClass(); + const cls = this.constructor as typeof Savegame).getReaderClass(); return new cls(this.currentData); } /** * Returns a reader to access external data * {} */ - getDumpReaderForExternalData(data: any): BaseSavegameInterface { + getDumpReaderForExternalData(data): BaseSavegameInterface { assert(data.version, "External data contains no version"); return getSavegameInterface(data); } @@ -240,26 +240,26 @@ export class Savegame extends ReadWriteProxy { * Updates the last update field so we can send the savegame to the server, * WITHOUT Saving! */ - setLastUpdate(time: any): any { + setLastUpdate(time) { this.currentData.lastUpdate = time; } - updateData(root: GameRoot): any { + updateData(root: GameRoot) { // Construct a new serializer - const serializer: any = new SavegameSerializer(); + const serializer = new SavegameSerializer(); // let timer = performance.now(); - const dump: any = serializer.generateDumpFromGameRoot(root); + const dump = serializer.generateDumpFromGameRoot(root); if (!dump) { return false; } - const shadowData: any = Object.assign({}, this.currentData); + const shadowData = Object.assign({}, this.currentData); shadowData.dump = dump; shadowData.lastUpdate = new Date().getTime(); shadowData.version = this.getCurrentVersion(); shadowData.mods = MODS.getModsListForSavegame(); - const reader: any = this.getDumpReaderForExternalData(shadowData); + const reader = this.getDumpReaderForExternalData(shadowData); // Validate (not in prod though) if (!G_IS_RELEASE) { - const validationResult: any = reader.validate(); + const validationResult = reader.validate(); if (!validationResult) { return false; } @@ -270,13 +270,13 @@ export class Savegame extends ReadWriteProxy { /** * Writes the savegame as well as its metadata */ - writeSavegameAndMetadata(): any { - return this.writeAsync().then((): any => this.saveMetadata()); + writeSavegameAndMetadata() { + return this.writeAsync().then(() => this.saveMetadata()); } /** * Updates the savegames metadata */ - saveMetadata(): any { + saveMetadata() { this.metaDataRef.lastUpdate = new Date().getTime(); this.metaDataRef.version = this.getCurrentVersion(); if (!this.hasGameDump()) { diff --git a/src/ts/savegame/savegame_compressor.ts b/src/ts/savegame/savegame_compressor.ts index d50e0698..1492fb68 100644 --- a/src/ts/savegame/savegame_compressor.ts +++ b/src/ts/savegame/savegame_compressor.ts @@ -1,6 +1,6 @@ -const charmap: any = "!#%&'()*+,-./:;<=>?@[]^_`{|}~¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿABCDEFGHIJKLMNOPQRSTUVWXYZ"; -let compressionCache: any = {}; -let decompressionCache: any = {}; +const charmap = "!#%&'()*+,-./:;<=>?@[]^_`{|}~¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿABCDEFGHIJKLMNOPQRSTUVWXYZ"; +let compressionCache = {}; +let decompressionCache = {}; /** * Compresses an integer into a tight string representation * {} @@ -11,11 +11,11 @@ function compressInt(i: number): string { // save `i` as the cache key // to avoid it being modified by the // rest of the function. - const cache_key: any = i; + const cache_key = i; if (compressionCache[cache_key]) { return compressionCache[cache_key]; } - let result: any = ""; + let result = ""; do { result += charmap[i % charmap.length]; i = Math.floor(i / charmap.length); @@ -31,8 +31,8 @@ function decompressInt(s: string): number { return decompressionCache[s]; } s = "" + s; - let result: any = 0; - for (let i: any = s.length - 1; i >= 0; --i) { + let result = 0; + for (let i = s.length - 1; i >= 0; --i) { result = result * charmap.length + charmap.indexOf(s.charAt(i)); } // Fixes zero value break fix from above @@ -41,7 +41,7 @@ function decompressInt(s: string): number { } // Sanity if (G_IS_DEV) { - for (let i: any = 0; i < 10000; ++i) { + for (let i = 0; i < 10000; ++i) { if (decompressInt(compressInt(i)) !== i) { throw new Error("Bad compression for: " + i + @@ -57,27 +57,27 @@ if (G_IS_DEV) { */ function compressObjectInternal(obj: any, keys: Map, values: Map): any[] | object | number | string { if (Array.isArray(obj)) { - let result: any = []; - for (let i: any = 0; i < obj.length; ++i) { + let result = []; + for (let i = 0; i < obj.length; ++i) { result.push(compressObjectInternal(obj[i], keys, values)); } return result; } else if (typeof obj === "object" && obj !== null) { - let result: any = {}; - for (const key: any in obj) { - let index: any = keys.get(key); + let result = {}; + for (const key in obj) { + let index = keys.get(key); if (index === undefined) { index = keys.size; keys.set(key, index); } - const value: any = obj[key]; + const value = obj[key]; result[compressInt(index)] = compressObjectInternal(value, keys, values); } return result; } else if (typeof obj === "string") { - let index: any = values.get(obj); + let index = values.get(obj); if (index === undefined) { index = values.size; values.set(obj, index); @@ -90,16 +90,16 @@ function compressObjectInternal(obj: any, keys: Map, values: Map): any[] | objec * {} */ function indexMapToArray(hashMap: Map): Array { - const result: any = new Array(hashMap.size); - hashMap.forEach((index: any, key: any): any => { + const result = new Array(hashMap.size); + hashMap.forEach((index, key) => { result[index] = key; }); return result; } -export function compressObject(obj: object): any { - const keys: any = new Map(); - const values: any = new Map(); - const data: any = compressObjectInternal(obj, keys, values); +export function compressObject(obj: object) { + const keys = new Map(); + const values = new Map(); + const data = compressObjectInternal(obj, keys, values); return { keys: indexMapToArray(keys), values: indexMapToArray(values), @@ -111,32 +111,32 @@ export function compressObject(obj: object): any { */ function decompressObjectInternal(obj: object, keys: string[] = [], values: any[] = []): object { if (Array.isArray(obj)) { - let result: any = []; - for (let i: any = 0; i < obj.length; ++i) { + let result = []; + for (let i = 0; i < obj.length; ++i) { result.push(decompressObjectInternal(obj[i], keys, values)); } return result; } else if (typeof obj === "object" && obj !== null) { - let result: any = {}; - for (const key: any in obj) { - const realIndex: any = decompressInt(key); - const value: any = obj[key]; + let result = {}; + for (const key in obj) { + const realIndex = decompressInt(key); + const value = obj[key]; result[keys[realIndex]] = decompressObjectInternal(value, keys, values); } return result; } else if (typeof obj === "string") { - const realIndex: any = decompressInt(obj); + const realIndex = decompressInt(obj); return values[realIndex]; } return obj; } -export function decompressObject(obj: object): any { +export function decompressObject(obj: object) { if (obj.keys && obj.values && obj.data) { - const keys: any = obj.keys; - const values: any = obj.values; - const result: any = decompressObjectInternal(obj.data, keys, values); + const keys = obj.keys; + const values = obj.values; + const result = decompressObjectInternal(obj.data, keys, values); return result; } return obj; diff --git a/src/ts/savegame/savegame_interface.ts b/src/ts/savegame/savegame_interface.ts index 7de9d9c8..542ff150 100644 --- a/src/ts/savegame/savegame_interface.ts +++ b/src/ts/savegame/savegame_interface.ts @@ -1,18 +1,18 @@ import { createLogger } from "../core/logging"; -const Ajv: any = require("ajv"); -const ajv: any = new Ajv({ +const Ajv = require("ajv"); +const ajv = new Ajv({ allErrors: false, uniqueItems: false, unicode: false, nullable: false, }); -const validators: any = {}; -const logger: any = createLogger("savegame_interface"); +const validators = {}; +const logger = createLogger("savegame_interface"); export class BaseSavegameInterface { /** * Returns the interfaces version */ - getVersion(): any { + getVersion() { throw new Error("Implement get version"); } /** @@ -22,17 +22,17 @@ export class BaseSavegameInterface { getSchemaUncached(): object { throw new Error("Implement get schema"); } - getValidator(): any { - const version: any = this.getVersion(); + getValidator() { + const version = this.getVersion(); if (validators[version]) { return validators[version]; } logger.log("Compiling schema for savegame version", version); - const schema: any = this.getSchemaUncached(); + const schema = this.getSchemaUncached(); try { validators[version] = ajv.compile(schema); } - catch (ex: any) { + catch (ex) { logger.error("SCHEMA FOR", this.getVersion(), "IS INVALID!"); logger.error(ex); throw new Error("Invalid schema for version " + version); @@ -51,7 +51,7 @@ export class BaseSavegameInterface { * {} */ validate(): boolean { - const validator: any = this.getValidator(); + const validator = this.getValidator(); if (!validator(this.data)) { logger.error("Savegame failed validation! ErrorText:", ajv.errorsText(validator.errors), "RawErrors:", validator.errors); return false; diff --git a/src/ts/savegame/savegame_interface_registry.ts b/src/ts/savegame/savegame_interface_registry.ts index 9c17a890..4373d7e6 100644 --- a/src/ts/savegame/savegame_interface_registry.ts +++ b/src/ts/savegame/savegame_interface_registry.ts @@ -26,7 +26,7 @@ export const savegameInterfaces: { 1009: SavegameInterface_V1009, 1010: SavegameInterface_V1010, }; -const logger: any = createLogger("savegame_interface_registry"); +const logger = createLogger("savegame_interface_registry"); /** * Returns if the given savegame has any supported interface * {} @@ -36,12 +36,12 @@ export function getSavegameInterface(savegame: any): BaseSavegameInterface | nul logger.warn("Savegame does not contain a valid version (undefined)"); return null; } - const version: any = savegame.version; + const version = savegame.version; if (!Number.isInteger(version)) { logger.warn("Savegame does not contain a valid version (non-integer):", version); return null; } - const interfaceClass: any = savegameInterfaces[version]; + const interfaceClass = savegameInterfaces[version]; if (!interfaceClass) { logger.warn("Version", version, "has no implemented interface!"); return null; diff --git a/src/ts/savegame/savegame_manager.ts b/src/ts/savegame/savegame_manager.ts index de135708..d5935acb 100644 --- a/src/ts/savegame/savegame_manager.ts +++ b/src/ts/savegame/savegame_manager.ts @@ -3,13 +3,13 @@ import { createLogger } from "../core/logging"; import { ReadWriteProxy } from "../core/read_write_proxy"; import { globalConfig } from "../core/config"; import { Savegame } from "./savegame"; -const logger: any = createLogger("savegame_manager"); -const Rusha: any = require("rusha"); +const logger = createLogger("savegame_manager"); +const Rusha = require("rusha"); export type SavegamesData = import("./savegame_typedefs").SavegamesData; export type SavegameMetadata = import("./savegame_typedefs").SavegameMetadata; /** @enum {string} */ -export const enumLocalSavegameStatus: any = { +export const enumLocalSavegameStatus = { offline: "offline", synced: "synced", }; @@ -29,22 +29,22 @@ export class SavegameManager extends ReadWriteProxy { savegames: [], }; } - getCurrentVersion(): any { + getCurrentVersion() { return 1002; } - verify(data: any): any { + verify(data) { // @TODO return ExplainedResult.good(); } - migrate(data: SavegamesData): any { + migrate(data: SavegamesData) { if (data.version < 1001) { - data.savegames.forEach((savegame: any): any => { + data.savegames.forEach(savegame => { savegame.level = 0; }); data.version = 1001; } if (data.version < 1002) { - data.savegames.forEach((savegame: any): any => { + data.savegames.forEach(savegame => { savegame.name = null; }); data.version = 1002; @@ -63,7 +63,7 @@ export class SavegameManager extends ReadWriteProxy { * {} */ getSavegameById(internalId: string): Savegame { - const metadata: any = this.getGameMetaDataByInternalId(internalId); + const metadata = this.getGameMetaDataByInternalId(internalId); if (!metadata) { return null; } @@ -72,19 +72,19 @@ export class SavegameManager extends ReadWriteProxy { /** * Deletes a savegame */ - deleteSavegame(game: SavegameMetadata): any { - const handle: any = new Savegame(this.app, { + deleteSavegame(game: SavegameMetadata) { + const handle = new Savegame(this.app, { internalId: game.internalId, metaDataRef: game, }); return handle .deleteAsync() - .catch((err: any): any => { + .catch(err => { console.warn("Failed to unlink physical savegame file, still removing:", err); }) - .then((): any => { - for (let i: any = 0; i < this.currentData.savegames.length; ++i) { - const potentialGame: any = this.currentData.savegames[i]; + .then(() => { + for (let i = 0; i < this.currentData.savegames.length; ++i) { + const potentialGame = this.currentData.savegames[i]; if (potentialGame.internalId === handle.internalId) { this.currentData.savegames.splice(i, 1); break; @@ -98,8 +98,8 @@ export class SavegameManager extends ReadWriteProxy { * {} */ getGameMetaDataByInternalId(id: string): SavegameMetadata { - for (let i: any = 0; i < this.currentData.savegames.length; ++i) { - const data: any = this.currentData.savegames[i]; + for (let i = 0; i < this.currentData.savegames.length; ++i) { + const data = this.currentData.savegames[i]; if (data.internalId === id) { return data; } @@ -112,8 +112,8 @@ export class SavegameManager extends ReadWriteProxy { * {} */ createNewSavegame(): Savegame { - const id: any = this.generateInternalId(); - const metaData: any = ({ + const id = this.generateInternalId(); + const metaData = { lastUpdate: Date.now(), version: Savegame.getCurrentVersion(), internalId: id, @@ -129,42 +129,42 @@ export class SavegameManager extends ReadWriteProxy { /** * Attempts to import a savegame */ - importSavegame(data: object): any { - const savegame: any = this.createNewSavegame(); - const migrationResult: any = savegame.migrate(data); + importSavegame(data: object) { + const savegame = this.createNewSavegame(); + const migrationResult = savegame.migrate(data); if (migrationResult.isBad()) { return Promise.reject("Failed to migrate: " + migrationResult.reason); } savegame.currentData = data; - const verification: any = savegame.verify(data); + const verification = savegame.verify(data); if (verification.isBad()) { return Promise.reject("Verification failed: " + verification.result); } - return savegame.writeSavegameAndMetadata().then((): any => this.updateAfterSavegamesChanged()); + return savegame.writeSavegameAndMetadata().then(() => this.updateAfterSavegamesChanged()); } /** * Hook after the savegames got changed */ - updateAfterSavegamesChanged(): any { - return this.sortSavegames().then((): any => this.writeAsync()); + updateAfterSavegamesChanged() { + return this.sortSavegames().then(() => this.writeAsync()); } /** * Sorts all savegames by their creation time descending * {} */ sortSavegames(): Promise { - this.currentData.savegames.sort((a: any, b: any): any => b.lastUpdate - a.lastUpdate); - let promiseChain: any = Promise.resolve(); + this.currentData.savegames.sort((a, b) => b.lastUpdate - a.lastUpdate); + let promiseChain = Promise.resolve(); while (this.currentData.savegames.length > 30) { - const toRemove: any = this.currentData.savegames.pop(); + const toRemove = this.currentData.savegames.pop(); // Try to remove the savegame since its no longer available - const game: any = new Savegame(this.app, { + const game = new Savegame(this.app, { internalId: toRemove.internalId, metaDataRef: toRemove, }); promiseChain = promiseChain - .then((): any => game.deleteAsync()) - .then((): any => { }, (err: any): any => { + .then(() => game.deleteAsync()) + .then(() => { }, err => { logger.error(this, "Failed to remove old savegame:", toRemove, ":", err); }); } @@ -173,16 +173,16 @@ export class SavegameManager extends ReadWriteProxy { /** * Helper method to generate a new internal savegame id */ - generateInternalId(): any { + generateInternalId() { return Rusha.createHash() .update(Date.now() + "/" + Math.random()) .digest("hex"); } // End - initialize(): any { + initialize() { // First read, then directly write to ensure we have the latest data // @ts-ignore - return this.readAsync().then((): any => { + return this.readAsync().then(() => { if (G_IS_DEV && globalConfig.debug.disableSavegameWrite) { return Promise.resolve(); } diff --git a/src/ts/savegame/savegame_serializer.ts b/src/ts/savegame/savegame_serializer.ts index ed2de0ff..24520ba0 100644 --- a/src/ts/savegame/savegame_serializer.ts +++ b/src/ts/savegame/savegame_serializer.ts @@ -9,7 +9,7 @@ export type Entity = import("../game/entity").Entity; export type GameRoot = import("../game/root").GameRoot; export type SerializedGame = import("./savegame_typedefs").SerializedGame; -const logger: any = createLogger("savegame_serializer"); +const logger = createLogger("savegame_serializer"); /** * Serializes a savegame */ @@ -40,7 +40,7 @@ export class SavegameSerializer { if (G_IS_DEV) { if (sanityChecks) { // Sanity check - const sanity: any = this.verifyLogicalErrors(data); + const sanity = this.verifyLogicalErrors(data); if (!sanity.result) { logger.error("Created invalid savegame:", sanity.reason, "savegame:", data); return null; @@ -57,11 +57,11 @@ export class SavegameSerializer { if (!savegame.entities) { return ExplainedResult.bad("Savegame has no entities"); } - const seenUids: any = new Set(); + const seenUids = new Set(); // Check for duplicate UIDS - for (let i: any = 0; i < savegame.entities.length; ++i) { + for (let i = 0; i < savegame.entities.length; ++i) { const entity: Entity = savegame.entities[i]; - const uid: any = entity.uid; + const uid = entity.uid; if (!Number.isInteger(uid)) { return ExplainedResult.bad("Entity has invalid uid: " + uid); } @@ -73,16 +73,16 @@ export class SavegameSerializer { if (!entity.components) { return ExplainedResult.bad("Entity is missing key 'components': " + JSON.stringify(entity)); } - const components: any = entity.components; - for (const componentId: any in components) { - const componentClass: any = gComponentRegistry.findById(componentId); + const components = entity.components; + for (const componentId in components) { + const componentClass = gComponentRegistry.findById(componentId); // Check component id is known if (!componentClass) { return ExplainedResult.bad("Unknown component id: " + componentId); } // Verify component data - const componentData: any = components[componentId]; - const componentVerifyError: any = (componentClass as StaticComponent).verify(componentData); + const componentData = components[componentId]; + const componentVerifyError = componentClass as StaticComponent).verify(componentData); // Check component data is ok if (componentVerifyError) { return ExplainedResult.bad("Component " + componentId + " has invalid data: " + componentVerifyError); @@ -97,11 +97,11 @@ export class SavegameSerializer { */ deserialize(savegame: SerializedGame, root: GameRoot): ExplainedResult { // Sanity - const verifyResult: any = this.verifyLogicalErrors(savegame); + const verifyResult = this.verifyLogicalErrors(savegame); if (!verifyResult.result) { return ExplainedResult.bad(verifyResult.reason); } - let errorReason: any = null; + let errorReason = null; errorReason = errorReason || root.entityMgr.deserialize(savegame.entityMgr); errorReason = errorReason || root.time.deserialize(savegame.time); errorReason = errorReason || root.camera.deserialize(savegame.camera); diff --git a/src/ts/savegame/schemas/1000.ts b/src/ts/savegame/schemas/1000.ts index f9673b69..ab808295 100644 --- a/src/ts/savegame/schemas/1000.ts +++ b/src/ts/savegame/schemas/1000.ts @@ -1,10 +1,10 @@ import { BaseSavegameInterface } from "../savegame_interface.js"; -const schema: any = require("./1000.json"); +const schema = require("./1000.json"); export class SavegameInterface_V1000 extends BaseSavegameInterface { - getVersion(): any { + getVersion() { return 1000; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } } diff --git a/src/ts/savegame/schemas/1001.ts b/src/ts/savegame/schemas/1001.ts index c3b1d313..ec54a142 100644 --- a/src/ts/savegame/schemas/1001.ts +++ b/src/ts/savegame/schemas/1001.ts @@ -2,19 +2,19 @@ import { SavegameInterface_V1000 } from "./1000.js"; import { createLogger } from "../../core/logging.js"; import { T } from "../../translations.js"; import { TypeVector, TypeNumber, TypeString, TypeNullable } from "../serialization_data_types.js"; -const schema: any = require("./1001.json"); -const logger: any = createLogger("savegame_interface/1001"); +const schema = require("./1001.json"); +const logger = createLogger("savegame_interface/1001"); export class SavegameInterface_V1001 extends SavegameInterface_V1000 { - getVersion(): any { + getVersion() { return 1001; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1000to1001(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1000to1001(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1000 to 1001"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } @@ -31,9 +31,9 @@ export class SavegameInterface_V1001 extends SavegameInterface_V1000 { }, ], }; - const entities: any = dump.entities; - for (let i: any = 0; i < entities.length; ++i) { - const entity: any = entities[i]; + const entities = dump.entities; + for (let i = 0; i < entities.length; ++i) { + const entity = entities[i]; export type OldStaticMapEntity = { origin: TypeVector; tileSize: TypeVector; @@ -52,7 +52,7 @@ export class SavegameInterface_V1001 extends SavegameInterface_V1000 { /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @ /** @type OldStaticMapEntity **/ // @ts-ignore const staticComp: OldStaticMapEntity = entity.components.StaticMapEntity; - const beltComp: any = entity.components.Belt; + const beltComp = entity.components.Belt; if (staticComp) { if (staticComp.spriteKey) { staticComp.blueprintSpriteKey = staticComp.spriteKey.replace("sprites/buildings", "sprites/blueprints"); @@ -62,7 +62,7 @@ export class SavegameInterface_V1001 extends SavegameInterface_V1000 { staticComp.blueprintSpriteKey = ""; } else if (beltComp) { - const direction: any = beltComp.direction; + const direction = beltComp.direction; staticComp.blueprintSpriteKey = "sprites/blueprints/belt_" + direction + ".png"; } else { diff --git a/src/ts/savegame/schemas/1002.ts b/src/ts/savegame/schemas/1002.ts index 986a8388..643c1aa5 100644 --- a/src/ts/savegame/schemas/1002.ts +++ b/src/ts/savegame/schemas/1002.ts @@ -1,27 +1,27 @@ import { createLogger } from "../../core/logging.js"; import { T } from "../../translations.js"; import { SavegameInterface_V1001 } from "./1001.js"; -const schema: any = require("./1002.json"); -const logger: any = createLogger("savegame_interface/1002"); +const schema = require("./1002.json"); +const logger = createLogger("savegame_interface/1002"); export class SavegameInterface_V1002 extends SavegameInterface_V1001 { - getVersion(): any { + getVersion() { return 1002; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1001to1002(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1001to1002(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1001 to 1002"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } - const entities: any = dump.entities; - for (let i: any = 0; i < entities.length; ++i) { - const entity: any = entities[i]; - const beltComp: any = entity.components.Belt; - const ejectorComp: any = entity.components.ItemEjector; + const entities = dump.entities; + for (let i = 0; i < entities.length; ++i) { + const entity = entities[i]; + const beltComp = entity.components.Belt; + const ejectorComp = entity.components.ItemEjector; if (beltComp && ejectorComp) { // @ts-ignore ejectorComp.instantEject = true; diff --git a/src/ts/savegame/schemas/1003.ts b/src/ts/savegame/schemas/1003.ts index d50a758e..acc92363 100644 --- a/src/ts/savegame/schemas/1003.ts +++ b/src/ts/savegame/schemas/1003.ts @@ -1,18 +1,18 @@ import { createLogger } from "../../core/logging.js"; import { SavegameInterface_V1002 } from "./1002.js"; -const schema: any = require("./1003.json"); -const logger: any = createLogger("savegame_interface/1003"); +const schema = require("./1003.json"); +const logger = createLogger("savegame_interface/1003"); export class SavegameInterface_V1003 extends SavegameInterface_V1002 { - getVersion(): any { + getVersion() { return 1003; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1002to1003(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1002to1003(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1002 to 1003"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } diff --git a/src/ts/savegame/schemas/1004.ts b/src/ts/savegame/schemas/1004.ts index a7a4f738..5cda9303 100644 --- a/src/ts/savegame/schemas/1004.ts +++ b/src/ts/savegame/schemas/1004.ts @@ -1,25 +1,25 @@ import { createLogger } from "../../core/logging.js"; import { SavegameInterface_V1003 } from "./1003.js"; -const schema: any = require("./1004.json"); -const logger: any = createLogger("savegame_interface/1004"); +const schema = require("./1004.json"); +const logger = createLogger("savegame_interface/1004"); export class SavegameInterface_V1004 extends SavegameInterface_V1003 { - getVersion(): any { + getVersion() { return 1004; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1003to1004(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1003to1004(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1003 to 1004"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } // The hub simply has an empty label - const waypointData: any = dump.waypoints.waypoints; - for (let i: any = 0; i < waypointData.length; ++i) { - const waypoint: any = waypointData[i]; + const waypointData = dump.waypoints.waypoints; + for (let i = 0; i < waypointData.length; ++i) { + const waypoint = waypointData[i]; if (!waypoint.deletable) { waypoint.label = null; } diff --git a/src/ts/savegame/schemas/1005.ts b/src/ts/savegame/schemas/1005.ts index 2fd42548..5286e6c0 100644 --- a/src/ts/savegame/schemas/1005.ts +++ b/src/ts/savegame/schemas/1005.ts @@ -1,32 +1,32 @@ import { createLogger } from "../../core/logging.js"; import { SavegameInterface_V1004 } from "./1004.js"; -const schema: any = require("./1005.json"); -const logger: any = createLogger("savegame_interface/1005"); +const schema = require("./1005.json"); +const logger = createLogger("savegame_interface/1005"); export class SavegameInterface_V1005 extends SavegameInterface_V1004 { - getVersion(): any { + getVersion() { return 1005; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1004to1005(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1004to1005(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1004 to 1005"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } // just reset belt paths for now dump.beltPaths = []; - const entities: any = dump.entities; + const entities = dump.entities; // clear ejector slots - for (let i: any = 0; i < entities.length; ++i) { - const entity: any = entities[i]; - const itemEjector: any = entity.components.ItemEjector; + for (let i = 0; i < entities.length; ++i) { + const entity = entities[i]; + const itemEjector = entity.components.ItemEjector; if (itemEjector) { - const slots: any = itemEjector.slots; - for (let k: any = 0; k < slots.length; ++k) { - const slot: any = slots[k]; + const slots = itemEjector.slots; + for (let k = 0; k < slots.length; ++k) { + const slot = slots[k]; slot.item = null; slot.progress = 0; } diff --git a/src/ts/savegame/schemas/1006.ts b/src/ts/savegame/schemas/1006.ts index 3957360c..a1fee0d8 100644 --- a/src/ts/savegame/schemas/1006.ts +++ b/src/ts/savegame/schemas/1006.ts @@ -17,9 +17,9 @@ import { StaticMapEntityComponent } from "../../game/components/static_map_entit import { Entity } from "../../game/entity.js"; import { defaultBuildingVariant, MetaBuilding } from "../../game/meta_building.js"; import { SavegameInterface_V1005 } from "./1005.js"; -const schema: any = require("./1006.json"); -const logger: any = createLogger("savegame_interface/1006"); -function findCode(metaBuilding: typeof MetaBuilding, variant: string= = defaultBuildingVariant, rotationVariant: number= = 0): any { +const schema = require("./1006.json"); +const logger = createLogger("savegame_interface/1006"); +function findCode(metaBuilding: typeof MetaBuilding, variant: string= = defaultBuildingVariant, rotationVariant: number= = 0) { return getCodeFromBuildingData(gMetaBuildingRegistry.findByClass(metaBuilding), variant, rotationVariant); } /** @@ -30,13 +30,13 @@ function rebalance(value: number): number { return Math.round(Math.pow(value, 0.75)); } export class SavegameInterface_V1006 extends SavegameInterface_V1005 { - getVersion(): any { + getVersion() { return 1006; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static computeSpriteMapping(): any { + static computeSpriteMapping() { return { // Belt "sprites/blueprints/belt_top.png": findCode(MetaBeltBuilding, defaultBuildingVariant, 0), @@ -76,15 +76,15 @@ export class SavegameInterface_V1006 extends SavegameInterface_V1005 { }; } - static migrate1005to1006(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1005to1006(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1005 to 1006"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } // Reduce stored shapes - const stored: any = dump.hubGoals.storedShapes; - for (const shapeKey: any in stored) { + const stored = dump.hubGoals.storedShapes; + for (const shapeKey in stored) { stored[shapeKey] = rebalance(stored[shapeKey]); } // Reset final game shape @@ -93,8 +93,8 @@ export class SavegameInterface_V1006 extends SavegameInterface_V1005 { if (dump.hubGoals.currentGoal) { dump.hubGoals.currentGoal.required = rebalance(dump.hubGoals.currentGoal.required); } - let level: any = Math.min(19, dump.hubGoals.level); - const levelMapping: any = { + let level = Math.min(19, dump.hubGoals.level); + const levelMapping = { 14: 15, 15: 16, 16: 17, @@ -104,10 +104,10 @@ export class SavegameInterface_V1006 extends SavegameInterface_V1005 { }; dump.hubGoals.level = levelMapping[level] || level; // Update entities - const entities: any = dump.entities; - for (let i: any = 0; i < entities.length; ++i) { - const entity: any = entities[i]; - const components: any = entity.components; + const entities = dump.entities; + for (let i = 0; i < entities.length; ++i) { + const entity = entities[i]; + const components = entity.components; this.migrateStaticComp1005to1006(entity); // HUB if (components.Hub) { @@ -174,9 +174,9 @@ export class SavegameInterface_V1006 extends SavegameInterface_V1005 { } } } - static migrateStaticComp1005to1006(entity: Entity): any { - const spriteMapping: any = this.computeSpriteMapping(); - const staticComp: any = entity.components.StaticMapEntity; + static migrateStaticComp1005to1006(entity: Entity) { + const spriteMapping = this.computeSpriteMapping(); + const staticComp = entity.components.StaticMapEntity; const newStaticComp: StaticMapEntityComponent = {}; newStaticComp.origin = staticComp.origin; newStaticComp.originalRotation = staticComp.originalRotation; @@ -189,7 +189,7 @@ export class SavegameInterface_V1006 extends SavegameInterface_V1005 { } // Belt special case if (entity.components.Belt) { - const actualCode: any = { + const actualCode = { top: findCode(MetaBeltBuilding, defaultBuildingVariant, 0), left: findCode(MetaBeltBuilding, defaultBuildingVariant, 1), right: findCode(MetaBeltBuilding, defaultBuildingVariant, 2), diff --git a/src/ts/savegame/schemas/1007.ts b/src/ts/savegame/schemas/1007.ts index 872d3cf8..66883184 100644 --- a/src/ts/savegame/schemas/1007.ts +++ b/src/ts/savegame/schemas/1007.ts @@ -1,25 +1,25 @@ import { createLogger } from "../../core/logging.js"; import { SavegameInterface_V1006 } from "./1006.js"; -const schema: any = require("./1007.json"); -const logger: any = createLogger("savegame_interface/1007"); +const schema = require("./1007.json"); +const logger = createLogger("savegame_interface/1007"); export class SavegameInterface_V1007 extends SavegameInterface_V1006 { - getVersion(): any { + getVersion() { return 1007; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1006to1007(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1006to1007(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1006 to 1007"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } - const waypoints: any = dump.waypoints.waypoints; + const waypoints = dump.waypoints.waypoints; // set waypoint layer to "regular" - for (let i: any = 0; i < waypoints.length; ++i) { - const waypoint: any = waypoints[i]; + for (let i = 0; i < waypoints.length; ++i) { + const waypoint = waypoints[i]; waypoint.layer = "regular"; } } diff --git a/src/ts/savegame/schemas/1008.ts b/src/ts/savegame/schemas/1008.ts index e8a41e41..0a325018 100644 --- a/src/ts/savegame/schemas/1008.ts +++ b/src/ts/savegame/schemas/1008.ts @@ -1,18 +1,18 @@ import { createLogger } from "../../core/logging.js"; import { SavegameInterface_V1007 } from "./1007.js"; -const schema: any = require("./1008.json"); -const logger: any = createLogger("savegame_interface/1008"); +const schema = require("./1008.json"); +const logger = createLogger("savegame_interface/1008"); export class SavegameInterface_V1008 extends SavegameInterface_V1007 { - getVersion(): any { + getVersion() { return 1008; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1007to1008(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1007to1008(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1007 to 1008"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } diff --git a/src/ts/savegame/schemas/1009.ts b/src/ts/savegame/schemas/1009.ts index 95de510d..5fbef077 100644 --- a/src/ts/savegame/schemas/1009.ts +++ b/src/ts/savegame/schemas/1009.ts @@ -1,19 +1,19 @@ import { createLogger } from "../../core/logging.js"; import { RegularGameMode } from "../../game/modes/regular.js"; import { SavegameInterface_V1008 } from "./1008.js"; -const schema: any = require("./1009.json"); -const logger: any = createLogger("savegame_interface/1009"); +const schema = require("./1009.json"); +const logger = createLogger("savegame_interface/1009"); export class SavegameInterface_V1009 extends SavegameInterface_V1008 { - getVersion(): any { + getVersion() { return 1009; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1008to1009(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1008to1009(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1008 to 1009"); - const dump: any = data.dump; + const dump = data.dump; if (!dump) { return true; } diff --git a/src/ts/savegame/schemas/1010.ts b/src/ts/savegame/schemas/1010.ts index 19d6dc92..a651f142 100644 --- a/src/ts/savegame/schemas/1010.ts +++ b/src/ts/savegame/schemas/1010.ts @@ -1,16 +1,16 @@ import { createLogger } from "../../core/logging.js"; import { SavegameInterface_V1009 } from "./1009.js"; -const schema: any = require("./1010.json"); -const logger: any = createLogger("savegame_interface/1010"); +const schema = require("./1010.json"); +const logger = createLogger("savegame_interface/1010"); export class SavegameInterface_V1010 extends SavegameInterface_V1009 { - getVersion(): any { + getVersion() { return 1010; } - getSchemaUncached(): any { + getSchemaUncached() { return schema; } - static migrate1009to1010(data: import("../savegame_typedefs.js").SavegameData): any { + static migrate1009to1010(data: import("../savegame_typedefs.js").SavegameData) { logger.log("Migrating 1009 to 1010"); data.mods = []; if (data.dump) { diff --git a/src/ts/savegame/serialization.ts b/src/ts/savegame/serialization.ts index 368077bc..f9fd8f48 100644 --- a/src/ts/savegame/serialization.ts +++ b/src/ts/savegame/serialization.ts @@ -1,8 +1,8 @@ import { createLogger } from "../core/logging"; import { BaseDataType, TypeArray, TypeBoolean, TypeClass, TypeClassData, TypeClassFromMetaclass, TypeClassId, TypeEntity, TypeEntityWeakref, TypeEnum, TypeFixedClass, TypeInteger, TypeKeyValueMap, TypeMetaClass, TypeNullable, TypeNumber, TypePair, TypePositiveInteger, TypePositiveNumber, TypeString, TypeStructuredObject, TypeVector, TypePositiveIntegerOrString, } from "./serialization_data_types"; -const logger: any = createLogger("serialization"); +const logger = createLogger("serialization"); // Schema declarations -export const types: any = { +export const types = { int: new TypeInteger(), uint: new TypePositiveInteger(), float: new TypeNumber(), @@ -14,55 +14,55 @@ export const types: any = { tileVector: new TypeVector(), bool: new TypeBoolean(), uintOrString: new TypePositiveIntegerOrString(), - nullable(wrapped: BaseDataType): any { + nullable(wrapped: BaseDataType) { return new TypeNullable(wrapped); }, - classId(registry: FactoryTemplate<*> | SingletonFactoryTemplate<*>): any { + classId(registry: FactoryTemplate<*> | SingletonFactoryTemplate<*>) { return new TypeClassId(registry); }, - keyValueMap(valueType: BaseDataType, includeEmptyValues: boolean= = true): any { + keyValueMap(valueType: BaseDataType, includeEmptyValues: boolean= = true) { return new TypeKeyValueMap(valueType, includeEmptyValues); }, enum(values: { [idx: string]: any; - }): any { + }) { return new TypeEnum(values); }, - obj(registry: FactoryTemplate<*>, resolver: (GameRoot, any) => object= = null): any { + obj(registry: FactoryTemplate<*>, resolver: (GameRoot, any) => object= = null) { return new TypeClass(registry, resolver); }, - objData(registry: FactoryTemplate<*>): any { + objData(registry: FactoryTemplate<*>) { return new TypeClassData(registry); }, - knownType(cls: typeof BasicSerializableObject): any { + knownType(cls: typeof BasicSerializableObject) { return new TypeFixedClass(cls); }, - array(innerType: BaseDataType): any { + array(innerType: BaseDataType) { return new TypeArray(innerType); }, - fixedSizeArray(innerType: BaseDataType): any { + fixedSizeArray(innerType: BaseDataType) { return new TypeArray(innerType, true); }, - classRef(registry: any): any { + classRef(registry) { return new TypeMetaClass(registry); }, structured(descriptor: { [idx: string]: BaseDataType; - }): any { + }) { return new TypeStructuredObject(descriptor); }, - pair(a: BaseDataType, b: BaseDataType): any { + pair(a: BaseDataType, b: BaseDataType) { return new TypePair(a, b); }, - classWithMetaclass(classHandle: typeof BasicSerializableObject, registry: SingletonFactoryTemplate<*>): any { + classWithMetaclass(classHandle: typeof BasicSerializableObject, registry: SingletonFactoryTemplate<*>) { return new TypeClassFromMetaclass(classHandle, registry); }, }; export type Schema = Object | object; -const globalSchemaCache: any = {}; +const globalSchemaCache = {}; /* dev:start */ -const classnamesCache: any = {}; +const classnamesCache = {}; /* dev:end*/ export class BasicSerializableObject { /* dev:start */ @@ -73,7 +73,7 @@ export class BasicSerializableObject { constructor(...args) { } /* dev:end */ - static getId(): any { + static getId() { abstract; } /** @@ -86,16 +86,16 @@ export class BasicSerializableObject { // Implementation /** {} */ static getCachedSchema(): Schema { - const id: any = this.getId(); + const id = this.getId(); /* dev:start */ assert(classnamesCache[id] === this || classnamesCache[id] === undefined, "Class name taken twice: " + id + " (from " + this.name + ")"); classnamesCache[id] = this; /* dev:end */ - const entry: any = globalSchemaCache[id]; + const entry = globalSchemaCache[id]; if (entry) { return entry; } - const schema: any = this.getSchema(); + const schema = this.getSchema(); globalSchemaCache[id] = schema; return schema; } @@ -114,7 +114,7 @@ export class BasicSerializableObject { this.constructor as typeof BasicSerializableObject).getCachedSchema(), data, null, root); } /** {} */ - static verify(data: any): string | void { + static verify(data): string | void { return verifySchema(this.getCachedSchema(), data); } } @@ -123,7 +123,7 @@ export class BasicSerializableObject { * {} Serialized data object */ export function serializeSchema(obj: object, schema: Schema, mergeWith: object= = {}): object { - for (const key: any in schema) { + for (const key in schema) { if (!obj.hasOwnProperty(key)) { logger.error("Invalid schema, property", key, "does not exist on", obj, "(schema=", schema, ")"); assert(obj.hasOwnProperty(key), "serialization: invalid schema, property does not exist on object: " + key); @@ -135,7 +135,7 @@ export function serializeSchema(obj: object, schema: Schema, mergeWith: object= try { mergeWith[key] = schema[key].serialize(obj[key]); } - catch (ex: any) { + catch (ex) { logger.error("Serialization of", obj, "failed on key '" + key + "' ->", ex, "(schema was", schema, ")"); throw ex; } @@ -158,7 +158,7 @@ export function deserializeSchema(obj: object, schema: Schema, data: object, bas logger.error("Got 'NULL' data for", obj, "and schema", schema, "!"); return "Got null data"; } - for (const key: any in schema) { + for (const key in schema) { if (!data.hasOwnProperty(key)) { logger.error("Data", data, "does not contain", key, "(schema:", schema, ")"); @@ -169,7 +169,7 @@ export function deserializeSchema(obj: object, schema: Schema, data: object, bas return "Non-nullable entry is null: " + key + " of class " + obj.constructor.name; } - const errorStatus: any = schema[key].deserializeWithVerify(data[key], obj, key, obj.root || root); + const errorStatus = schema[key].deserializeWithVerify(data[key], obj, key, obj.root || root); if (errorStatus) { logger.error("Deserialization failed with error '" + errorStatus + "' on object", obj, "and key", key, "(root? =", obj.root ? "y" : "n", ")"); return errorStatus; @@ -181,7 +181,7 @@ export function deserializeSchema(obj: object, schema: Schema, data: object, bas * {} String error code or nothing on success */ export function verifySchema(schema: Schema, data: object): string | void { - for (const key: any in schema) { + for (const key in schema) { if (!data.hasOwnProperty(key)) { logger.error("Data", data, "does not contain", key, "(schema:", schema, ")"); return "verify: missing key required by schema in stored data: " + key; @@ -190,7 +190,7 @@ export function verifySchema(schema: Schema, data: object): string | void { logger.error("Data", data, "has null value for", key, "(schema:", schema, ")"); return "verify: non-nullable entry is null: " + key; } - const errorStatus: any = schema[key].verifySerializedValue(data[key]); + const errorStatus = schema[key].verifySerializedValue(data[key]); if (errorStatus) { logger.error(errorStatus); return "verify: " + errorStatus; @@ -203,7 +203,7 @@ export function verifySchema(schema: Schema, data: object): string | void { */ export function extendSchema(base: Schema, newOne: Schema): Schema { const result: Schema = Object.assign({}, base); - for (const key: any in newOne) { + for (const key in newOne) { if (result.hasOwnProperty(key)) { logger.error("Extend schema got duplicate key:", key); continue; diff --git a/src/ts/savegame/serialization_data_types.ts b/src/ts/savegame/serialization_data_types.ts index 2e93bd79..ed6569c2 100644 --- a/src/ts/savegame/serialization_data_types.ts +++ b/src/ts/savegame/serialization_data_types.ts @@ -4,16 +4,16 @@ import type { BasicSerializableObject } from "./serialization"; /* typehints:end */ import { Vector } from "../core/vector"; import { round4Digits } from "../core/utils"; -export const globalJsonSchemaDefs: any = {}; -export function schemaToJsonSchema(schema: import("./serialization").Schema): any { - const jsonSchema: any = { +export const globalJsonSchemaDefs = {}; +export function schemaToJsonSchema(schema: import("./serialization").Schema) { + const jsonSchema = { type: "object", additionalProperties: false, required: [], properties: {}, }; - for (const key: any in schema) { - const subSchema: any = schema[key].getAsJsonSchema(); + for (const key in schema) { + const subSchema = schema[key].getAsJsonSchema(); jsonSchema.required.push(key); jsonSchema.properties[key] = subSchema; } @@ -22,7 +22,7 @@ export function schemaToJsonSchema(schema: import("./serialization").Schema): an /** * Helper function to create a json schema object */ -function schemaObject(properties: any): any { +function schemaObject(properties: any) { return { type: "object", required: Object.keys(properties).slice(), @@ -38,7 +38,7 @@ export class BaseDataType { * Serializes a given raw value * @abstract */ - serialize(value: any): any { + serialize(value: any) { abstract; return {}; } @@ -58,9 +58,9 @@ export class BaseDataType { /** * Returns the json schema */ - getAsJsonSchema(): any { - const key: any = this.getCacheKey(); - const schema: any = this.getAsJsonSchemaUncached(); + getAsJsonSchema() { + const key = this.getCacheKey(); + const schema = this.getAsJsonSchemaUncached(); if (!globalJsonSchemaDefs[key]) { // schema.$id = key; globalJsonSchemaDefs[key] = schema; @@ -73,7 +73,7 @@ export class BaseDataType { * INTERNAL Should return the json schema representation * @abstract */ - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { abstract; } /** @@ -89,7 +89,7 @@ export class BaseDataType { * {} String error code or null on success */ deserializeWithVerify(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - const errorCode: any = this.verifySerializedValue(value); + const errorCode = this.verifySerializedValue(value); if (errorCode) { return ("serialization verify failed: " + errorCode + @@ -103,13 +103,13 @@ export class BaseDataType { * Should return a cacheable key * @abstract */ - getCacheKey(): any { + getCacheKey() { abstract; return ""; } } export class TypeInteger extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(Number.isInteger(value), "Type integer got non integer for serialize: " + value); return value; } @@ -120,22 +120,22 @@ export class TypeInteger extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "integer", }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Number.isInteger(value)) { return "Not a valid number"; } } - getCacheKey(): any { + getCacheKey() { return "int"; } } export class TypePositiveInteger extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(Number.isInteger(value), "Type integer got non integer for serialize: " + value); assert(value >= 0, "value < 0: " + value); return value; @@ -147,13 +147,13 @@ export class TypePositiveInteger extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "integer", minimum: 0, }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Number.isInteger(value)) { return "Not a valid number"; } @@ -161,12 +161,12 @@ export class TypePositiveInteger extends BaseDataType { return "Negative value for positive integer"; } } - getCacheKey(): any { + getCacheKey() { return "uint"; } } export class TypePositiveIntegerOrString extends BaseDataType { - serialize(value: any): any { + serialize(value) { if (Number.isInteger(value)) { assert(value >= 0, "type integer got negative value: " + value); } @@ -185,12 +185,12 @@ export class TypePositiveIntegerOrString extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { oneOf: [{ type: "integer", minimum: 0 }, { type: "string" }], }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (Number.isInteger(value)) { if (value < 0) { return "Negative value for positive integer"; @@ -203,12 +203,12 @@ export class TypePositiveIntegerOrString extends BaseDataType { return "Not a valid number or string: " + value; } } - getCacheKey(): any { + getCacheKey() { return "uint_str"; } } export class TypeBoolean extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(value === true || value === false, "Type bool got non bool for serialize: " + value); return value; } @@ -219,22 +219,22 @@ export class TypeBoolean extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "boolean", }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (value !== true && value !== false) { return "Not a boolean"; } } - getCacheKey(): any { + getCacheKey() { return "bool"; } } export class TypeString extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(typeof value === "string", "Type string got non string for serialize: " + value); return value; } @@ -245,29 +245,29 @@ export class TypeString extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "string", }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (typeof value !== "string") { return "Not a valid string"; } } - getCacheKey(): any { + getCacheKey() { return "string"; } } export class TypeVector extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(value instanceof Vector, "Type vector got non vector for serialize: " + value); return { x: round4Digits(value.x), y: round4Digits(value.y), }; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return schemaObject({ x: { type: "number", @@ -284,23 +284,23 @@ export class TypeVector extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = new Vector(value.x, value.y); } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Number.isFinite(value.x) || !Number.isFinite(value.y)) { return "Not a valid vector, missing x/y or bad data type"; } } - getCacheKey(): any { + getCacheKey() { return "vector"; } } export class TypeTileVector extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(value instanceof Vector, "Type vector got non vector for serialize: " + value); assert(Number.isInteger(value.x) && value.x > 0, "Invalid tile x:" + value.x); assert(Number.isInteger(value.y) && value.y > 0, "Invalid tile x:" + value.y); return { x: value.x, y: value.y }; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return schemaObject({ x: { type: "integer", @@ -321,7 +321,7 @@ export class TypeTileVector extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = new Vector(value.x, value.y); } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Number.isInteger(value.x) || !Number.isInteger(value.y)) { return "Not a valid tile vector, missing x/y or bad data type"; } @@ -329,17 +329,17 @@ export class TypeTileVector extends BaseDataType { return "Invalid tile vector, x or y < 0"; } } - getCacheKey(): any { + getCacheKey() { return "tilevector"; } } export class TypeNumber extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(Number.isFinite(value), "Type number got non number for serialize: " + value); assert(!Number.isNaN(value), "Value is nan: " + value); return round4Digits(value); } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "number", }; @@ -351,17 +351,17 @@ export class TypeNumber extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Number.isFinite(value)) { return "Not a valid number: " + value; } } - getCacheKey(): any { + getCacheKey() { return "float"; } } export class TypePositiveNumber extends BaseDataType { - serialize(value: any): any { + serialize(value) { assert(Number.isFinite(value), "Type number got non number for serialize: " + value); assert(value >= 0, "Postitive number got negative value: " + value); return round4Digits(value); @@ -373,13 +373,13 @@ export class TypePositiveNumber extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "number", minimum: 0, }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Number.isFinite(value)) { return "Not a valid number: " + value; } @@ -387,7 +387,7 @@ export class TypePositiveNumber extends BaseDataType { return "Positive number got negative value: " + value; } } - getCacheKey(): any { + getCacheKey() { return "ufloat"; } } @@ -397,7 +397,7 @@ export class TypeEnum extends BaseDataType { constructor(enumeration = {}) { super(); } - serialize(value: any): any { + serialize(value) { assert(this.availableValues.indexOf(value) >= 0, "Unknown value: " + value); return value; } @@ -408,30 +408,30 @@ export class TypeEnum extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "string", enum: this.availableValues, }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (this.availableValues.indexOf(value) < 0) { return "Unknown enum value: " + value; } } - getCacheKey(): any { + getCacheKey() { return "enum." + this.availableValues.join(","); } } export class TypeEntity extends BaseDataType { - serialize(value: any): any { + serialize(value) { // assert(value instanceof Entity, "Not a valid entity ref: " + value); assert(value.uid, "Entity has no uid yet"); assert(!value.destroyed, "Entity already destroyed"); assert(!value.queuedForDestroy, "Entity queued for destroy"); return value.uid; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "integer", minimum: 0, @@ -442,23 +442,23 @@ export class TypeEntity extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - const entity: any = root.entityMgr.findByUid(value); + const entity = root.entityMgr.findByUid(value); if (!entity) { return "Entity not found by uid: " + value; } targetObject[targetKey] = entity; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Number.isFinite(value)) { return "Not a valid uuid: " + value; } } - getCacheKey(): any { + getCacheKey() { return "entity"; } } export class TypeEntityWeakref extends BaseDataType { - serialize(value: any): any { + serialize(value) { if (value === null) { return null; } @@ -478,24 +478,24 @@ export class TypeEntityWeakref extends BaseDataType { targetObject[targetKey] = null; return; } - const entity: any = root.entityMgr.findByUid(value, false); + const entity = root.entityMgr.findByUid(value, false); targetObject[targetKey] = entity; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: ["null", "integer"], minimum: 0, }; } - allowNull(): any { + allowNull() { return true; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (value !== null && !Number.isFinite(value)) { return "Not a valid uuid: " + value; } } - getCacheKey(): any { + getCacheKey() { return "entity-weakref"; } } @@ -506,7 +506,7 @@ export class TypeClass extends BaseDataType { constructor(registry, customResolver = null) { super(); } - serialize(value: any): any { + serialize(value) { assert(typeof value === "object", "Not a class instance: " + value); return { @@ -514,11 +514,11 @@ export class TypeClass extends BaseDataType { data: value.serialize(), }; } - getAsJsonSchemaUncached(): any { - const options: any = []; - const entries: any = this.registry.getEntries(); - for (let i: any = 0; i < entries.length; ++i) { - const entry: any = entries[i]; + getAsJsonSchemaUncached() { + const options = []; + const entries = this.registry.getEntries(); + for (let i = 0; i < entries.length; ++i) { + const entry = entries[i]; options.push(schemaObject({ $: { type: "string", @@ -536,7 +536,7 @@ export class TypeClass extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - let instance: any; + let instance; if (this.customResolver) { instance = this.customResolver(root, value); if (!instance) { @@ -544,19 +544,19 @@ export class TypeClass extends BaseDataType { } } else { - const instanceClass: any = this.registry.findById(value.$); + const instanceClass = this.registry.findById(value.$); if (!instanceClass || !instanceClass.prototype) { return "Invalid class id (runtime-err): " + value.$ + "->" + instanceClass; } instance = Object.create(instanceClass.prototype); - const errorState: any = instance.deserialize(value.data); + const errorState = instance.deserialize(value.data); if (errorState) { return errorState; } } targetObject[targetKey] = instance; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!value) { return "Got null data"; } @@ -564,7 +564,7 @@ export class TypeClass extends BaseDataType { return "Invalid class id: " + value.$ + " (factory is " + this.registry.getId() + ")"; } } - getCacheKey(): any { + getCacheKey() { return "class." + this.registry.getId(); } } @@ -574,15 +574,15 @@ export class TypeClassData extends BaseDataType { constructor(registry) { super(); } - serialize(value: any): any { + serialize(value) { assert(typeof value === "object", "Not a class instance: " + value); return value.serialize(); } - getAsJsonSchemaUncached(): any { - const options: any = []; - const entries: any = this.registry.getEntries(); - for (let i: any = 0; i < entries.length; ++i) { - const entry: any = entries[i]; + getAsJsonSchemaUncached() { + const options = []; + const entries = this.registry.getEntries(); + for (let i = 0; i < entries.length; ++i) { + const entry = entries[i]; options.push(schemaToJsonSchema(entry as typeof BasicSerializableObject).getCachedSchema())); } return { oneOf: options }; @@ -594,12 +594,12 @@ export class TypeClassData extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { assert(false, "can not deserialize class data of type " + this.registry.getId()); } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!value) { return "Got null data"; } } - getCacheKey(): any { + getCacheKey() { return "class." + this.registry.getId(); } } @@ -610,16 +610,16 @@ export class TypeClassFromMetaclass extends BaseDataType { constructor(classHandle, registry) { super(); } - serialize(value: any): any { + serialize(value) { assert(typeof value === "object", "Not a class instance: " + value); return { $: value.getMetaclass().getId(), data: value.serialize(), }; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { // const options = []; - const ids: any = this.registry.getAllIds(); + const ids = this.registry.getAllIds(); return { $: { type: "string", @@ -633,19 +633,19 @@ export class TypeClassFromMetaclass extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - const metaClassInstance: any = this.registry.findById(value.$); + const metaClassInstance = this.registry.findById(value.$); if (!metaClassInstance || !metaClassInstance.prototype) { return "Invalid meta class id (runtime-err): " + value.$ + "->" + metaClassInstance; } - const instanceClass: any = metaClassInstance.getInstanceClass(); - const instance: any = Object.create(instanceClass.prototype); - const errorState: any = instance.deserialize(value.data); + const instanceClass = metaClassInstance.getInstanceClass(); + const instance = Object.create(instanceClass.prototype); + const errorState = instance.deserialize(value.data); if (errorState) { return errorState; } targetObject[targetKey] = instance; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!value) { return "Got null data"; } @@ -653,7 +653,7 @@ export class TypeClassFromMetaclass extends BaseDataType { return "Invalid class id: " + value.$ + " (factory is " + this.registry.getId() + ")"; } } - getCacheKey(): any { + getCacheKey() { return "classofmetaclass." + this.registry.getId(); } } @@ -663,7 +663,7 @@ export class TypeMetaClass extends BaseDataType { constructor(registry) { super(); } - serialize(value: any): any { + serialize(value) { return value.getId(); } /** @@ -671,19 +671,19 @@ export class TypeMetaClass extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - const instanceClass: any = this.registry.findById(value); + const instanceClass = this.registry.findById(value); if (!instanceClass) { return "Invalid class id (runtime-err): " + value; } targetObject[targetKey] = instanceClass; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "string", enum: this.registry.getAllIds(), }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!value) { return "Got null data"; } @@ -694,7 +694,7 @@ export class TypeMetaClass extends BaseDataType { return "Invalid class id: " + value + " (factory is " + this.registry.getId() + ")"; } } - getCacheKey(): any { + getCacheKey() { return "metaclass." + this.registry.getId(); } } @@ -705,10 +705,10 @@ export class TypeArray extends BaseDataType { constructor(innerType, fixedSize = false) { super(); } - serialize(value: any): any { + serialize(value) { assert(Array.isArray(value), "Not an array"); - const result: any = new Array(value.length); - for (let i: any = 0; i < value.length; ++i) { + const result = new Array(value.length); + for (let i = 0; i < value.length; ++i) { result[i] = this.innerType.serialize(value[i]); } return result; @@ -718,30 +718,30 @@ export class TypeArray extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - let destination: any = targetObject[targetKey]; + let destination = targetObject[targetKey]; if (!destination) { targetObject[targetKey] = destination = new Array(value.length); } - const size: any = this.fixedSize ? Math.min(value.length, destination.length) : value.length; - for (let i: any = 0; i < size; ++i) { - const errorStatus: any = this.innerType.deserializeWithVerify(value[i], destination, i, root); + const size = this.fixedSize ? Math.min(value.length, destination.length) : value.length; + for (let i = 0; i < size; ++i) { + const errorStatus = this.innerType.deserializeWithVerify(value[i], destination, i, root); if (errorStatus) { return errorStatus; } } } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "array", items: this.innerType.getAsJsonSchema(), }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Array.isArray(value)) { return "Not an array: " + value; } } - getCacheKey(): any { + getCacheKey() { return "array." + this.innerType.getCacheKey(); } } @@ -751,7 +751,7 @@ export class TypeFixedClass extends BaseDataType { constructor(baseclass) { super(); } - serialize(value: any): any { + serialize(value) { assert(value instanceof this.baseclass, "Not a valid class instance"); return value.serialize(); } @@ -760,24 +760,24 @@ export class TypeFixedClass extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - const instance: any = Object.create(this.baseclass.prototype); - const errorState: any = instance.deserialize(value); + const instance = Object.create(this.baseclass.prototype); + const errorState = instance.deserialize(value); if (errorState) { return "Failed to deserialize class: " + errorState; } targetObject[targetKey] = instance; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { this.baseclass.getSchema(); this.baseclass.getCachedSchema(); return schemaToJsonSchema(this.baseclass.getCachedSchema()); } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!value) { return "Got null data"; } } - getCacheKey(): any { + getCacheKey() { return "fixedclass." + this.baseclass.getId(); } } @@ -788,11 +788,11 @@ export class TypeKeyValueMap extends BaseDataType { constructor(valueType, includeEmptyValues = true) { super(); } - serialize(value: any): any { + serialize(value) { assert(typeof value === "object", "not an object"); - let result: any = {}; - for (const key: any in value) { - const serialized: any = this.valueType.serialize(value[key]); + let result = {}; + for (const key in value) { + const serialized = this.valueType.serialize(value[key]); if (!this.includeEmptyValues && typeof serialized === "object") { if (serialized.$ && typeof serialized.data === "object" && @@ -812,27 +812,27 @@ export class TypeKeyValueMap extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - let result: any = {}; - for (const key: any in value) { - const errorCode: any = this.valueType.deserializeWithVerify(value[key], result, key, root); + let result = {}; + for (const key in value) { + const errorCode = this.valueType.deserializeWithVerify(value[key], result, key, root); if (errorCode) { return errorCode; } } targetObject[targetKey] = result; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "object", additionalProperties: this.valueType.getAsJsonSchema(), }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (typeof value !== "object") { return "KV map is not an object"; } } - getCacheKey(): any { + getCacheKey() { return "kvmap." + this.valueType.getCacheKey(); } } @@ -842,7 +842,7 @@ export class TypeClassId extends BaseDataType { constructor(registry) { super(); } - serialize(value: any): any { + serialize(value) { assert(typeof value === "string", "Not a valid string"); assert(this.registry.hasId(value), "Id " + value + " not found in registry"); return value; @@ -854,13 +854,13 @@ export class TypeClassId extends BaseDataType { deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { targetObject[targetKey] = value; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "string", enum: this.registry.getAllIds(), }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (typeof value !== "string") { return "Not a valid registry id key: " + value; } @@ -868,7 +868,7 @@ export class TypeClassId extends BaseDataType { return "Id " + value + " not known to registry"; } } - getCacheKey(): any { + getCacheKey() { return "classid." + this.registry.getId(); } } @@ -881,7 +881,7 @@ export class TypePair extends BaseDataType { assert(type1 && type1 instanceof BaseDataType, "bad first type given for pair"); assert(type2 && type2 instanceof BaseDataType, "bad second type given for pair"); } - serialize(value: any): any { + serialize(value) { assert(Array.isArray(value), "pair: not an array"); assert(value.length === 2, "pair: length != 2"); return [this.type1.serialize(value[0]), this.type2.serialize(value[1])]; @@ -891,8 +891,8 @@ export class TypePair extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - const result: any = [undefined, undefined]; - let errorCode: any = this.type1.deserialize(value[0], result, 0, root); + const result = [undefined, undefined]; + let errorCode = this.type1.deserialize(value[0], result, 0, root); if (errorCode) { return errorCode; } @@ -902,7 +902,7 @@ export class TypePair extends BaseDataType { } targetObject[targetKey] = result; } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { type: "array", minLength: 2, @@ -910,14 +910,14 @@ export class TypePair extends BaseDataType { items: [this.type1.getAsJsonSchema(), this.type2.getAsJsonSchema()], }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (!Array.isArray(value)) { return "Pair is not an array"; } if (value.length !== 2) { return "Pair length != 2"; } - let errorCode: any = this.type1.verifySerializedValue(value[0]); + let errorCode = this.type1.verifySerializedValue(value[0]); if (errorCode) { return errorCode; } @@ -926,7 +926,7 @@ export class TypePair extends BaseDataType { return errorCode; } } - getCacheKey(): any { + getCacheKey() { return "pair.(" + this.type1.getCacheKey() + "," + this.type2.getCacheKey + ")"; } } @@ -936,7 +936,7 @@ export class TypeNullable extends BaseDataType { constructor(wrapped) { super(); } - serialize(value: any): any { + serialize(value) { if (value === null || value === undefined) { return null; } @@ -953,13 +953,13 @@ export class TypeNullable extends BaseDataType { } return this.wrapped.deserialize(value, targetObject, targetKey, root); } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (value === null) { return; } return this.wrapped.verifySerializedValue(value); } - getAsJsonSchemaUncached(): any { + getAsJsonSchemaUncached() { return { oneOf: [ { @@ -969,10 +969,10 @@ export class TypeNullable extends BaseDataType { ], }; } - allowNull(): any { + allowNull() { return true; } - getCacheKey(): any { + getCacheKey() { return "nullable." + this.wrapped.getCacheKey(); } } @@ -982,10 +982,10 @@ export class TypeStructuredObject extends BaseDataType { constructor(descriptor) { super(); } - serialize(value: any): any { + serialize(value) { assert(typeof value === "object", "not an object"); - let result: any = {}; - for (const key: any in this.descriptor) { + let result = {}; + for (const key in this.descriptor) { // assert(value.hasOwnProperty(key), "Serialization: Object does not have", key, "property!"); result[key] = this.descriptor[key].serialize(value[key]); } @@ -996,21 +996,21 @@ export class TypeStructuredObject extends BaseDataType { * {} String error code or null on success */ deserialize(value: any, targetObject: object, targetKey: string | number, root: GameRoot): string | void { - let target: any = targetObject[targetKey]; + let target = targetObject[targetKey]; if (!target) { targetObject[targetKey] = target = {}; } - for (const key: any in value) { - const valueType: any = this.descriptor[key]; - const errorCode: any = valueType.deserializeWithVerify(value[key], target, key, root); + for (const key in value) { + const valueType = this.descriptor[key]; + const errorCode = valueType.deserializeWithVerify(value[key], target, key, root); if (errorCode) { return errorCode; } } } - getAsJsonSchemaUncached(): any { - let properties: any = {}; - for (const key: any in this.descriptor) { + getAsJsonSchemaUncached() { + let properties = {}; + for (const key in this.descriptor) { properties[key] = this.descriptor[key].getAsJsonSchema(); } return { @@ -1019,23 +1019,23 @@ export class TypeStructuredObject extends BaseDataType { properties, }; } - verifySerializedValue(value: any): any { + verifySerializedValue(value) { if (typeof value !== "object") { return "structured object is not an object"; } - for (const key: any in this.descriptor) { + for (const key in this.descriptor) { if (!value.hasOwnProperty(key)) { return "structured object is missing key " + key; } - const subError: any = this.descriptor[key].verifySerializedValue(value[key]); + const subError = this.descriptor[key].verifySerializedValue(value[key]); if (subError) { return "structured object::" + subError; } } } - getCacheKey(): any { - let props: any = []; - for (const key: any in this.descriptor) { + getCacheKey() { + let props = []; + for (const key in this.descriptor) { props.push(key + "=" + this.descriptor[key].getCacheKey()); } return "structured[" + props.join(",") + "]"; diff --git a/src/ts/savegame/serializer_internal.ts b/src/ts/savegame/serializer_internal.ts index e95dfff0..d4d84e95 100644 --- a/src/ts/savegame/serializer_internal.ts +++ b/src/ts/savegame/serializer_internal.ts @@ -4,16 +4,16 @@ import { Vector } from "../core/vector"; import { getBuildingDataFromCode } from "../game/building_codes"; import { Entity } from "../game/entity"; import { GameRoot } from "../game/root"; -const logger: any = createLogger("serializer_internal"); +const logger = createLogger("serializer_internal"); // Internal serializer methods export class SerializerInternal { /** * Serializes an array of entities */ - serializeEntityArray(array: Array): any { - const serialized: any = []; - for (let i: any = 0; i < array.length; ++i) { - const entity: any = array[i]; + serializeEntityArray(array: Array) { + const serialized = []; + for (let i = 0; i < array.length; ++i) { + const entity = array[i]; if (!entity.queuedForDestroy && !entity.destroyed) { serialized.push(entity.serialize()); } @@ -25,17 +25,17 @@ export class SerializerInternal { * {} */ deserializeEntityArray(root: GameRoot, array: Array): string | void { - for (let i: any = 0; i < array.length; ++i) { + for (let i = 0; i < array.length; ++i) { this.deserializeEntity(root, array[i]); } } - deserializeEntity(root: GameRoot, payload: Entity): any { - const staticData: any = payload.components.StaticMapEntity; + deserializeEntity(root: GameRoot, payload: Entity) { + const staticData = payload.components.StaticMapEntity; assert(staticData, "entity has no static data"); - const code: any = staticData.code; - const data: any = getBuildingDataFromCode(code); - const metaBuilding: any = data.metaInstance; - const entity: any = metaBuilding.createEntity({ + const code = staticData.code; + const data = getBuildingDataFromCode(code); + const metaBuilding = data.metaInstance; + const entity = metaBuilding.createEntity({ root, origin: Vector.fromSerializedObject(staticData.origin), rotation: staticData.rotation, @@ -56,7 +56,7 @@ export class SerializerInternal { deserializeComponents(root: GameRoot, entity: Entity, data: { [idx: string]: any; }): string | void { - for (const componentId: any in data) { + for (const componentId in data) { if (!entity.components[componentId]) { if (G_IS_DEV && !globalConfig.debug.disableSlowAsserts) { // @ts-ignore @@ -66,7 +66,7 @@ export class SerializerInternal { } continue; } - const errorStatus: any = entity.components[componentId].deserialize(data[componentId], root); + const errorStatus = entity.components[componentId].deserialize(data[componentId], root); if (errorStatus) { return errorStatus; } diff --git a/src/ts/states/about.ts b/src/ts/states/about.ts index de4da471..38dbc712 100644 --- a/src/ts/states/about.ts +++ b/src/ts/states/about.ts @@ -8,10 +8,10 @@ export class AboutState extends TextualGameState { constructor() { super("AboutState"); } - getStateHeaderTitle(): any { + getStateHeaderTitle() { return T.about.title; } - getMainContentHTML(): any { + getMainContentHTML() { return `
shapez.io Logo @@ -23,13 +23,13 @@ export class AboutState extends TextualGameState {
`; } - onEnter(): any { - const links: any = this.htmlElement.querySelectorAll("a[href]"); - links.forEach((link: any): any => { - this.trackClicks(link, (): any => this.app.platformWrapper.openExternalLink(link.getAttribute("href")), { preventClick: true }); + onEnter() { + const links = this.htmlElement.querySelectorAll("a[href]"); + links.forEach(link => { + this.trackClicks(link, () => this.app.platformWrapper.openExternalLink(link.getAttribute("href")), { preventClick: true }); }); } - getDefaultPreviousState(): any { + getDefaultPreviousState() { return "SettingsState"; } } diff --git a/src/ts/states/changelog.ts b/src/ts/states/changelog.ts index f46524d2..10fcf3fd 100644 --- a/src/ts/states/changelog.ts +++ b/src/ts/states/changelog.ts @@ -6,30 +6,30 @@ export class ChangelogState extends TextualGameState { constructor() { super("ChangelogState"); } - getStateHeaderTitle(): any { + getStateHeaderTitle() { return T.changelog.title; } - getMainContentHTML(): any { - const entries: any = CHANGELOG; - let html: any = ""; - for (let i: any = 0; i < entries.length; ++i) { - const entry: any = entries[i]; + getMainContentHTML() { + const entries = CHANGELOG; + let html = ""; + for (let i = 0; i < entries.length; ++i) { + const entry = entries[i]; html += `
${entry.version} ${entry.date}
    - ${entry.entries.map((text: any): any => `
  • ${text}
  • `).join("")} + ${entry.entries.map(text => `
  • ${text}
  • `).join("")}
`; } return html; } - onEnter(): any { - const links: any = this.htmlElement.querySelectorAll("a[href]"); - links.forEach((link: any): any => { - this.trackClicks(link, (): any => this.app.platformWrapper.openExternalLink(link.getAttribute("href")), { preventClick: true }); + onEnter() { + const links = this.htmlElement.querySelectorAll("a[href]"); + links.forEach(link => { + this.trackClicks(link, () => this.app.platformWrapper.openExternalLink(link.getAttribute("href")), { preventClick: true }); }); } } diff --git a/src/ts/states/ingame.ts b/src/ts/states/ingame.ts index 36a0db2b..74c1c19c 100644 --- a/src/ts/states/ingame.ts +++ b/src/ts/states/ingame.ts @@ -11,9 +11,9 @@ import { enumGameModeIds } from "../game/game_mode"; import { MOD_SIGNALS } from "../mods/mod_signals"; import { HUDModalDialogs } from "../game/hud/parts/modal_dialogs"; import { T } from "../translations"; -const logger: any = createLogger("state/ingame"); +const logger = createLogger("state/ingame"); // Different sub-states -export const GAME_LOADING_STATES: any = { +export const GAME_LOADING_STATES = { s3_createCore: "s3_createCore", s4_A_initEmptyGame: "s4_A_initEmptyGame", s4_B_resumeGame: "s4_B_resumeGame", @@ -25,7 +25,7 @@ export const GAME_LOADING_STATES: any = { destroyed: "destroyed", initFailed: "initFailed", }; -export const gameCreationAction: any = { +export const gameCreationAction = { new: "new-game", resume: "resume-game", }; @@ -58,7 +58,7 @@ export class InGameState extends GameState { /** * Switches the game into another sub-state */ - switchStage(stage: string): any { + switchStage(stage: string) { assert(stage, "Got empty stage"); if (stage !== this.stage) { this.stage = stage; @@ -72,31 +72,31 @@ export class InGameState extends GameState { } } // GameState implementation - getInnerHTML(): any { + getInnerHTML() { return ""; } - onAppPause(): any { + onAppPause() { // if (this.stage === stages.s10_gameRunning) { // logger.log("Saving because app got paused"); // this.doSave(); // } } - getHasFadeIn(): any { + getHasFadeIn() { return false; } - getPauseOnFocusLost(): any { + getPauseOnFocusLost() { return false; } - getHasUnloadConfirmation(): any { + getHasUnloadConfirmation() { return true; } - onLeave(): any { + onLeave() { if (this.core) { this.stageDestroyed(); } this.app.inputMgr.dismountFilter(this.boundInputFilter); } - onResized(w: any, h: any): any { + onResized(w, h) { super.onResized(w, h); if (this.stage === GAME_LOADING_STATES.s10_gameRunning) { this.core.resize(w, h); @@ -106,7 +106,7 @@ export class InGameState extends GameState { /** * Goes back to the menu state */ - goBackToMenu(): any { + goBackToMenu() { if ([enumGameModeIds.puzzleEdit, enumGameModeIds.puzzlePlay].includes(this.gameModeId)) { this.saveThenGoToState("PuzzleMenuState"); } @@ -117,7 +117,7 @@ export class InGameState extends GameState { /** * Goes back to the settings state */ - goToSettings(): any { + goToSettings() { this.saveThenGoToState("SettingsState", { backToStateId: this.key, backToStatePayload: this.creationPayload, @@ -126,7 +126,7 @@ export class InGameState extends GameState { /** * Goes back to the settings state */ - goToKeybindings(): any { + goToKeybindings() { this.saveThenGoToState("KeybindingsState", { backToStateId: this.key, backToStatePayload: this.creationPayload, @@ -135,21 +135,21 @@ export class InGameState extends GameState { /** * Moves to a state outside of the game */ - saveThenGoToState(stateId: string, payload: any=): any { + saveThenGoToState(stateId: string, payload: any=) { if (this.stage === GAME_LOADING_STATES.leaving || this.stage === GAME_LOADING_STATES.destroyed) { logger.warn("Tried to leave game twice or during destroy:", this.stage, "(attempted to move to", stateId, ")"); return; } this.stageLeavingGame(); - this.doSave().then((): any => { + this.doSave().then(() => { this.stageDestroyed(); this.moveToState(stateId, payload); }); } - onBackButton(): any { + onBackButton() { // do nothing } - getIsIngame(): any { + getIsIngame() { return (this.stage === GAME_LOADING_STATES.s10_gameRunning && this.core && !this.core.root.hud.shouldPauseGame()); @@ -158,7 +158,7 @@ export class InGameState extends GameState { * Called when the game somehow failed to initialize. Resets everything to basic state and * then goes to the main menu, showing the error */ - onInitializationFailure(err: string): any { + onInitializationFailure(err: string) { if (this.switchStage(GAME_LOADING_STATES.initFailed)) { logger.error("Init failure:", err); this.stageDestroyed(); @@ -169,13 +169,13 @@ export class InGameState extends GameState { /** * Creates the game core instance, and thus the root */ - stage3CreateCore(): any { + stage3CreateCore() { if (this.switchStage(GAME_LOADING_STATES.s3_createCore)) { logger.log("Waiting for resources to load"); - this.app.backgroundResourceLoader.resourceStateChangedSignal.add(({ progress }: any): any => { + this.app.backgroundResourceLoader.resourceStateChangedSignal.add(({ progress }) => { this.loadingOverlay.loadingIndicator.innerText = T.global.loadingResources.replace("", (progress * 100.0).toFixed(1)); }); - this.app.backgroundResourceLoader.getIngamePromise().then((): any => { + this.app.backgroundResourceLoader.getIngamePromise().then(() => { if (this.creationPayload.gameModeId && this.creationPayload.gameModeId.includes("puzzle")) { this.app.sound.playThemeMusic(MUSIC.puzzle); @@ -195,10 +195,10 @@ export class InGameState extends GameState { this.app.gameAnalytics.handleGameStarted(); this.stage4aInitEmptyGame(); } - }, (err: any): any => { + }, err => { logger.error("Failed to preload resources:", err); - const dialogs: any = new HUDModalDialogs(null, this.app); - const dialogsElement: any = document.createElement("div"); + const dialogs = new HUDModalDialogs(null, this.app); + const dialogsElement = document.createElement("div"); dialogsElement.id = "ingame_HUD_ModalDialogs"; dialogsElement.style.zIndex = "999999"; document.body.appendChild(dialogsElement); @@ -210,7 +210,7 @@ export class InGameState extends GameState { /** * Initializes a new empty game */ - stage4aInitEmptyGame(): any { + stage4aInitEmptyGame() { if (this.switchStage(GAME_LOADING_STATES.s4_A_initEmptyGame)) { this.core.initNewGame(); this.stage5FirstUpdate(); @@ -219,7 +219,7 @@ export class InGameState extends GameState { /** * Resumes an existing game */ - stage4bResumeGame(): any { + stage4bResumeGame() { if (this.switchStage(GAME_LOADING_STATES.s4_B_resumeGame)) { if (!this.core.initExistingGame()) { this.onInitializationFailure("Savegame is corrupt and can not be restored."); @@ -232,7 +232,7 @@ export class InGameState extends GameState { /** * Performs the first game update on the game which initializes most caches */ - stage5FirstUpdate(): any { + stage5FirstUpdate() { if (this.switchStage(GAME_LOADING_STATES.s5_firstUpdate)) { this.core.root.logicInitialized = true; this.core.updateLogic(); @@ -243,7 +243,7 @@ export class InGameState extends GameState { * Call the post load hook, this means that we have loaded the game, and all systems * can operate and start to work now. */ - stage6PostLoadHook(): any { + stage6PostLoadHook() { if (this.switchStage(GAME_LOADING_STATES.s6_postLoadHook)) { logger.log("Post load hook"); this.core.postLoadHook(); @@ -255,7 +255,7 @@ export class InGameState extends GameState { * the V8 engine can already start to optimize it. Also this makes sure the resources * are in the VRAM and we have a smooth experience once we start. */ - stage7Warmup(): any { + stage7Warmup() { if (this.switchStage(GAME_LOADING_STATES.s7_warmup)) { if (this.creationPayload.fastEnter) { this.warmupTimeSeconds = globalConfig.warmupTimeSecondsFast; @@ -268,7 +268,7 @@ export class InGameState extends GameState { /** * The final stage where this game is running and updating regulary. */ - stage10GameRunning(): any { + stage10GameRunning() { if (this.switchStage(GAME_LOADING_STATES.s10_gameRunning)) { this.core.root.signals.readyToRender.dispatch(); logSection("GAME STARTED", "#26a69a"); @@ -280,7 +280,7 @@ export class InGameState extends GameState { /** * This stage destroys the whole game, used to cleanup */ - stageDestroyed(): any { + stageDestroyed() { if (this.switchStage(GAME_LOADING_STATES.destroyed)) { // Cleanup all api calls this.cancelAllAsyncOperations(); @@ -298,7 +298,7 @@ export class InGameState extends GameState { /** * When leaving the game */ - stageLeavingGame(): any { + stageLeavingGame() { if (this.switchStage(GAME_LOADING_STATES.leaving)) { // ... } @@ -307,10 +307,10 @@ export class InGameState extends GameState { /** * Filters the input (keybindings) */ - filterInput(): any { + filterInput() { return this.stage === GAME_LOADING_STATES.s10_gameRunning; } - onEnter(payload: GameCreationPayload): any { + onEnter(payload: GameCreationPayload) { this.app.inputMgr.installFilter(this.boundInputFilter); this.creationPayload = payload; this.savegame = payload.savegame; @@ -321,8 +321,8 @@ export class InGameState extends GameState { document.body.querySelector(".modalDialogParent").remove(); this.asyncChannel .watch(waitNextFrame()) - .then((): any => this.stage3CreateCore()) - .catch((ex: any): any => { + .then(() => this.stage3CreateCore()) + .catch(ex => { logger.error(ex); throw ex; }); @@ -330,7 +330,7 @@ export class InGameState extends GameState { /** * Render callback */ - onRender(dt: number): any { + onRender(dt: number) { if (window.APP_ERROR_OCCURED) { // Application somehow crashed, do not do anything return; @@ -360,13 +360,13 @@ export class InGameState extends GameState { } } } - onBackgroundTick(dt: any): any { + onBackgroundTick(dt) { this.onRender(dt); } /** * Saves the game */ - doSave(): any { + doSave() { if (!this.savegame || !this.savegame.isSaveable()) { return Promise.resolve(); } @@ -391,11 +391,11 @@ export class InGameState extends GameState { this.savegame.updateData(this.core.root); this.currentSavePromise = this.savegame .writeSavegameAndMetadata() - .catch((err: any): any => { + .catch(err => { // Catch errors logger.warn("Failed to save:", err); }) - .then((): any => { + .then(() => { // Clear promise logger.log("Saved!"); this.core.root.signals.gameSaved.dispatch(); diff --git a/src/ts/states/keybindings.ts b/src/ts/states/keybindings.ts index 81f3dbf2..f50a64fa 100644 --- a/src/ts/states/keybindings.ts +++ b/src/ts/states/keybindings.ts @@ -8,10 +8,10 @@ export class KeybindingsState extends TextualGameState { constructor() { super("KeybindingsState"); } - getStateHeaderTitle(): any { + getStateHeaderTitle() { return T.keybindings.title; } - getMainContentHTML(): any { + getMainContentHTML() { return `
@@ -25,44 +25,44 @@ export class KeybindingsState extends TextualGameState {
`; } - onEnter(): any { - const keybindingsElem: any = this.htmlElement.querySelector(".keybindings"); + onEnter() { + const keybindingsElem = this.htmlElement.querySelector(".keybindings"); this.trackClicks(this.htmlElement.querySelector(".resetBindings"), this.resetBindings); - for (const category: any in KEYMAPPINGS) { + for (const category in KEYMAPPINGS) { if (Object.keys(KEYMAPPINGS[category]).length === 0) { continue; } - const categoryDiv: any = document.createElement("div"); + const categoryDiv = document.createElement("div"); categoryDiv.classList.add("category"); keybindingsElem.appendChild(categoryDiv); - const labelDiv: any = document.createElement("strong"); + const labelDiv = document.createElement("strong"); labelDiv.innerText = T.keybindings.categoryLabels[category]; labelDiv.classList.add("categoryLabel"); categoryDiv.appendChild(labelDiv); - for (const keybindingId: any in KEYMAPPINGS[category]) { - const mapped: any = KEYMAPPINGS[category][keybindingId]; - const elem: any = document.createElement("div"); + for (const keybindingId in KEYMAPPINGS[category]) { + const mapped = KEYMAPPINGS[category][keybindingId]; + const elem = document.createElement("div"); elem.classList.add("entry"); elem.setAttribute("data-keybinding", keybindingId); categoryDiv.appendChild(elem); - const title: any = document.createElement("span"); + const title = document.createElement("span"); title.classList.add("title"); title.innerText = T.keybindings.mappings[keybindingId]; elem.appendChild(title); - const mappingDiv: any = document.createElement("span"); + const mappingDiv = document.createElement("span"); mappingDiv.classList.add("mapping"); elem.appendChild(mappingDiv); - const editBtn: any = document.createElement("button"); + const editBtn = document.createElement("button"); editBtn.classList.add("styledButton", "editKeybinding"); - const resetBtn: any = document.createElement("button"); + const resetBtn = document.createElement("button"); resetBtn.classList.add("styledButton", "resetKeybinding"); if (mapped.builtin) { editBtn.classList.add("disabled"); resetBtn.classList.add("disabled"); } else { - this.trackClicks(editBtn, (): any => this.editKeybinding(keybindingId)); - this.trackClicks(resetBtn, (): any => this.resetKeybinding(keybindingId)); + this.trackClicks(editBtn, () => this.editKeybinding(keybindingId)); + this.trackClicks(resetBtn, () => this.resetKeybinding(keybindingId)); } elem.appendChild(editBtn); elem.appendChild(resetBtn); @@ -70,15 +70,15 @@ export class KeybindingsState extends TextualGameState { } this.updateKeybindings(); } - editKeybinding(id: any): any { - const dialog: any = new Dialog({ + editKeybinding(id) { + const dialog = new Dialog({ app: this.app, title: T.dialogs.editKeybinding.title, contentHTML: T.dialogs.editKeybinding.desc, buttons: ["cancel:good"], type: "info", }); - dialog.inputReciever.keydown.add(({ keyCode, shift, alt, event }: any): any => { + dialog.inputReciever.keydown.add(({ keyCode, shift, alt, event }) => { if (keyCode === 27) { this.dialogs.closeDialog(dialog); return; @@ -99,23 +99,23 @@ export class KeybindingsState extends TextualGameState { this.dialogs.closeDialog(dialog); this.updateKeybindings(); }); - dialog.inputReciever.backButton.add((): any => { }); + dialog.inputReciever.backButton.add(() => { }); this.dialogs.internalShowDialog(dialog); this.app.sound.playUiSound(SOUNDS.dialogOk); } - updateKeybindings(): any { - const overrides: any = this.app.settings.getKeybindingOverrides(); - for (const category: any in KEYMAPPINGS) { - for (const keybindingId: any in KEYMAPPINGS[category]) { - const mapped: any = KEYMAPPINGS[category][keybindingId]; - const container: any = this.htmlElement.querySelector("[data-keybinding='" + keybindingId + "']"); + updateKeybindings() { + const overrides = this.app.settings.getKeybindingOverrides(); + for (const category in KEYMAPPINGS) { + for (const keybindingId in KEYMAPPINGS[category]) { + const mapped = KEYMAPPINGS[category][keybindingId]; + const container = this.htmlElement.querySelector("[data-keybinding='" + keybindingId + "']"); assert(container, "Container for keybinding not found: " + keybindingId); - let keyCode: any = mapped.keyCode; + let keyCode = mapped.keyCode; if (overrides[keybindingId]) { keyCode = overrides[keybindingId]; } - const mappingDiv: any = container.querySelector(".mapping"); - let modifiers: any = ""; + const mappingDiv = container.querySelector(".mapping"); + let modifiers = ""; if (mapped.modifiers && mapped.modifiers.shift) { modifiers += "⇪ "; } @@ -127,24 +127,24 @@ export class KeybindingsState extends TextualGameState { } mappingDiv.innerHTML = modifiers + getStringForKeyCode(keyCode); mappingDiv.classList.toggle("changed", !!overrides[keybindingId]); - const resetBtn: any = container.querySelector("button.resetKeybinding"); + const resetBtn = container.querySelector("button.resetKeybinding"); resetBtn.classList.toggle("disabled", mapped.builtin || !overrides[keybindingId]); } } } - resetKeybinding(id: any): any { + resetKeybinding(id) { this.app.settings.resetKeybindingOverride(id); this.updateKeybindings(); } - resetBindings(): any { - const { reset }: any = this.dialogs.showWarning(T.dialogs.resetKeybindingsConfirmation.title, T.dialogs.resetKeybindingsConfirmation.desc, ["cancel:good", "reset:bad"]); - reset.add((): any => { + resetBindings() { + const { reset } = this.dialogs.showWarning(T.dialogs.resetKeybindingsConfirmation.title, T.dialogs.resetKeybindingsConfirmation.desc, ["cancel:good", "reset:bad"]); + reset.add(() => { this.app.settings.resetKeybindingOverrides(); this.updateKeybindings(); this.dialogs.showInfo(T.dialogs.keybindingsResetOk.title, T.dialogs.keybindingsResetOk.desc); }); } - getDefaultPreviousState(): any { + getDefaultPreviousState() { return "SettingsState"; } } diff --git a/src/ts/states/login.ts b/src/ts/states/login.ts index 2cefd748..bea326d9 100644 --- a/src/ts/states/login.ts +++ b/src/ts/states/login.ts @@ -7,7 +7,7 @@ export class LoginState extends GameState { constructor() { super("LoginState"); } - getInnerHTML(): any { + getInnerHTML() { return `
@@ -19,13 +19,13 @@ export class LoginState extends GameState { } onEnter(payload: { nextStateId: string; - }): any { + }) { this.payload = payload; if (!this.payload.nextStateId) { throw new Error("No next state id"); } this.dialogs = new HUDModalDialogs(null, this.app); - const dialogsElement: any = document.body.querySelector(".modalDialogParent"); + const dialogsElement = document.body.querySelector(".modalDialogParent"); this.dialogs.initializeToElement(dialogsElement); this.htmlElement.classList.add("prefab_LoadingState"); this.hintsText = this.htmlElement.querySelector(".prefab_GameHint"); @@ -33,12 +33,12 @@ export class LoginState extends GameState { this.nextHintDuration = 0; this.tryLogin(); } - tryLogin(): any { - this.app.clientApi.tryLogin().then((success: any): any => { + tryLogin() { + this.app.clientApi.tryLogin().then(success => { console.log("Logged in:", success); if (!success) { - const signals: any = this.dialogs.showWarning(T.dialogs.offlineMode.title, T.dialogs.offlineMode.desc, ["retry", "playOffline:bad"]); - signals.retry.add((): any => setTimeout((): any => this.tryLogin(), 2000), this); + const signals = this.dialogs.showWarning(T.dialogs.offlineMode.title, T.dialogs.offlineMode.desc, ["retry", "playOffline:bad"]); + signals.retry.add(() => setTimeout(() => this.tryLogin(), 2000), this); signals.playOffline.add(this.finishLoading, this); } else { @@ -46,17 +46,17 @@ export class LoginState extends GameState { } }); } - finishLoading(): any { + finishLoading() { this.moveToState(this.payload.nextStateId); } - getDefaultPreviousState(): any { + getDefaultPreviousState() { return "MainMenuState"; } - update(): any { - const now: any = performance.now(); + update() { + const now = performance.now(); if (now - this.lastHintShown > this.nextHintDuration) { this.lastHintShown = now; - const hintText: any = getRandomHint(); + const hintText = getRandomHint(); this.hintsText.innerHTML = hintText; /** * Compute how long the user will need to read the hint. @@ -66,10 +66,10 @@ export class LoginState extends GameState { this.nextHintDuration = Math.max(2500, (hintText.length / 650) * 60 * 1000); } } - onRender(): any { + onRender() { this.update(); } - onBackgroundTick(): any { + onBackgroundTick() { this.update(); } } diff --git a/src/ts/states/main_menu.ts b/src/ts/states/main_menu.ts index 91ca4510..dcac3091 100644 --- a/src/ts/states/main_menu.ts +++ b/src/ts/states/main_menu.ts @@ -13,7 +13,7 @@ import { PlatformWrapperImplBrowser } from "../platform/browser/wrapper"; import { PlatformWrapperImplElectron } from "../platform/electron/wrapper"; import { Savegame } from "../savegame/savegame"; import { T } from "../translations"; -const trim: any = require("trim"); +const trim = require("trim"); export type SavegameMetadata = import("../savegame/savegame_typedefs").SavegameMetadata; export type EnumSetting = import("../profile/setting_types").EnumSetting; @@ -23,30 +23,30 @@ export class MainMenuState extends GameState { constructor() { super("MainMenuState"); } - getInnerHTML(): any { - const showExitAppButton: any = G_IS_STANDALONE; - const showPuzzleDLC: any = G_IS_STANDALONE || WEB_STEAM_SSO_AUTHENTICATED; - const hasMods: any = MODS.anyModsActive(); - let showExternalLinks: any = true; + getInnerHTML() { + const showExitAppButton = G_IS_STANDALONE; + const showPuzzleDLC = G_IS_STANDALONE || WEB_STEAM_SSO_AUTHENTICATED; + const hasMods = MODS.anyModsActive(); + let showExternalLinks = true; if (!G_IS_STANDALONE) { - const wrapper: any = (this.app.platformWrapper as PlatformWrapperImplBrowser); + const wrapper = this.app.platformWrapper as PlatformWrapperImplBrowser); if (!wrapper.embedProvider.externalLinks) { showExternalLinks = false; } } - const showDemoAdvertisement: any = showExternalLinks && this.app.restrictionMgr.getIsStandaloneMarketingActive(); - const ownsPuzzleDLC: any = WEB_STEAM_SSO_AUTHENTICATED || + const showDemoAdvertisement = showExternalLinks && this.app.restrictionMgr.getIsStandaloneMarketingActive(); + const ownsPuzzleDLC = WEB_STEAM_SSO_AUTHENTICATED || (G_IS_STANDALONE && this.app.platformWrapper as PlatformWrapperImplElectron).dlcs.puzzle); - const showShapez2: any = showExternalLinks && MODS.mods.length === 0; - const bannerHtml: any = ` + const showShapez2 = showExternalLinks && MODS.mods.length === 0; + const bannerHtml = `

${T.demoBanners.titleV2}

${Array.from(Object.entries(T.ingame.standaloneAdvantages.points)) .slice(0, 6) - .map(([key, trans]: any): any => ` + .map(([key, trans]) => `
${trans.title}

${trans.desc}

@@ -155,7 +155,7 @@ export class MainMenuState extends GameState {
${MODS.mods - .map((mod: any): any => { + .map(mod => { return `
${mod.metadata.name}
@@ -252,7 +252,7 @@ export class MainMenuState extends GameState { /** * Asks the user to import a savegame */ - requestImportSavegame(): any { + requestImportSavegame() { if (this.app.savegameMgr.getSavegamesMetaData().length > 0 && !this.app.restrictionMgr.getHasUnlimitedSavegames()) { this.showSavegameSlotLimit(); @@ -260,33 +260,33 @@ export class MainMenuState extends GameState { } this.app.gameAnalytics.note("startimport"); // Create a 'fake' file-input to accept savegames - startFileChoose(".bin").then((file: any): any => { + startFileChoose(".bin").then(file => { if (file) { - const closeLoader: any = this.dialogs.showLoadingDialog(); - waitNextFrame().then((): any => { - const reader: any = new FileReader(); - reader.addEventListener("load", (event: any): any => { - const contents: any = event.target.result; - let realContent: any; + const closeLoader = this.dialogs.showLoadingDialog(); + waitNextFrame().then(() => { + const reader = new FileReader(); + reader.addEventListener("load", event => { + const contents = event.target.result; + let realContent; try { realContent = ReadWriteProxy.deserializeObject(contents); } - catch (err: any) { + catch (err) { closeLoader(); this.dialogs.showWarning(T.dialogs.importSavegameError.title, T.dialogs.importSavegameError.text + "

" + err); return; } - this.app.savegameMgr.importSavegame(realContent).then((): any => { + this.app.savegameMgr.importSavegame(realContent).then(() => { closeLoader(); this.dialogs.showWarning(T.dialogs.importSavegameSuccess.title, T.dialogs.importSavegameSuccess.text); this.renderMainMenu(); this.renderSavegames(); - }, (err: any): any => { + }, err => { closeLoader(); this.dialogs.showWarning(T.dialogs.importSavegameError.title, T.dialogs.importSavegameError.text + ":

" + err); }); }); - reader.addEventListener("error", (error: any): any => { + reader.addEventListener("error", error => { this.dialogs.showWarning(T.dialogs.importSavegameError.title, T.dialogs.importSavegameError.text + ":

" + error); }); reader.readAsText(file, "utf-8"); @@ -294,15 +294,15 @@ export class MainMenuState extends GameState { } }); } - onBackButton(): any { + onBackButton() { this.app.platformWrapper.exitApp(); } - onEnter(payload: any): any { + onEnter(payload) { // Start loading already - const app: any = this.app; - setTimeout((): any => app.backgroundResourceLoader.getIngamePromise(), 10); + const app = this.app; + setTimeout(() => app.backgroundResourceLoader.getIngamePromise(), 10); this.dialogs = new HUDModalDialogs(null, this.app); - const dialogsElement: any = document.body.querySelector(".modalDialogParent"); + const dialogsElement = document.body.querySelector(".modalDialogParent"); this.dialogs.initializeToElement(dialogsElement); if (payload.loadError) { this.dialogs.showWarning(T.dialogs.gameLoadFailure.title, T.dialogs.gameLoadFailure.text + "

" + payload.loadError); @@ -312,7 +312,7 @@ export class MainMenuState extends GameState { return; } if (G_IS_DEV && globalConfig.debug.fastGameEnter) { - const games: any = this.app.savegameMgr.getSavegamesMetaData(); + const games = this.app.savegameMgr.getSavegamesMetaData(); if (games.length > 0 && globalConfig.debug.resumeGameOnFastEnter) { this.resumeGame(games[0]); } @@ -323,12 +323,12 @@ export class MainMenuState extends GameState { // Initialize video this.videoElement = this.htmlElement.querySelector("video"); this.videoElement.playbackRate = 0.9; - this.videoElement.addEventListener("canplay", (): any => { + this.videoElement.addEventListener("canplay", () => { if (this.videoElement) { this.videoElement.classList.add("loaded"); } }); - const clickHandling: any = { + const clickHandling = { ".settingsButton": this.onSettingsButtonClicked, ".languageChoose": this.onLanguageChooseClicked, ".redditLink": this.onRedditClicked, @@ -340,10 +340,10 @@ export class MainMenuState extends GameState { ".steamLink": this.onSteamLinkClicked, ".steamLinkSocial": this.onSteamLinkClickedSocial, ".shapez2": this.onShapez2Clicked, - ".discordLink": (): any => { + ".discordLink": () => { this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.discord); }, - ".githubLink": (): any => { + ".githubLink": () => { this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.github); }, ".puzzleDlcPlayButton": this.onPuzzleModeButtonClicked, @@ -351,9 +351,9 @@ export class MainMenuState extends GameState { ".wegameDisclaimer > .rating": this.onWegameRatingClicked, ".editMods": this.onModsClicked, }; - for (const key: any in clickHandling) { - const handler: any = clickHandling[key]; - const element: any = this.htmlElement.querySelector(key); + for (const key in clickHandling) { + const handler = clickHandling[key]; + const element = this.htmlElement.querySelector(key); if (element) { this.trackClicks(element, handler, { preventClick: true }); } @@ -361,13 +361,13 @@ export class MainMenuState extends GameState { this.renderMainMenu(); this.renderSavegames(); this.fetchPlayerCount(); - this.refreshInterval = setInterval((): any => this.fetchPlayerCount(), 10000); + this.refreshInterval = setInterval(() => this.fetchPlayerCount(), 10000); this.app.gameAnalytics.noteMinor("menu.enter"); } - renderMainMenu(): any { - const buttonContainer: any = this.htmlElement.querySelector(".mainContainer .buttons"); + renderMainMenu() { + const buttonContainer = this.htmlElement.querySelector(".mainContainer .buttons"); removeAllChildren(buttonContainer); - const outerDiv: any = makeDivElement(null, ["outer"], null); + const outerDiv = makeDivElement(null, ["outer"], null); // Import button this.trackClicks(makeButton(outerDiv, ["importButton", "styledButton"], T.mainMenu.importSavegame), this.requestImportSavegame); if (this.savedGames.length > 0) { @@ -387,7 +387,7 @@ export class MainMenuState extends GameState { this.trackClicks(makeButton(outerDiv, ["modsButton", "styledButton"], T.mods.title), this.onModsClicked); buttonContainer.appendChild(outerDiv); } - fetchPlayerCount(): any { + fetchPlayerCount() { const element: HTMLDivElement = this.htmlElement.querySelector(".onlinePlayerCount"); if (!element) { return; @@ -395,70 +395,70 @@ export class MainMenuState extends GameState { fetch("https://analytics.shapez.io/v1/player-count", { cache: "no-cache", }) - .then((res: any): any => res.json()) - .then((count: any): any => { + .then(res => res.json()) + .then(count => { element.innerText = T.demoBanners.playerCount.replace("", String(count)); - }, (ex: any): any => { + }, ex => { console.warn("Failed to get player count:", ex); }); } - onPuzzleModeButtonClicked(force: any = false): any { - const hasUnlockedBlueprints: any = this.app.savegameMgr.getSavegamesMetaData().some((s: any): any => s.level >= 12); + onPuzzleModeButtonClicked(force = false) { + const hasUnlockedBlueprints = this.app.savegameMgr.getSavegamesMetaData().some(s => s.level >= 12); if (!force && !hasUnlockedBlueprints) { - const { ok }: any = this.dialogs.showWarning(T.dialogs.puzzlePlayRegularRecommendation.title, T.dialogs.puzzlePlayRegularRecommendation.desc, ["cancel:good", "ok:bad:timeout"]); - ok.add((): any => this.onPuzzleModeButtonClicked(true)); + const { ok } = this.dialogs.showWarning(T.dialogs.puzzlePlayRegularRecommendation.title, T.dialogs.puzzlePlayRegularRecommendation.desc, ["cancel:good", "ok:bad:timeout"]); + ok.add(() => this.onPuzzleModeButtonClicked(true)); return; } this.moveToState("LoginState", { nextStateId: "PuzzleMenuState", }); } - onPuzzleWishlistButtonClicked(): any { + onPuzzleWishlistButtonClicked() { this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.puzzleDlcStorePage); } - onShapez2Clicked(): any { + onShapez2Clicked() { this.app.platformWrapper.openExternalLink("https://tobspr.io/shapez-2?utm_medium=shapez"); } - onBackButtonClicked(): any { + onBackButtonClicked() { this.renderMainMenu(); this.renderSavegames(); } - onSteamLinkClicked(): any { + onSteamLinkClicked() { openStandaloneLink(this.app, "shapez_mainmenu"); return false; } - onSteamLinkClickedSocial(): any { + onSteamLinkClickedSocial() { openStandaloneLink(this.app, "shapez_mainmenu_social"); return false; } - onExitAppButtonClicked(): any { + onExitAppButtonClicked() { this.app.platformWrapper.exitApp(); } - onChangelogClicked(): any { + onChangelogClicked() { this.moveToState("ChangelogState"); } - onRedditClicked(): any { + onRedditClicked() { this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.reddit); } - onTwitterLinkClicked(): any { + onTwitterLinkClicked() { this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.twitter); } - onPatreonLinkClicked(): any { + onPatreonLinkClicked() { this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.patreon); } - onLanguageChooseClicked(): any { - const setting: any = (this.app.settings.getSettingHandleById("language") as EnumSetting); - const { optionSelected }: any = this.dialogs.showOptionChooser(T.settings.labels.language.title, { + onLanguageChooseClicked() { + const setting = this.app.settings.getSettingHandleById("language") as EnumSetting); + const { optionSelected } = this.dialogs.showOptionChooser(T.settings.labels.language.title, { active: this.app.settings.getLanguage(), - options: setting.options.map((option: any): any => ({ + options: setting.options.map(option => ({ value: setting.valueGetter(option), text: setting.textGetter(option), desc: setting.descGetter(option), iconPrefix: setting.iconPrefix, })), }); - optionSelected.add((value: any): any => { - this.app.settings.updateLanguage(value).then((): any => { + optionSelected.add(value => { + this.app.settings.updateLanguage(value).then(() => { if (setting.restartRequired) { if (this.app.platformWrapper.getSupportsRestart()) { this.app.platformWrapper.performRestart(); @@ -478,59 +478,59 @@ export class MainMenuState extends GameState { get savedGames() { return this.app.savegameMgr.getSavegamesMetaData(); } - renderSavegames(): any { - const oldContainer: any = this.htmlElement.querySelector(".mainContainer .savegames"); + renderSavegames() { + const oldContainer = this.htmlElement.querySelector(".mainContainer .savegames"); if (oldContainer) { oldContainer.remove(); } - const games: any = this.savedGames; + const games = this.savedGames; if (games.length > 0) { - const parent: any = makeDiv(this.htmlElement.querySelector(".mainContainer .savegamesMount"), null, [ + const parent = makeDiv(this.htmlElement.querySelector(".mainContainer .savegamesMount"), null, [ "savegames", ]); - for (let i: any = 0; i < games.length; ++i) { - const elem: any = makeDiv(parent, null, ["savegame"]); + for (let i = 0; i < games.length; ++i) { + const elem = makeDiv(parent, null, ["savegame"]); makeDiv(elem, null, ["playtime"], formatSecondsToTimeAgo((new Date().getTime() - games[i].lastUpdate) / 1000.0)); makeDiv(elem, null, ["level"], games[i].level ? T.mainMenu.savegameLevel.replace("", "" + games[i].level) : T.mainMenu.savegameLevelUnknown); - const name: any = makeDiv(elem, null, ["name"], "" + (games[i].name ? games[i].name : T.mainMenu.savegameUnnamed) + ""); - const deleteButton: any = document.createElement("button"); + const name = makeDiv(elem, null, ["name"], "" + (games[i].name ? games[i].name : T.mainMenu.savegameUnnamed) + ""); + const deleteButton = document.createElement("button"); deleteButton.classList.add("styledButton", "deleteGame"); deleteButton.setAttribute("aria-label", "Delete"); elem.appendChild(deleteButton); - const downloadButton: any = document.createElement("button"); + const downloadButton = document.createElement("button"); downloadButton.classList.add("styledButton", "downloadGame"); downloadButton.setAttribute("aria-label", "Download"); elem.appendChild(downloadButton); - const renameButton: any = document.createElement("button"); + const renameButton = document.createElement("button"); renameButton.classList.add("styledButton", "renameGame"); renameButton.setAttribute("aria-label", "Rename Savegame"); name.appendChild(renameButton); - this.trackClicks(renameButton, (): any => this.requestRenameSavegame(games[i])); - const resumeButton: any = document.createElement("button"); + this.trackClicks(renameButton, () => this.requestRenameSavegame(games[i])); + const resumeButton = document.createElement("button"); resumeButton.classList.add("styledButton", "resumeGame"); resumeButton.setAttribute("aria-label", "Resumee"); elem.appendChild(resumeButton); - this.trackClicks(deleteButton, (): any => this.deleteGame(games[i])); - this.trackClicks(downloadButton, (): any => this.downloadGame(games[i])); - this.trackClicks(resumeButton, (): any => this.resumeGame(games[i])); + this.trackClicks(deleteButton, () => this.deleteGame(games[i])); + this.trackClicks(downloadButton, () => this.downloadGame(games[i])); + this.trackClicks(resumeButton, () => this.resumeGame(games[i])); } } else { - const parent: any = makeDiv(this.htmlElement.querySelector(".mainContainer .savegamesMount"), null, ["savegamesNone"], T.mainMenu.noActiveSavegames); + const parent = makeDiv(this.htmlElement.querySelector(".mainContainer .savegamesMount"), null, ["savegamesNone"], T.mainMenu.noActiveSavegames); } } - requestRenameSavegame(game: SavegameMetadata): any { - const regex: any = /^[a-zA-Z0-9_\- ]{1,20}$/; - const nameInput: any = new FormElementInput({ + requestRenameSavegame(game: SavegameMetadata) { + const regex = /^[a-zA-Z0-9_\- ]{1,20}$/; + const nameInput = new FormElementInput({ id: "nameInput", label: null, placeholder: "", defaultValue: game.name || "", - validator: (val: any): any => val.match(regex) && trim(val).length > 0, + validator: val => val.match(regex) && trim(val).length > 0, }); - const dialog: any = new DialogWithForm({ + const dialog = new DialogWithForm({ app: this.app, title: T.dialogs.renameSavegame.title, desc: T.dialogs.renameSavegame.desc, @@ -539,36 +539,36 @@ export class MainMenuState extends GameState { }); this.dialogs.internalShowDialog(dialog); // When confirmed, save the name - dialog.buttonSignals.ok.add((): any => { + dialog.buttonSignals.ok.add(() => { game.name = trim(nameInput.getValue()); this.app.savegameMgr.writeAsync(); this.renderSavegames(); }); } - resumeGame(game: SavegameMetadata): any { - this.app.adProvider.showVideoAd().then((): any => { - const savegame: any = this.app.savegameMgr.getSavegameById(game.internalId); + resumeGame(game: SavegameMetadata) { + this.app.adProvider.showVideoAd().then(() => { + const savegame = this.app.savegameMgr.getSavegameById(game.internalId); savegame .readAsync() - .then((): any => this.checkForModDifferences(savegame)) - .then((): any => { + .then(() => this.checkForModDifferences(savegame)) + .then(() => { this.moveToState("InGameState", { savegame, }); }) - .catch((err: any): any => { + .catch(err => { this.dialogs.showWarning(T.dialogs.gameLoadFailure.title, T.dialogs.gameLoadFailure.text + "

" + err); }); }); } - checkForModDifferences(savegame: Savegame): any { - const difference: any = MODS.computeModDifference(savegame.currentData.mods); + checkForModDifferences(savegame: Savegame) { + const difference = MODS.computeModDifference(savegame.currentData.mods); if (difference.missing.length === 0 && difference.extra.length === 0) { return Promise.resolve(); } - let dialogHtml: any = T.dialogs.modsDifference.desc; + let dialogHtml = T.dialogs.modsDifference.desc; - function formatMod(mod: import("../savegame/savegame_typedefs").SavegameStoredMods[0]): any { + function formatMod(mod: import("../savegame/savegame_typedefs").SavegameStoredMods[0]) { return `
${mod.name}
@@ -587,68 +587,68 @@ export class MainMenuState extends GameState { dialogHtml += "

" + T.dialogs.modsDifference.newMods + "

"; dialogHtml += difference.extra.map(formatMod).join("
"); } - const signals: any = this.dialogs.showWarning(T.dialogs.modsDifference.title, dialogHtml, [ + const signals = this.dialogs.showWarning(T.dialogs.modsDifference.title, dialogHtml, [ "cancel:good", "continue:bad", ]); - return new Promise((resolve: any): any => { + return new Promise(resolve => { signals.continue.add(resolve); }); } - deleteGame(game: SavegameMetadata): any { - const signals: any = this.dialogs.showWarning(T.dialogs.confirmSavegameDelete.title, T.dialogs.confirmSavegameDelete.text + deleteGame(game: SavegameMetadata) { + const signals = this.dialogs.showWarning(T.dialogs.confirmSavegameDelete.title, T.dialogs.confirmSavegameDelete.text .replace("", game.name || T.mainMenu.savegameUnnamed) .replace("", String(game.level)), ["cancel:good", "delete:bad:timeout"]); - signals.delete.add((): any => { - this.app.savegameMgr.deleteSavegame(game).then((): any => { + signals.delete.add(() => { + this.app.savegameMgr.deleteSavegame(game).then(() => { this.renderSavegames(); if (this.savedGames.length <= 0) this.renderMainMenu(); - }, (err: any): any => { + }, err => { this.dialogs.showWarning(T.dialogs.savegameDeletionError.title, T.dialogs.savegameDeletionError.text + "

" + err); }); }); } - downloadGame(game: SavegameMetadata): any { - const savegame: any = this.app.savegameMgr.getSavegameById(game.internalId); - savegame.readAsync().then((): any => { - const data: any = ReadWriteProxy.serializeObject(savegame.currentData); - const filename: any = (game.name || "unnamed") + ".bin"; + downloadGame(game: SavegameMetadata) { + const savegame = this.app.savegameMgr.getSavegameById(game.internalId); + savegame.readAsync().then(() => { + const data = ReadWriteProxy.serializeObject(savegame.currentData); + const filename = (game.name || "unnamed") + ".bin"; generateFileDownload(filename, data); }); } /** * Shows a hint that the slot limit has been reached */ - showSavegameSlotLimit(): any { - const { getStandalone }: any = this.dialogs.showWarning(T.dialogs.oneSavegameLimit.title, T.dialogs.oneSavegameLimit.desc, ["cancel:bad", "getStandalone:good"]); - getStandalone.add((): any => { + showSavegameSlotLimit() { + const { getStandalone } = this.dialogs.showWarning(T.dialogs.oneSavegameLimit.title, T.dialogs.oneSavegameLimit.desc, ["cancel:bad", "getStandalone:good"]); + getStandalone.add(() => { openStandaloneLink(this.app, "shapez_slotlimit"); }); this.app.gameAnalytics.note("slotlimit"); } - onSettingsButtonClicked(): any { + onSettingsButtonClicked() { this.moveToState("SettingsState"); } - onTranslationHelpLinkClicked(): any { + onTranslationHelpLinkClicked() { this.app.platformWrapper.openExternalLink("https://github.com/tobspr-games/shapez.io/blob/master/translations"); } - onPlayButtonClicked(): any { + onPlayButtonClicked() { if (this.app.savegameMgr.getSavegamesMetaData().length > 0 && !this.app.restrictionMgr.getHasUnlimitedSavegames()) { this.app.gameAnalytics.noteMinor("menu.slotlimit"); this.showSavegameSlotLimit(); return; } - this.app.adProvider.showVideoAd().then((): any => { + this.app.adProvider.showVideoAd().then(() => { this.app.gameAnalytics.noteMinor("menu.play"); - const savegame: any = this.app.savegameMgr.createNewSavegame(); + const savegame = this.app.savegameMgr.createNewSavegame(); this.moveToState("InGameState", { savegame, }); }); } - onWegameRatingClicked(): any { + onWegameRatingClicked() { this.dialogs.showInfo("提示说明:", ` 1)本游戏是一款休闲建造类单机游戏,画面简洁而乐趣充足。适用于年满8周岁及以上的用户,建议未成年人在家长监护下使用游戏产品。
2)本游戏模拟简单的生产流水线,剧情简单且积极向上,没有基于真实历史和现实事件的改编内容。游戏玩法为摆放简单的部件,完成生产目标。游戏为单机作品,没有基于文字和语音的陌生人社交系统。
@@ -656,22 +656,22 @@ export class MainMenuState extends GameState { 4)游戏功能说明:一款关于传送带自动化生产特定形状产品的工厂流水线模拟游戏,画面简洁而乐趣充足,可以让玩家在轻松愉快的氛围下获得各种游戏乐趣,体验完成目标的成就感。游戏没有失败功能,自动存档,不存在较强的挫折体验。 `); } - onModsClicked(): any { + onModsClicked() { this.app.gameAnalytics.noteMinor("menu.mods"); this.moveToState("ModsState", { backToStateId: "MainMenuState", }); } - onContinueButtonClicked(): any { - let latestLastUpdate: any = 0; - let latestInternalId: any; - this.app.savegameMgr.currentData.savegames.forEach((saveGame: any): any => { + onContinueButtonClicked() { + let latestLastUpdate = 0; + let latestInternalId; + this.app.savegameMgr.currentData.savegames.forEach(saveGame => { if (saveGame.lastUpdate > latestLastUpdate) { latestLastUpdate = saveGame.lastUpdate; latestInternalId = saveGame.internalId; } }); - const savegame: any = this.app.savegameMgr.getSavegameById(latestInternalId); + const savegame = this.app.savegameMgr.getSavegameById(latestInternalId); if (!savegame) { console.warn("No savegame to continue found:", this.app.savegameMgr.currentData.savegames); return; @@ -679,15 +679,15 @@ export class MainMenuState extends GameState { this.app.gameAnalytics.noteMinor("menu.continue"); savegame .readAsync() - .then((): any => this.app.adProvider.showVideoAd()) - .then((): any => this.checkForModDifferences(savegame)) - .then((): any => { + .then(() => this.app.adProvider.showVideoAd()) + .then(() => this.checkForModDifferences(savegame)) + .then(() => { this.moveToState("InGameState", { savegame, }); }); } - onLeave(): any { + onLeave() { this.dialogs.cleanup(); clearInterval(this.refreshInterval); } diff --git a/src/ts/states/mobile_warning.ts b/src/ts/states/mobile_warning.ts index aa61e5d7..bfb5da86 100644 --- a/src/ts/states/mobile_warning.ts +++ b/src/ts/states/mobile_warning.ts @@ -5,7 +5,7 @@ export class MobileWarningState extends GameState { constructor() { super("MobileWarningState"); } - getInnerHTML(): any { + getInnerHTML() { return ` @@ -17,13 +17,13 @@ export class MobileWarningState extends GameState { Play on Steam! `; } - getThemeMusic(): any { + getThemeMusic() { return null; } - getHasFadeIn(): any { + getHasFadeIn() { return false; } - onEnter(): any { + onEnter() { try { if (window.gtag) { window.gtag("event", "click", { @@ -32,11 +32,11 @@ export class MobileWarningState extends GameState { }); } } - catch (ex: any) { + catch (ex) { console.warn("Failed to track mobile click:", ex); } } - onLeave(): any { + onLeave() { // this.dialogs.cleanup(); } } diff --git a/src/ts/states/mods.ts b/src/ts/states/mods.ts index ce41c894..5ccda1d7 100644 --- a/src/ts/states/mods.ts +++ b/src/ts/states/mods.ts @@ -8,15 +8,15 @@ export class ModsState extends TextualGameState { constructor() { super("ModsState"); } - getStateHeaderTitle(): any { + getStateHeaderTitle() { return T.mods.title; } get modsSupported() { return (!WEB_STEAM_SSO_AUTHENTICATED && (G_IS_STANDALONE || (G_IS_DEV && !window.location.href.includes("demo")))); } - internalGetFullHtml(): any { - let headerHtml: any = ` + internalGetFullHtml() { + let headerHtml = `

${this.getStateHeaderTitle()}

@@ -37,7 +37,7 @@ export class ModsState extends TextualGameState {
`; } - getMainContentHTML(): any { + getMainContentHTML() { if (!this.modsSupported) { return `
@@ -62,8 +62,8 @@ export class ModsState extends TextualGameState { `; } - let modsHtml: any = ``; - MODS.mods.forEach((mod: any): any => { + let modsHtml = ``; + MODS.mods.forEach(mod => { modsHtml += `
@@ -91,42 +91,42 @@ export class ModsState extends TextualGameState {
`; } - onEnter(): any { - const steamLink: any = this.htmlElement.querySelector(".steamLink"); + onEnter() { + const steamLink = this.htmlElement.querySelector(".steamLink"); if (steamLink) { this.trackClicks(steamLink, this.onSteamLinkClicked); } - const openModsFolder: any = this.htmlElement.querySelector(".openModsFolder"); + const openModsFolder = this.htmlElement.querySelector(".openModsFolder"); if (openModsFolder) { this.trackClicks(openModsFolder, this.openModsFolder); } - const browseMods: any = this.htmlElement.querySelector(".browseMods"); + const browseMods = this.htmlElement.querySelector(".browseMods"); if (browseMods) { this.trackClicks(browseMods, this.openBrowseMods); } - const checkboxes: any = this.htmlElement.querySelectorAll(".checkbox"); - Array.from(checkboxes).forEach((checkbox: any): any => { + const checkboxes = this.htmlElement.querySelectorAll(".checkbox"); + Array.from(checkboxes).forEach(checkbox => { this.trackClicks(checkbox, this.showModTogglingComingSoon); }); } - showModTogglingComingSoon(): any { + showModTogglingComingSoon() { this.dialogs.showWarning(T.mods.togglingComingSoon.title, T.mods.togglingComingSoon.description); } - openModsFolder(): any { + openModsFolder() { if (!G_IS_STANDALONE) { this.dialogs.showWarning(T.global.error, T.mods.folderOnlyStandalone); return; } ipcRenderer.invoke("open-mods-folder"); } - openBrowseMods(): any { + openBrowseMods() { this.app.platformWrapper.openExternalLink(THIRDPARTY_URLS.modBrowser); } - onSteamLinkClicked(): any { + onSteamLinkClicked() { openStandaloneLink(this.app, "shapez_modsettings"); return false; } - getDefaultPreviousState(): any { + getDefaultPreviousState() { return "SettingsState"; } } diff --git a/src/ts/states/preload.ts b/src/ts/states/preload.ts index 3ede7877..ebdd021e 100644 --- a/src/ts/states/preload.ts +++ b/src/ts/states/preload.ts @@ -10,24 +10,24 @@ import { getRandomHint } from "../game/hints"; import { HUDModalDialogs } from "../game/hud/parts/modal_dialogs"; import { PlatformWrapperImplBrowser } from "../platform/browser/wrapper"; import { autoDetectLanguageId, T, updateApplicationLanguage } from "../translations"; -const logger: any = createLogger("state/preload"); +const logger = createLogger("state/preload"); export class PreloadState extends GameState { constructor() { super("PreloadState"); } - getThemeMusic(): any { + getThemeMusic() { return null; } - getHasFadeIn(): any { + getHasFadeIn() { return false; } - getRemovePreviousContent(): any { + getRemovePreviousContent() { return false; } - onEnter(): any { + onEnter() { this.dialogs = new HUDModalDialogs(null, this.app); - const dialogsElement: any = document.body.querySelector(".modalDialogParent"); + const dialogsElement = document.body.querySelector(".modalDialogParent"); this.dialogs.initializeToElement(dialogsElement); this.hintsText = this.htmlElement.querySelector("#preload_ll_text"); this.lastHintShown = -1000; @@ -36,17 +36,17 @@ export class PreloadState extends GameState { this.progressElement = this.htmlElement.querySelector("#ll_progressbar span"); this.startLoading(); } - async fetchDiscounts(): any { + async fetchDiscounts() { await timeoutPromise(fetch("https://analytics.shapez.io/v1/discounts") - .then((res: any): any => res.json()) - .then((data: any): any => { + .then(res => res.json()) + .then(data => { globalConfig.currentDiscount = Number(data["1318690"].data.price_overview.discount_percent); logger.log("Fetched current discount:", globalConfig.currentDiscount); - }), 2000).catch((err: any): any => { + }), 2000).catch(err => { logger.warn("Failed to fetch current discount:", err); }); } - async sendBeacon(): any { + async sendBeacon() { if (G_IS_STANDALONE) { return; } @@ -56,46 +56,46 @@ export class PreloadState extends GameState { "?lpurl=nocontent&fbclid=" + (queryParamOptions.fbclid || "") + "&gclid=" + - (queryParamOptions.gclid || "")).catch((err: any): any => { + (queryParamOptions.gclid || "")).catch(err => { console.warn("Failed to send beacon:", err); }); } if (queryParamOptions.embedProvider) { fetch("https://analytics.shapez.io/campaign/embed_" + queryParamOptions.embedProvider + - "?lpurl=nocontent").catch((err: any): any => { + "?lpurl=nocontent").catch(err => { console.warn("Failed to send beacon:", err); }); } } - onLeave(): any { + onLeave() { // this.dialogs.cleanup(); } - startLoading(): any { + startLoading() { this.setStatus("Booting") - .then((): any => { + .then(() => { try { window.localStorage.setItem("local_storage_feature_detection", "1"); } - catch (ex: any) { + catch (ex) { throw new Error("Could not access local storage. Make sure you are not playing in incognito mode and allow thirdparty cookies!"); } }) - .then((): any => this.setStatus("Creating platform wrapper", 3)) - .then((): any => this.sendBeacon()) - .then((): any => authorizeViaSSOToken(this.app, this.dialogs)) - .then((): any => this.app.platformWrapper.initialize()) - .then((): any => this.setStatus("Initializing local storage", 6)) - .then((): any => { - const wrapper: any = this.app.platformWrapper; + .then(() => this.setStatus("Creating platform wrapper", 3)) + .then(() => this.sendBeacon()) + .then(() => authorizeViaSSOToken(this.app, this.dialogs)) + .then(() => this.app.platformWrapper.initialize()) + .then(() => this.setStatus("Initializing local storage", 6)) + .then(() => { + const wrapper = this.app.platformWrapper; if (wrapper instanceof PlatformWrapperImplBrowser) { try { window.localStorage.setItem("local_storage_test", "1"); window.localStorage.removeItem("local_storage_test"); } - catch (ex: any) { + catch (ex) { logger.error("Failed to read/write local storage:", ex); - return new Promise((): any => { + return new Promise(() => { alert("Your brower does not support thirdparty cookies or you have disabled it in your security settings.\n\n" + "In Chrome this setting is called 'Block third-party cookies and site data'.\n\n" + "Please allow third party cookies and then reload the page."); @@ -104,72 +104,72 @@ export class PreloadState extends GameState { } } }) - .then((): any => this.setStatus("Creating storage", 9)) - .then((): any => { + .then(() => this.setStatus("Creating storage", 9)) + .then(() => { return this.app.storage.initialize(); }) - .then((): any => this.setStatus("Initializing libraries", 12)) - .then((): any => this.app.analytics.initialize()) - .then((): any => this.app.gameAnalytics.initialize()) - .then((): any => this.setStatus("Connecting to api", 15)) - .then((): any => this.fetchDiscounts()) - .then((): any => this.setStatus("Initializing settings", 20)) - .then((): any => { + .then(() => this.setStatus("Initializing libraries", 12)) + .then(() => this.app.analytics.initialize()) + .then(() => this.app.gameAnalytics.initialize()) + .then(() => this.setStatus("Connecting to api", 15)) + .then(() => this.fetchDiscounts()) + .then(() => this.setStatus("Initializing settings", 20)) + .then(() => { return this.app.settings.initialize(); }) - .then((): any => { + .then(() => { // Initialize fullscreen if (this.app.platformWrapper.getSupportsFullscreen()) { this.app.platformWrapper.setFullscreen(this.app.settings.getIsFullScreen()); } }) - .then((): any => this.setStatus("Initializing language", 25)) - .then((): any => { + .then(() => this.setStatus("Initializing language", 25)) + .then(() => { if (this.app.settings.getLanguage() === "auto-detect") { - const language: any = autoDetectLanguageId(); + const language = autoDetectLanguageId(); logger.log("Setting language to", language); return this.app.settings.updateLanguage(language); } }) - .then((): any => { + .then(() => { document.documentElement.setAttribute("lang", this.app.settings.getLanguage()); }) - .then((): any => { - const language: any = this.app.settings.getLanguage(); + .then(() => { + const language = this.app.settings.getLanguage(); updateApplicationLanguage(language); }) - .then((): any => this.setStatus("Initializing sounds", 30)) - .then((): any => { + .then(() => this.setStatus("Initializing sounds", 30)) + .then(() => { return this.app.sound.initialize(); }) - .then((): any => this.setStatus("Initializing restrictions", 34)) - .then((): any => { + .then(() => this.setStatus("Initializing restrictions", 34)) + .then(() => { return this.app.restrictionMgr.initialize(); }) - .then((): any => this.setStatus("Initializing savegames", 38)) - .then((): any => { - return this.app.savegameMgr.initialize().catch((err: any): any => { + .then(() => this.setStatus("Initializing savegames", 38)) + .then(() => { + return this.app.savegameMgr.initialize().catch(err => { logger.error("Failed to initialize savegames:", err); alert("Your savegames failed to load, it seems your data files got corrupted. I'm so sorry!\n\n(This can happen if your pc crashed while a game was saved).\n\nYou can try re-importing your savegames."); return this.app.savegameMgr.writeAsync(); }); }) - .then((): any => this.setStatus("Downloading resources", 40)) - .then((): any => { - this.app.backgroundResourceLoader.resourceStateChangedSignal.add(({ progress }: any): any => { + .then(() => this.setStatus("Downloading resources", 40)) + .then(() => { + this.app.backgroundResourceLoader.resourceStateChangedSignal.add(({ progress }) => { this.setStatus("Downloading resources (" + (progress * 100.0).toFixed(1) + " %)", 40 + progress * 50); }); - return this.app.backgroundResourceLoader.getMainMenuPromise().catch((err: any): any => { + return this.app.backgroundResourceLoader.getMainMenuPromise().catch(err => { logger.error("Failed to load resources:", err); this.app.backgroundResourceLoader.showLoaderError(this.dialogs, err); - return new Promise((): any => null); + return new Promise(() => null); }); }) - .then((): any => { + .then(() => { this.app.backgroundResourceLoader.resourceStateChangedSignal.removeAll(); }) - .then((): any => this.setStatus("Checking changelog", 95)) - .then((): any => { + .then(() => this.setStatus("Checking changelog", 95)) + .then(() => { if (G_IS_DEV && globalConfig.debug.disableUpgradeNotification) { return; } @@ -178,19 +178,19 @@ export class PreloadState extends GameState { } return this.app.storage .readFileAsync("lastversion.bin") - .catch((err: any): any => { + .catch(err => { logger.warn("Failed to read lastversion:", err); return G_BUILD_VERSION; }) - .then((version: any): any => { + .then(version => { logger.log("Last version:", version, "App version:", G_BUILD_VERSION); this.app.storage.writeFileAsync("lastversion.bin", G_BUILD_VERSION); return version; }) - .then((version: any): any => { - let changelogEntries: any = []; + .then(version => { + let changelogEntries = []; logger.log("Last seen version:", version); - for (let i: any = 0; i < CHANGELOG.length; ++i) { + for (let i = 0; i < CHANGELOG.length; ++i) { if (CHANGELOG[i].version === version) { break; } @@ -199,36 +199,36 @@ export class PreloadState extends GameState { if (changelogEntries.length === 0) { return; } - let dialogHtml: any = T.dialogs.updateSummary.desc; - for (let i: any = 0; i < changelogEntries.length; ++i) { - const entry: any = changelogEntries[i]; + let dialogHtml = T.dialogs.updateSummary.desc; + for (let i = 0; i < changelogEntries.length; ++i) { + const entry = changelogEntries[i]; dialogHtml += `
${entry.version} ${entry.date}
    - ${entry.entries.map((text: any): any => `
  • ${text}
  • `).join("")} + ${entry.entries.map(text => `
  • ${text}
  • `).join("")}
`; } - return new Promise((resolve: any): any => { + return new Promise(resolve => { this.dialogs.showInfo(T.dialogs.updateSummary.title, dialogHtml).ok.add(resolve); }); }); }) - .then((): any => this.setStatus("Launching", 99)) - .then((): any => { + .then(() => this.setStatus("Launching", 99)) + .then(() => { this.moveToState("MainMenuState"); - }, (err: any): any => { + }, err => { this.showFailMessage(err); }); } - update(): any { - const now: any = performance.now(); + update() { + const now = performance.now(); if (now - this.lastHintShown > this.nextHintDuration) { this.lastHintShown = now; - const hintText: any = getRandomHint(); + const hintText = getRandomHint(); this.hintsText.innerHTML = hintText; /** * Compute how long the user will need to read the hint. @@ -238,23 +238,23 @@ export class PreloadState extends GameState { this.nextHintDuration = Math.max(2500, (hintText.length / 650) * 60 * 1000); } } - onRender(): any { + onRender() { this.update(); } - onBackgroundTick(): any { + onBackgroundTick() { this.update(); } - setStatus(text: string, progress: any): any { + setStatus(text: string, progress) { logger.log("✅ " + text); this.currentStatus = text; this.statusText.innerText = text; this.progressElement.style.width = 80 + (progress / 100) * 20 + "%"; return Promise.resolve(); } - showFailMessage(text: any): any { + showFailMessage(text) { logger.error("App init failed:", text); - const email: any = "bugs@shapez.io"; - const subElement: any = document.createElement("div"); + const email = "bugs@shapez.io"; + const subElement = document.createElement("div"); subElement.classList.add("failureBox"); subElement.innerHTML = `