### Prevent BeforeInstallPrompt Event using JavaScript Source: https://github.com/pagefaultgames/pokerogue/blob/beta/index.html Listens for the 'beforeinstallprompt' event and prevents the default behavior, which is the invasive browser installation prompt. This allows developers to control when and how the user is prompted to install the application. ```javascript window.addEventListener('beforeinstallprompt', e => { // Prevent invasive install prompt (users are still able to install as an app) e.preventDefault(); }); ``` -------------------------------- ### Initialize Phaser Game Instance Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Starts the Phaser game instance with specific configurations for PokéRogue, including rendering type, scaling, plugins, input settings, and scene management. It also loads custom fonts and game manifest data before initialization. ```typescript import Phaser from "phaser"; import { LoadingScene } from "./loading-scene"; import { BattleScene } from "./battle-scene"; import { InvertPostFX } from "./pipelines/invert"; async function startGame(gameManifest?: Record): Promise { const game = new Phaser.Game({ type: Phaser.WEBGL, parent: "app", scale: { width: 1920, height: 1080, mode: Phaser.Scale.FIT, }, plugins: { global: [ { key: "rexInputTextPlugin", plugin: InputTextPlugin, start: true, }, { key: "rexBBCodeTextPlugin", plugin: BBCodeTextPlugin, start: true, }, ], scene: [ { key: "rexUI", plugin: UIPlugin, mapping: "rexUI", }, ], }, input: { mouse: { target: "app" }, touch: { target: "app" }, gamepad: true, }, dom: { createContainer: true, }, antialias: false, pipeline: [InvertPostFX] as unknown as Phaser.Types.Core.PipelineConfig, scene: [LoadingScene, BattleScene], version: "1.11.6", }); game.sound.pauseOnBlur = false; game.manifest = gameManifest; } // Load fonts and manifest, then start const loadFonts = Promise.all([ document.fonts.load("16px emerald"), document.fonts.load("10px pkmnems") ]); const [jsonResponse] = await Promise.all([ fetch("/manifest.json").then(r => r.json()), loadFonts ]); await startGame(jsonResponse.manifest); ``` -------------------------------- ### TypeScript Game Configuration and Overrides Source: https://context7.com/pagefaultgames/pokerogue/llms.txt This snippet demonstrates how to import and utilize core game constants such as party size, encounter weights, and friendship caps. It also showcases how to apply development-specific overrides for various game parameters like starting waves, biomes, species, levels, and battle conditions. These overrides are intended for development builds to facilitate testing and customization. ```typescript import { PLAYER_PARTY_MAX_SIZE, CLASSIC_MODE_MYSTERY_ENCOUNTER_WAVES, BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT, MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT, RARE_CANDY_FRIENDSHIP_CAP, defaultStarterSpecies } from "./constants"; import Overrides from "./overrides"; // Core constants console.log(`Max party size: ${PLAYER_PARTY_MAX_SIZE}`); // 6 console.log(`Mystery encounter waves: ${CLASSIC_MODE_MYSTERY_ENCOUNTER_WAVES}`); // [10, 180] console.log(`Base ME spawn weight: ${BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT}`); // 3 console.log(`Max ME spawn weight: ${MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT}`); // 256 console.log(`Rare candy friendship cap: ${RARE_CANDY_FRIENDSHIP_CAP}`); // 200 // Default starters available to all players defaultStarterSpecies.forEach(speciesId => { const species = getPokemonSpecies(speciesId); console.log(`Starter: ${species.name}`); }); // Development overrides (only work in dev builds) // Override starting wave Overrides.STARTING_WAVE_OVERRIDE = 50; // Override starting biome Overrides.STARTING_BIOME_OVERRIDE = BiomeId.FOREST; // Override starter species Overrides.STARTER_SPECIES_OVERRIDE = SpeciesId.PIKACHU; // Override enemy species Overrides.OPP_SPECIES_OVERRIDE = SpeciesId.MEWTWO; // Override enemy level Overrides.OPP_LEVEL_OVERRIDE = 100; // Override shiny chance (0-100) Overrides.SHINY_RATE_OVERRIDE = 100; // All Pokémon shiny // Override to always get critical hits Overrides.ALWAYS_CRIT_OVERRIDE = true; // Override move accuracy to always hit Overrides.MOVE_ACCURACY_OVERRIDE = true; // Force double battles Overrides.DOUBLE_BATTLE_OVERRIDE = true; // Override battle type Overrides.BATTLE_TYPE_OVERRIDE = BattleType.TRAINER; // Override EXP multiplier Overrides.XP_MULTIPLIER_OVERRIDE = 10; // Disable level cap Overrides.DISABLE_LEVEL_CAP = true; // Override starting money Overrides.STARTING_MONEY_OVERRIDE = 999999; // Override weather Overrides.WEATHER_OVERRIDE = WeatherType.SUNNY; console.log("Development overrides configured"); ``` -------------------------------- ### Translation JSON Structure (English Example) Source: https://github.com/pagefaultgames/pokerogue/blob/beta/docs/localization.md An example of a JSON file structure used for storing translations. This specific example is for the English language and defines a key with interpolation placeholders. ```jsonc // from "en/file-name.json"... { "keyName": "{{arg1}}! This is {{arg2}} of translated text!" } ``` -------------------------------- ### TSDoc Example: AddSubstituteAttr Class Documentation (TypeScript) Source: https://github.com/pagefaultgames/pokerogue/blob/beta/docs/comments.md This snippet demonstrates TSDoc comments for a TypeScript class `AddSubstituteAttr`. It showcases the use of {@link https://bulbaparden.net/wiki/Substitute_(doll)_|Substitute Doll} and {@linkcode MoveId.SUBSTITUTE} tags for linking to external resources and code elements, respectively. It also includes descriptions for properties and methods, adhering to TSDoc specifications. ```typescript /** * Attribute to put in a {@link https://bulbaparden.net/wiki/Substitute_(doll)_|Substitute Doll} for the user. * * Used for {@linkcode MoveId.SUBSTITUTE} and {@linkcode MoveId.SHED_TAIL}. */ export class AddSubstituteAttr extends MoveEffectAttr { /** The percentage of the user's maximum HP that is required to apply this effect. */ private readonly hpCost: number; /** Whether the damage taken should be rounded up (Shed Tail rounds up). */ private readonly roundUp: boolean; constructor(hpCost: number, roundUp: boolean) { // code removed } /** * Helper function to compute the amount of HP required to create a substitute. * @param user - The {@linkcode Pokemon} using the move * @returns The amount of HP that required to create a substitute. */ private getHpCost(user: Pokemon): number { // code removed } /** * Remove a fraction of the user's maximum HP to create a 25% HP substitute doll. * @param user - The {@linkcode Pokemon} using the move * @param target - n/a * @param move - The {@linkcode Move} being used * @param args - n/a * @returns Whether the attribute successfully applied. */ public override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { // code removed } public override getUserBenefitScore(user: Pokemon, _target: Pokemon, _move: Move): number { // code removed } getCondition(): MoveConditionFunc { // code removed } public override getFailedText(user: Pokemon): string | undefined { // code removed } } ``` -------------------------------- ### PokéRogue API: Account Management and User Info (TypeScript) Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Handles user authentication, session updates, and retrieving account details using the pokerogueApi. Includes examples for updating user info, getting general account data, registering new accounts, and logging in existing users. It relies on the '#api/pokerogue-api' module and local account state. ```typescript import { pokerogueApi } from "#api/pokerogue-api"; import { updateUserInfo, loggedInUser, clientSessionId } from "./account"; // Update user information (login/session check) try { const [success, status] = await updateUserInfo(); if (success && loggedInUser) { console.log(`Logged in as: ${loggedInUser.username}`); console.log(`Last session slot: ${loggedInUser.lastSessionSlot}`); console.log(`Has admin role: ${loggedInUser.hasAdminRole}`); console.log(`Session ID: ${clientSessionId}`); } else { console.error(`Login failed with status: ${status}`); } } catch (error) { console.error("Failed to update user info:", error); } // Get account information try { const [accountInfo, status] = await pokerogueApi.account.getInfo(); if (accountInfo) { console.log(`Username: ${accountInfo.username}`); console.log(`Discord linked: ${!!accountInfo.discordId}`); console.log(`Google linked: ${!!accountInfo.googleId}`); } } catch (error) { console.error("Failed to get account info:", error); } // Register new account try { const success = await pokerogueApi.account.register( "myusername", "mypassword123" ); if (success) { console.log("Account registered successfully"); } } catch (error) { console.error("Registration failed:", error); } // Login try { const success = await pokerogueApi.account.login( "myusername", "mypassword123" ); if (success) { console.log("Login successful"); } } catch (error) { console.error("Login failed:", error); } ``` -------------------------------- ### Biome CLI Flags for Writing and Filtering Checks Source: https://github.com/pagefaultgames/pokerogue/blob/beta/docs/linting.md This example illustrates common Biome command-line flags used for controlling its behavior. The `--write` flag applies safe fixes, while `--changed` and `--staged` limit checks to modified or staged files, respectively. `diagnostic-level` filters output by severity. ```shell # Apply safe fixes and formatting pnpm exec biome check --write # Check only changed files pnpm exec biome check --changed # Check only staged files pnpm exec biome check --staged # Show only errors and warnings pnpm exec biome check --diagnostic-level=warn ``` -------------------------------- ### TSDoc Guidelines: Default Values in Comments (TypeScript) Source: https://github.com/pagefaultgames/pokerogue/blob/beta/docs/comments.md This example demonstrates how to document default values for properties and parameters in TSDoc comments. It shows the use of the `@defaultValue` tag for class properties and inline default value information for function parameters to inform users about available defaults. ```typescript class BattleScene { /** * Tracker for whether the last run attempt failed. * @defaultValue `false` */ public failedRunAway = false; } /** * Turn all frogs in the global frog registry gay using science mumbo-jumbo. * @param maxFrogs - The maximum number of animals to convert * @param includeToads - (Default `false`) Whether to also convert toads as well * @param turnExplosive - (Default `true`) Whether to make converted frogs explode */ function turnFrogsGay(maxFrogs: number, includeToads = false, turnExplosive = true): void {}; /** * Print a copiously long, procedurally generated lorem ipsum-like placeholder string. * @param charCount - (Default `1000`) The number of characters to create */ function printLorem(charCount = 1000): string {}; ``` -------------------------------- ### PokéRogue API: Save Data Sync and Daily Seed (TypeScript) Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Provides examples for synchronizing game save data to the server and retrieving the daily game seed. It requires game-specific data such as trainerId, secretId, and dexData for synchronization. Errors during these operations are caught and logged. ```typescript // Sync save data to server try { const success = await pokerogueApi.savedata.system.update({ slot: 0, trainerId: gameData.trainerId, secretId: gameData.secretId, dexData: gameData.dexData, starterData: gameData.starterData, // ... other system data }); if (success) { console.log("Save data synced to server"); } } catch (error) { console.error("Failed to sync save data:", error); } // Get daily seed try { const dailySeed = await pokerogueApi.daily.getSeed(); if (dailySeed) { console.log(`Today's daily seed: ${dailySeed.seed}`); } } catch (error) { console.error("Failed to get daily seed:", error); } ``` -------------------------------- ### Execute Biome CLI for Custom Linting and Formatting Source: https://github.com/pagefaultgames/pokerogue/blob/beta/docs/linting.md This shows how to run the Biome executable directly from the command line using `pnpm exec`. This method allows for greater customization of Biome's behavior through various command-line flags, such as specifying diagnostic levels or targeting specific files. ```shell pnpm exec biome check --[flags] ``` -------------------------------- ### Manage Game Phases with PhaseManager Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Demonstrates how to use the PhaseManager to create and manage a phase-based game loop, including queuing messages and custom phase implementation. Dependencies include PhaseManager, BattleScene, and Phase classes. ```typescript import { PhaseManager } from "./phase-manager"; import { BattleScene } from "./battle-scene"; // The phase manager is used internally by BattleScene // Phases are queued and executed sequentially // Example: Starting a new battle encounter scene.phaseManager.newPhase("InitEncounterPhase"); // Queue a message to the player scene.phaseManager.queueMessage( "A wild Pokémon appeared!", 1000, // callback delay true, // show prompt 500 // prompt delay ); // Example phase flow in a turn: // 1. TurnInitPhase - Initialize turn, check speed // 2. CommandPhase - Player selects action // 3. EnemyCommandPhase - AI selects action // 4. TurnStartPhase - Execute commands based on priority // 5. MovePhase - Execute move // - MoveHeaderPhase - Show move name // - MoveAnimPhase - Play move animation // - MoveEffectPhase - Apply move effects // - MoveEndPhase - Clean up // 6. TurnEndPhase - End of turn effects // 7. CheckInterludePhase - Check for phase transitions // Custom phase implementation example import { Phase } from "./phase"; import { globalScene } from "./global-scene"; export class CustomPhase extends Phase { public readonly phaseName = "CustomPhase"; start() { super.start(); // Custom phase logic console.log("Executing custom phase"); // End this phase and move to next this.end(); } } // Queue custom phase scene.phaseManager.newPhase("CustomPhase"); ``` -------------------------------- ### Run Biome Linting and Formatting via npm/pnpm Scripts Source: https://github.com/pagefaultgames/pokerogue/blob/beta/docs/linting.md This snippet demonstrates how to execute Biome for linting and formatting tasks using the project's package manager scripts defined in `package.json`. These scripts provide convenient aliases for common Biome operations. ```shell pnpm biome pnpm biome:all ``` -------------------------------- ### Manage UI Modes and Handlers in TypeScript Source: https://context7.com/pagefaultgames/pokerogue/llms.txt This TypeScript snippet illustrates how to control the UI system, including setting different UI modes and using their respective handlers. It covers displaying messages, switching between command, fight, party, summary, and selection screens, as well as clearing the UI and playing sound effects. ```typescript import { UI } from "#ui/ui"; import { UiMode } from "#enums/ui-mode"; // Access UI system from scene const ui = scene.ui; // Set UI mode ui.setMode(UiMode.MESSAGE).then(() => { console.log("Switched to message mode"); }); // Show message ui.showText( "A wild Pikachu appeared!", null, // speed () => { // Callback after message shown console.log("Message displayed"); }, 1000, // delay true // prompt (wait for input) ); // Switch to command mode (Fight/Pokémon/Bag/Run) ui.setMode(UiMode.COMMAND).then(() => { console.log("Player can select command"); }); // Switch to fight mode (move selection) ui.setMode(UiMode.FIGHT, playerPokemon).then(() => { console.log("Player selecting move"); }); // Switch to party screen ui.setMode(UiMode.PARTY).then(() => { console.log("Party screen opened"); }); // Open Pokémon summary ui.setMode(UiMode.SUMMARY, playerPokemon).then(() => { console.log("Viewing Pokémon summary"); }); // Modifier selection (items after battle) ui.setMode(UiMode.MODIFIER_SELECT).then(() => { console.log("Selecting reward item"); }); // Starter selection at game start ui.setMode(UiMode.STARTER_SELECT, (starters: PlayerPokemon[]) => { console.log("Selected starters:", starters); }).then(() => { console.log("Starter selection screen"); }); // Open Pokédex ui.setMode(UiMode.POKEDEX).then(() => { console.log("Pokédex opened"); }); // Open achievements ui.setMode(UiMode.ACHIEVEMENTS).then(() => { console.log("Achievements opened"); }); // Mystery encounter UI ui.setMode(UiMode.MYSTERY_ENCOUNTER).then(() => { console.log("Mystery encounter screen"); }); // Clear UI ui.clearText(); // Get current mode const currentMode = ui.getMode(); console.log(`Current UI mode: ${UiMode[currentMode]}`); // Play select sound ui.playSelect(); // Play error sound ui.playError(); ``` -------------------------------- ### Manage Pokémon Instances with TypeScript Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Demonstrates creating player and enemy Pokémon, generating wild encounters, evolving Pokémon, applying and removing status tags, checking stats, accessing movesets, and performing fusion. Requires imports from '#field/pokemon', '#utils/pokemon-utils', '#enums/species-id', and '#enums/nature'. ```typescript import { PlayerPokemon, EnemyPokemon } from "#field/pokemon"; import { getPokemonSpecies } from "#utils/pokemon-utils"; import { SpeciesId } from "#enums/species-id"; import { Nature } from "#enums/nature"; // Create a player's Pokémon const species = getPokemonSpecies(SpeciesId.CHARIZARD); const playerPokemon = new PlayerPokemon( scene, species, 50, // level undefined, // abilityIndex undefined, // formIndex undefined, // gender undefined, // shiny undefined, // variant undefined, // ivs Nature.ADAMANT, // nature undefined // dataSource ); // Generate a random wild Pokémon const wildSpecies = scene.arena.randomSpecies( scene.currentBattle.waveIndex, 50, // level 0, // attempt 2, // luck value false // is boss ); // Evolve a Pokémon const evolution = playerPokemon.species.evolutions[0]; const evoSpecies = getPokemonSpecies(evolution.speciesId); await playerPokemon.evolve(evolution, evoSpecies); // Add a status tag (Burned, Paralyzed, etc.) playerPokemon.addTag( BattlerTagType.BURNED, 0, // turn count (0 = permanent) MoveId.FLAMETHROWER, // source move enemyPokemon.id // source ID ); // Remove a tag playerPokemon.removeTag(BattlerTagType.BURNED); // Check Pokémon stats console.log(`HP: ${playerPokemon.hp}/${playerPokemon.getMaxHp()}`); console.log(`Attack: ${playerPokemon.stats[Stat.ATK]}`); console.log(`Speed: ${playerPokemon.stats[Stat.SPD]}`); // Access moveset playerPokemon.moveset.forEach(pokemonMove => { if (pokemonMove) { const move = pokemonMove.getMove(); console.log(`${move.name}: ${pokemonMove.ppUsed}/${move.pp} PP`); } }); // Use PP for a move const move = playerPokemon.moveset[0]; if (move) { move.usePP(1); // Use 1 PP } // Check if Pokémon can battle if (!playerPokemon.isFainted()) { console.log("Pokémon is ready to battle!"); } // Fusion example playerPokemon.generateFusionSpecies(false); if (playerPokemon.fusionSpecies) { console.log(`Fused with: ${playerPokemon.fusionSpecies.name}`); } ``` -------------------------------- ### Manage Arena and Field Effects (TypeScript) Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Illustrates how to manage the game's arena and field, including setting biomes, weather, and terrain. It also shows how to add arena tags like Stealth Rock and access player status. ```typescript import { Arena } from "#field/arena"; import { BiomeId } from "#enums/biome-id"; import { WeatherType } from "#enums/weather-type"; import { TerrainType } from "#data/terrain"; // Arena is created by BattleScene const arena = scene.arena; // Access current biome console.log(`Current biome: ${arena.biomeType}`); // Set biome arena.biomeType = BiomeId.FOREST; // Get random species for current wave const randomSpecies = arena.randomSpecies( scene.currentBattle.waveIndex, 50, // level 0, // attempt 2, // luck value false // is boss ); console.log(`Random encounter: ${randomSpecies.name}`); // Weather management if (arena.weather) { console.log(`Current weather: ${arena.weather.weatherType}`); // Check if weather is damaging if (arena.weather.isDamaging()) { console.log("This weather damages Pokémon each turn"); } } // Set weather arena.trySetWeather(WeatherType.RAIN, true); // Terrain management if (arena.terrain) { console.log(`Current terrain: ${arena.terrain.terrainType}`); } // Arena tags (entry hazards, screens, etc.) arena.tags.forEach(tag => { console.log(`Field effect: ${tag.tagType}`); }); // Add arena tag (e.g., Stealth Rock) arena.addTag( ArenaTagType.STEALTH_ROCK, 0, // turn count MoveId.STEALTH_ROCK, trainerId, ArenaTagSide.PLAYER ); // Count player faints (for wild Pokémon flee rate) console.log(`Player faints: ${arena.playerFaints}`); ``` -------------------------------- ### Save and Load Game Data - TypeScript Source: https://context7.com/pagefaultgames/pokerogue/llms.txt This TypeScript code demonstrates how to save and load system data (like Pokédex entries and achievements) and session data (the current game run) using the GameData class. It includes error handling for save/load operations and provides examples of accessing loaded data such as trainer ID, gender, Pokédex status, game statistics, unlocks, and starter Pokémon details. ```typescript import { GameData } from "#system/game-data"; import { GameDataType } from "#enums/game-data-type"; // GameData is part of BattleScene const gameData = scene.gameData; // Save system data (Pokédex, starters, achievements) try { const success = await gameData.saveSystem(); if (success) { console.log("System data saved successfully"); } } catch (error) { console.error("Failed to save system data:", error); } // Save session data (current run) try { const success = await gameData.saveSession(); if (success) { console.log("Session saved successfully"); } } catch (error) { console.error("Failed to save session:", error); } // Load system data try { const success = await gameData.loadSystem(); if (success) { console.log("System data loaded"); // Access loaded data console.log(`Trainer ID: ${gameData.trainerId}`); console.log(`Gender: ${gameData.gender}`); // Check Pokédex data const speciesData = gameData.dexData[SpeciesId.PIKACHU]; console.log(`Pikachu caught: ${speciesData.caughtAttr > 0}`); console.log(`Pikachu seen count: ${speciesData.seenCount}`); } } catch (error) { console.error("Failed to load system data:", error); } // Load a specific session slot try { const slotId = 0; // Slots 0-4 const success = await gameData.loadSession(slotId); if (success) { console.log(`Session ${slotId} loaded`); } } catch (error) { console.error("Failed to load session:", error); } // Check if session exists const hasSession = gameData.hasSession(0); if (hasSession) { console.log("Save slot 0 has data"); } // Delete a session gameData.deleteSession(0).then(success => { if (success) { console.log("Session deleted"); } }); // Access game stats console.log(`Battles won: ${gameData.gameStats.battles}`); console.log(`Pokémon caught: ${gameData.gameStats.pokemonCaught}`); console.log(`Eggs hatched: ${gameData.gameStats.eggsHatched}`); // Check unlocks if (gameData.unlocks[Unlockables.ENDLESS_MODE]) { console.log("Endless mode unlocked"); } // Starter data access const starterData = gameData.starterData[SpeciesId.CHARMANDER]; console.log(`Charmander candy count: ${starterData.candyCount}`); console.log(`Friendship: ${starterData.friendship}`); ``` -------------------------------- ### Manage Battle State and Combat with Battle Class Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Shows how to instantiate and manage battles, including wild and trainer encounters, and handle turn-based combat mechanics. It utilizes the Battle class and various enums for battle types and specifications. Inputs include battle mode, wave index, and battle type; outputs include battle state information and participant management. ```typescript import { Battle } from "./battle"; import { BattleType } from "#enums/battle-type"; import { BattleSpec } from "#enums/battle-spec"; // Create a wild Pokémon battle const wildBattle = new Battle( GameModes.CLASSIC, 1, // wave index BattleType.WILD, undefined, // trainer config false // double battle ); // Calculate level for current wave const enemyLevel = wildBattle.getLevelForWave(); console.log(`Enemy level: ${enemyLevel}`); // Formula: 1 + waveIndex/2 + (waveIndex/25)^2 // Boss battles multiply by 1.2 // Trainer battle example const trainerBattle = new Battle( GameModes.CLASSIC, 10, BattleType.TRAINER, trainerConfig, false ); // Access battle state console.log(`Current wave: ${trainerBattle.waveIndex}`); console.log(`Turn number: ${trainerBattle.turn}`); console.log(`Battle type: ${trainerBattle.battleType}`); // Increment turn counter trainerBattle.incrementTurn(); // Add participant for EXP distribution trainerBattle.addParticipant(playerPokemon); // Remove participant trainerBattle.removeParticipant(playerPokemon); // Collect money after battle trainerBattle.pickUpScatteredMoney(); // Check if double battle if (trainerBattle.double) { console.log("This is a double battle"); } // Access enemy party trainerBattle.enemyParty.forEach(pokemon => { console.log(`Enemy: ${pokemon.name} Lv.${pokemon.level}`); }); ``` -------------------------------- ### Define and Manage Mystery Encounters in TypeScript Source: https://context7.com/pagefaultgames/pokerogue/llms.txt This snippet demonstrates how to define and manage special random encounters in the game. It covers setting spawn weights, defining encounter options with associated logic, and setting requirements for when an encounter can occur. It also shows how to initialize an encounter and check if it can spawn based on game state. ```typescript import { MysteryEncounter } from "#data/mystery-encounters/mystery-encounter"; import { MysteryEncounterType } from "#enums/mystery-encounter-type"; import { MysteryEncounterTier } from "#enums/mystery-encounter-tier"; import { MysteryEncounterMode } from "#enums/mystery-encounter-mode"; // Mystery encounters spawn based on wave and weight // Base spawn weight: 3 // Max spawn weight: 256 // Weight increases by 3 each wave without an encounter // Target: ~12 encounters per run // Define a mystery encounter const mysteryEncounter = new MysteryEncounter( MysteryEncounterType.MYSTERIOUS_CHEST, MysteryEncounterTier.COMMON, MysteryEncounterMode.NO_BATTLE ); // Add encounter options mysteryEncounter.options = [ { buttonLabel: "Open the chest", buttonTooltip: "Who knows what's inside?", async onOptionPhaseEnd(scene: BattleScene) { // Reward logic const modifier = generateModifierType(scene, ModifierTier.GREAT); await scene.addModifier(modifier); }, }, { buttonLabel: "Leave it alone", buttonTooltip: "Better safe than sorry", async onOptionPhaseEnd(scene: BattleScene) { // No reward, continue }, }, ]; // Set encounter requirements mysteryEncounter.requirements = [ { requiredWave: 10, // Minimum wave maxWave: 180, // Maximum wave }, ]; // Initialize encounter mysteryEncounter.onInit = function() { // Setup encounter state console.log("Mystery encounter initialized"); }; // Check if encounter can spawn const canSpawn = scene.currentBattle.waveIndex >= 10 && scene.currentBattle.waveIndex <= 180; if (canSpawn && Math.random() * 256 < currentSpawnWeight) { // Trigger mystery encounter phase scene.phaseManager.newPhase("MysteryEncounterPhase"); } // Access current mystery encounter in battle if (scene.currentBattle.mysteryEncounter) { const encounter = scene.currentBattle.mysteryEncounter; console.log(`Encounter type: ${encounter.encounterType}`); console.log(`Number of options: ${encounter.options.length}`); } // Handle option selection scene.phaseManager.newPhase( "MysteryEncounterOptionSelectedPhase", optionIndex ); // Rewards phase after encounter scene.phaseManager.newPhase("MysteryEncounterRewardsPhase"); ``` -------------------------------- ### Define and Execute Moves with TypeScript Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Explains how to retrieve move data, access its properties like name, type, category, power, accuracy, and PP. It also demonstrates checking move categories and executing moves, including status moves and area-of-effect moves. Requires imports from '#data/data-lists', '#enums/move-id', and '#enums/move-category'. ```typescript import { allMoves } from "#data/data-lists"; import { MoveId } from "#enums/move-id"; import { MoveCategory } from "#enums/move-category"; // Get a specific move const flamethrower = allMoves[MoveId.FLAMETHROWER]; // Access move properties console.log(`Name: ${flamethrower.name}`); console.log(`Type: ${flamethrower.type}`); console.log(`Category: ${flamethrower.category}`); // PHYSICAL, SPECIAL, or STATUS console.log(`Power: ${flamethrower.power}`); console.log(`Accuracy: ${flamethrower.accuracy}`); console.log(`PP: ${flamethrower.pp}`); console.log(`Priority: ${flamethrower.priority}`); console.log(`Chance: ${flamethrower.chance}%`); // Secondary effect chance // Check move category if (flamethrower.category === MoveCategory.SPECIAL) { console.log("This is a special attack"); } // Execute a move (typically done through MovePhase) const success = flamethrower.apply( userPokemon, targetPokemon, flamethrower ); if (success) { console.log("Move hit successfully!"); } // Check if move can target multiple Pokémon const earthquake = allMoves[MoveId.EARTHQUAKE]; console.log(`Target: ${earthquake.moveTarget}`); // Status moves const thunderWave = allMoves[MoveId.THUNDER_WAVE]; if (thunderWave.category === MoveCategory.STATUS) { console.log("This move doesn't deal direct damage"); } ``` -------------------------------- ### Account Management API Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Endpoints for user account registration, login, and retrieving account information. ```APIDOC ## Account Registration ### Description Registers a new user account with the provided username and password. ### Method POST ### Endpoint `/api/account/register` ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new account. - **password** (string) - Required - The password for the new account. ### Request Example ```json { "username": "myusername", "password": "mypassword123" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the registration was successful. #### Response Example ```json { "success": true } ``` ## User Login ### Description Logs in an existing user with their username and password. ### Method POST ### Endpoint `/api/account/login` ### Parameters #### Request Body - **username** (string) - Required - The username of the user. - **password** (string) - Required - The password of the user. ### Request Example ```json { "username": "myusername", "password": "mypassword123" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the login was successful. #### Response Example ```json { "success": true } ``` ## Get Account Information ### Description Retrieves the current logged-in user's account details. ### Method GET ### Endpoint `/api/account/info` ### Response #### Success Response (200) - **username** (string) - The username of the account. - **discordId** (string) - The user's Discord ID, if linked (nullable). - **googleId** (string) - The user's Google ID, if linked (nullable). #### Response Example ```json { "username": "myusername", "discordId": "1234567890", "googleId": null } ``` ## Unlink Discord Account ### Description Unlinks the user's Discord account from their PokéRogue account. ### Method POST ### Endpoint `/api/account/unlink/discord` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the unlinking was successful. #### Response Example ```json { "success": true } ``` ## Unlink Google Account ### Description Unlinks the user's Google account from their PokéRogue account. ### Method POST ### Endpoint `/api/account/unlink/google` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the unlinking was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Configure and Manage Game Modes Source: https://context7.com/pagefaultgames/pokerogue/llms.txt Defines and configures different game modes (Classic, Endless, Daily) with specific rules, challenges, and encounter settings. It allows for setting and checking challenges within a game mode and retrieving mode-specific data like wave adjustments. ```typescript import { GameMode } from "./game-mode"; import { GameModes } from "#enums/game-modes"; // Classic mode - standard roguelite progression const classicMode = new GameMode( GameModes.CLASSIC, { isClassic: true, hasTrainers: true, hasMysteryEncounters: true, }, classicFixedBattles // Predefined trainer battles ); // Enable a challenge in the game mode classicMode.setChallengeValue(Challenges.SINGLE_TYPE, 0); // Mono-type challenge // Check if mode has specific challenge if (classicMode.hasChallenge(ChallengeType.SINGLE_TYPE)) { console.log("Single type challenge is active"); } // Endless mode - no end condition const endlessMode = new GameMode( GameModes.ENDLESS, { isEndless: true, hasTrainers: true, hasShortBiomes: true, hasRandomBosses: true, } ); // Daily mode - fixed seed for all players const dailyMode = new GameMode( GameModes.DAILY, { isDaily: true, hasTrainers: true, } ); // Get the current game mode const currentMode = getGameMode(GameModes.CLASSIC); const waveForDifficulty = currentMode.getWaveForDifficulty(50); console.log(`Adjusted wave index: ${waveForDifficulty}`); ``` -------------------------------- ### Fetch Translated Text using i18next (TypeScript) Source: https://github.com/pagefaultgames/pokerogue/blob/beta/docs/localization.md Demonstrates how to retrieve translated text within the game's source code using the i18next library. It shows fetching a translation key and passing interpolation arguments. ```typescript globalScene.phaseManager.queueMessage( i18next.t("fileName:keyName", { arg1: "Hello", arg2: "an example", ... }) ); ```