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-5 upgrades the battle sequence. FIGHT now plays out a turn, where both Pokémon attack in order of Speed, and the battle goes on until one of them dies faints. Health bars slide down as damage lands.
Battle Turns
takeTurns() in src/states/battle/BattleState.js now loops until the battle is over. Each time the player picks FIGHT, a new BattleTurn plays out one round with the Pokémon’s first move, and BattleTurn.fight() resolves with whether the battle has ended. This is a different fight() from BattleState.fight() in Pokémon-4, which plays the whole battle:
149let isBattleOver = false;150
151while (!isBattleOver) {152 const action = await this.chooseAction();153
154 if (action === BattleAction.Fight) {155 const move = this.playerPokemon.moves[0];156
157 isBattleOver = await new BattleTurn(this.game, this).fight(move);158 }159}BattleTurn in src/objects/BattleTurn.js is a plain class, not a state. It draws nothing and has nothing to update each frame, since BattleState draws the Pokémon and the panels. It only plays out the steps of a turn, in order. BattleTurn.fight() gives each Pokémon its attack, and stops as soon as one of them faints:
33async fight(playerMove) {34 for (const [attacker, defender, move] of this.getAttackOrder(playerMove)) {35 await this.attack(attacker, defender, move);36
37 if (this.playerPokemon.currentHealth <= 0) {38 await this.processDefeat();39
40 return true;41 }42
43 if (this.opponentPokemon.currentHealth <= 0) {44 await this.processVictory();45
46 return true;47 }48 }49
50 return false;51}A Pokémon that faints from the first attack never gets to make the second one. processDefeat() and processVictory() play the faint sound, slide the fainted Pokémon off the bottom of the screen, and show the message.
Who Goes First
getAttackOrder() returns the two attacks, each as an attacker, a defender, and a move. The faster Pokémon goes first, and a tie is a coin flip:
61const isPlayerFirst =62 playerPokemon.speed > opponentPokemon.speed ||63 (playerPokemon.speed === opponentPokemon.speed && Math.random() < 0.5);One Attack
attack() shows what move is being used, then plays the move’s sound while the attacker lunges (tweens) forward and back:
88async attack(attacker, defender, move) {89 await this.battle.showMessage(90 `${attacker.battleName} used\n${move.name}!`,91 ATTACK_MESSAGE_DURATION,92 );93
94 const sound = this.game.sounds.playAsync(move.sound);95
96 await this.lunge(attacker);97 await sound;98 await this.landHit(attacker, defender, move);99}playAsync() starts the sound and returns a promise that resolves when it ends. attack() keeps the promise without awaiting it yet, so the lunge starts straight away. Awaiting the lunge and then the sound waits until both have finished, however long each one takes. Only then does the hit land.
The message passes ATTACK_MESSAGE_DURATION, so it closes by itself shortly after it finishes typing. The player only presses Enter for messages that end something, like “You won!”.
Move in src/objects/Move.js now has a basePower and a sound, from moveDefinitions in src/config/pokemon.js. Tackle has a power of 40.
Landing a Hit
calculateDamage() in src/objects/Pokemon.js works out the damage with the formula from the real games. A higher level, a stronger move, and a higher Attack against the defender’s Defense each do more damage. One hit in 16 is a critical hit, which does half as much again.
calculateDamage() changes nothing. It only returns the damage, so the turn decides when the health actually drops. landHit() plays the hit sound, flashes the defender, and only then takes the health away and slides its bar down:
109async landHit(attacker, defender, move) {110 const { damage, isCritical } = attacker.calculateDamage(defender, move);111
112 this.game.sounds.play(SoundName.HitRegular);113 await this.flash(defender);114
115 defender.takeDamage(damage);116 await this.battle.getPanel(defender).animateHealth();117
118 if (isCritical) {119 await this.battle.showMessage("Critical hit!", MESSAGE_DURATION);120 }121}flash() uses timer.every() to blink the defender and shake it left and right, then timer.delay() to wait before cancelling the blinking. takeDamage() stops health at zero.
Here’s one turn with a timeline along the bottom, one block for each await. The lunge’s block has two rows, because attack() starts the sound, awaits the lunge, and only then awaits the sound. The LCD shows the defender’s currentHealth, which drops at once, and the bar’s value, which slides after it. The demo uses the game’s own levels, a level 1 Charmander against a level 2 Pidgey. Pidgey is faster, so it goes first:
The Health Bar
Each battle panel has a HealthProgressBar, from src/user-interface/battle/HealthProgressBar.js. A ProgressBar draws a bar filled to value out of max, and the health bar picks its colour from how full it is. It’s green above half, yellow at half or below, and red at a quarter or below. renderBar() draws the bar as two fillRect() calls, a thin dark strip along the top and the lighter fill under it, so the bar needs no art.
The bar has its own value, separate from the Pokémon’s currentHealth. takeDamage() lowers the health at once, and the bar slides down to it afterwards. animateHealth() in src/user-interface/battle/BattlePanel.js hands the new health to the bar:
38animateHealth() {39 return this.healthBar.setValue(this.pokemon.currentHealth);40}landHit() awaits it, so the turn only goes on once the bar stops. Nobody else needs to know when health changes. The panel reads the Pokémon directly, and the turn tells it when to slide.
The player’s panel also shows the health as 4/ 12, read from the bar’s value, so the number counts down as the bar slides. PlayerPanel in src/user-interface/battle/PlayerPanel.js sounds the low-health alarm whenever the health is at a quarter or below, and BattleState.exit() stops it when the battle ends.
Healing
A fainted party can’t battle. After the battle has faded back to the map, startBattle() in src/states/PlayState.js checks whether every Pokémon in the party has fainted, and heals them:
105if (player.party.every((pokemon) => pokemon.currentHealth === 0)) {106 await this.healWithMessage(FAINTED_MESSAGE);107}A Pokémon that won keeps its damage into the next battle.
Slide the health bar
When a Pokémon takes a hit, its health bar jumps straight to the new value, because setValue() in src/user-interface/elements/ProgressBar.js sets it at once.
Replace the body of setValue() with a tween from this.game.timer.tweenAsync(). Have it move the bar’s own value to the new value over BAR_DURATION seconds, and return its promise, so landHit() can wait for the bar to stop.
Then battle a wild Pokémon and watch the bars slide. The health number on your panel, such as 4/ 12, counts down with the bar. The Challenge tab gets a ✓ as soon as a health bar finishes sliding.
tweenAsync() takes the object to change, the values to change it to, and how many seconds the change takes. Here the object is the bar itself, this.
Delete this.value = value; and return Promise.resolve();. If this.value = value; stays above the tween, the bar is already at its new value and has nowhere to slide.
The whole body is one line, return this.game.timer.tweenAsync(this, { value }, BAR_DURATION);. { value } is short for { value: value }.