← Back to home
Tutorial series

Step 12. Earning and spending coins

Creating Tower Defense game with PIXI Step 12 of 12 2 min read

The player will spend coins to build and upgrade towers. And he will earn coins for killing each enemy. The cost of each tower, as well as the reward value for killing an enemy, is indicated in the towers and enemies configs in Config.js.

Let’s add processing of expenses and earnings to the corresponding methods of the Game class.

  1. Let’s add an addditional check for the required number of coins and further spending on building and upgrading a tower in the onTowerPlaceClick method:
onTowerPlaceClick(towerPlace) {
    const towerConfig = App.config.towers["tower" + (towerPlace.level + 1)];

    if (!towerConfig) {
        return;
    }

    if (this.player.coins < towerConfig.coins) {
        return;
    }

    this.player.coins -= towerConfig.coins;
    ++towerPlace.level;
    // ...
}
  1. We will also give the player a reward for killing an enemy unit in the processEnemyBulletCollision method:
processEnemyBulletCollision() {
    // ...
    enemy.addDamage(bullet.damage);
    if (enemy.hp <= 0) {
        this.player.coins += enemy.config.coins;
    }
    // ...
}

Since our UI is already constantly updated in the Game.update method, we do not need to additionally redraw the UI for each such action.