This lesson was updated. Reset to the new version?
This browser isn't keeping your edits, so they're lost when you leave the page.
Pokémon-4 hides wild Pokémon in the tall grass. Stepping into it can start a battle, which fades in, introduces both Pokémon, and offers the battle menu. Only FIGHT works, and the battle ends after one attack that doesn’t hit yet. The NPC’s line in src/config/characters.js now points to the grass on Route 1.
Wild Encounters
walkTo() in src/states/player/PlayerWalkState.js rolls for an encounter once each step finishes, if the player has stepped onto tall grass:
82const { playState } = player.map;83const { encounters = [] } = playState.area;84const isOnGrass = player.map.isGrassTile(target.x, target.y);85
86if (87 isOnGrass &&88 encounters.length > 0 &&89 Math.random() < ENCOUNTER_CHANCE90) {91 player.changeState(PlayerStateName.Idle);92 void playState.startBattle(Opponent.wild(this.game, encounters));93}isGrassTile() asks the Bottom layer whether the tile’s id is GRASS_TILE from src/config/tiles.js. GRASS_TILE is 4039 and counts from 0, like sprites[], so Tiled shows it as 4040, the tall grass. ENCOUNTER_CHANCE in src/config/game.js is 0.3 for now, so battles come quickly while you test. GameMap keeps a reference to its PlayState, which is how the player reaches startBattle().
areas in src/config/areas.js splits each map into parts, and PlayState’s area getter finds the first one whose bounds hold the player’s tile. An area with no bounds covers the rest of the map. Route 1 lists its encounters, the wild Pokémon in its grass, and Pallet Town lists none:
7const ROUTE_1_ENCOUNTERS = [8 { name: "Pidgey", minLevel: 2, maxLevel: 5, weight: 50 },9 { name: "Rattata", minLevel: 2, maxLevel: 4, weight: 50 },10];Opponent.wild() in src/objects/Opponent.js builds the other side with the factory from Pokémon-3. pickEncounter() picks an encounter, where a bigger share of the total weight makes a Pokémon more likely, and the level is anywhere from minLevel to maxLevel:
25static wild(game, encounters) {26 const { name, minLevel, maxLevel } = pickEncounter(encounters);27 const level = getRandomPositiveInteger(minLevel, maxLevel);28
29 return new Opponent([createPokemon(game, name, level)]);30}The starters aren’t in the grass, so Player now picks its starter from starterNames in src/config/pokemon.js. An Opponent has a party, like the player, so a trainer would fit the same shape.
Changing Screens
Pushing BattleState onto the stack keeps the map underneath, unchanged, as it did under the textbox. TransitionState in src/states/TransitionState.js hides the swap. It’s an overlay that tweens a white rectangle’s opacity on its own Timer and closes itself when the tween ends. cover() fades the screen to white, and uncover() fades it back:
98static cover(game, options = {}) {99 return TransitionState.run(game, TransitionType.Cover, options);100}Every change of screen in Pokémon has the same three steps. await the cover, change the stack while the screen is white, then await the uncover. The code after await TransitionState.cover() runs before the next frame is drawn, so no frame ever shows the swap. Step through startBattle() to see the stack and the white at each line:
The Battle
BattleState in src/states/battle/BattleState.js draws the background, both Pokémon, the message panel, and a panel for each Pokémon with its name, level, and health bar. fight() plays the battle out from start to finish:
97async fight() {98 await this.introducePokemon();99 await this.takeTurns();100}introducePokemon() reads in the order things happen on screen. The wild Pokémon slides in and cries (plays its sound), two messages are shown, then the player’s Pokémon slides in and cries:
111await timer.tweenAsync(112 opponentPokemon.position,113 { x: FRONT_LAYOUT.end.x },114 SLIDE_DURATION,115);116
117sounds.play(opponentPokemon.cry);118
119await this.showMessage(`A wild ${opponentPokemon.name} appeared!`);120await this.showMessage(`Go ${playerPokemon.name}!`);121
122await timer.tweenAsync(123 playerPokemon.position,124 { x: BACK_LAYOUT.end.x },125 SLIDE_DURATION,126);127
128sounds.play(playerPokemon.cry);The game loop keeps running through every await, so the slides animate and the messages type out. Step through introducePokemon() to see what each line waits for, or switch code to turns to follow takeTurns():
Menus
showMessage() shows a BattleMessageState, a textbox with the battle border. chooseAction() shows a BattleMenuState, a 2 × 2 GridMenu of FIGHT, BAG, POKéMON, and RUN. When the player picks one, the menu closes with it:
44(action) => this.close(action),show() returns whatever close() was given, so chooseAction() resolves with the action the player chose:
154chooseAction() {155 return this.game.stateStack.show(new BattleMenuState(this.game), {156 pokemon: this.playerPokemon,157 });158}takeTurns() asks until the player picks FIGHT, then shows the first move:
138let action = await this.chooseAction();139
140while (action !== BattleAction.Fight) {141 action = await this.chooseAction();142}143
144const { battleName, moves } = this.playerPokemon;145
146await this.showMessage(`${battleName} used\n${moves[0].name}!`);BAG, POKéMON, and RUN close the menu, and the loop opens it again. Every Pokémon knows one move for now, Tackle, from starterMoves in src/config/pokemon.js.
Battle Sprites
prepareForBattle() in src/objects/Pokemon.js picks each Pokémon’s sprite and starting position from a layout in src/config/pokemon.js. FRONT_LAYOUT is for the opponent, and BACK_LAYOUT for the player:
71export const FRONT_LAYOUT = {72 sprite: 0,73 spriteOffset: { x: 8, y: 8 },74 start: { x: 240, y: 15 },75 end: { x: 140, y: 15 },76};start is off screen, and end is where introducePokemon() slides it to. backSpriteMargin in each entry of pokemonDefinitions is the number of empty rows below the back sprite, which prepareForBattle() adds to its offset. Each Pokémon also has a cry, assets/sounds/pokemon/NAME.wav. Adding a Pokémon now takes its entry, with backSpriteMargin and starterMoves, and its cry.
Start a battle
Walking in the tall grass rolls for wild Pokémon, but no battle ever starts, because startBattle() in src/states/PlayState.js is empty.
Replace the TODO with the way into the battle and back out of it, the way Changing Screens above describes:
- Cover the screen with
TransitionState.cover(). - Push
battleontogame.stateStack, withplayerandopponentfor it to fight with. - Uncover the screen, then run the battle with
battle.fight(). - For the way back, cover the screen again, pop the battle off the stack, and uncover.
Await every cover, uncover and battle.fight(), so each one finishes before the next starts. Then walk in the grass until a battle starts, and pick FIGHT. The Challenge tab gets a ✓ once you’re back on the map after a battle.
startBattle() needs seven lines, one for each thing that happens. Every line except the push and the pop starts with await.
If the battle appears before the screen is covered, the await in front of TransitionState.cover(game) is missing.
Replace the TODO with:
await TransitionState.cover(game);game.stateStack.push(battle, { player, opponent,});await TransitionState.uncover(game);await battle.fight();
await TransitionState.cover(game);game.stateStack.pop();await TransitionState.uncover(game);