JavaScript Tutorial
  • 🍼Introduction
  • 🥛Hello Gamers
  • 🍯Variables
    • Action Game Example
  • 🌰Strings
    • RPG Example
  • 🍪Character Acces
    • Simulation Example
  • 🍩Plus (+) operator
    • Strategy Game Example
  • 🥜Functions
    • Adventure Game Example
  • 🍿Template strings
    • Strategy Game Example
  • 🍫Numbers
    • Sports Game Example
  • 🍬Converting Numbers to Strings
    • Fighting Game Example
  • 🍭Operations
    • FPS Game Example
  • 🍮Conditions
    • Platformer Game Example
  • 🎂Arrays
    • Puzzle Game Example
  • 🍰Objects
    • Racing Game Example
  • 🧁Arrow Functions
    • Rhythm Game Example
  • 🔌Shameless Plug
  • 🥧Implicit Return
    • Platform Game Example
  • 🍦String Methods
    • GRID Game Example
  • 🍨Object Literals
    • Board Game Example
  • 🍧DynamicProperty
    • Political Game Example
  • 🍡Reading Dynamic Property
    • Hide & Seek Game
  • 🥮Objects Continued
    • Medieval Game Example
  • 🥠Object Shorthands
    • Trivia Game example
  • 🔌Shameless Plug (again)
  • 🍥Destructuring & Concatenation
    • Dig a hole game example
  • 🍏Optional Chaining
    • Action Game Example
  • 🍐Nullish coalescing operator
    • Adventure Game Example
  • 🍊Refactoring If Conditions
    • Arcade Game Example
  • 🍋Implicit Conversion & Falcy Values
    • Strategy Game Example
  • 🍌Arrays of objects
    • Sports Game Example
  • 🍉Transforming Array of Objects
    • Fighters Game Example
  • 🍇Some important array methods
    • FPS Example
  • 🫐Reducing arrays of objects
    • Third Person Shooter Example
  • 🍓Try....catch
    • Platformer Example
  • 🍈Immutability
    • Puzzle game example
  • 🍒Creating new arrays or objects
    • Racing Game Example
  • 🔌Shameless Plug (again)
  • 🍑Immutable object operations
    • Basics
    • Rhythm Game Example
  • 🥭Classes
    • Basics
    • Platformer Game Example
  • 🍍Instance Method
    • Basics
    • Role-playing game example
  • 🥥Object Oriented Programming
    • Basics
    • Stealth Game Example
  • 🥝Getters & Setters
    • Basics
    • Survival Game Example
  • 🍅Static Methods & Chaining
    • Basics
    • Tactical Role Playing Game
  • 🍆Class Inheritance
    • Tower Defense Game Example
  • 🥑Use of Super
    • Vehicular Combat Game example
  • 🫒Public Class Field
    • MMORPG Example
  • 🥦Private class fields
    • Battle Royale Games Example
  • 🥬Aysnc/Await
    • Collectible Card Game example
    • Video Board game example
  • 🫑SetTimeout
    • Dice game example
  • 🥒Execution Order
    • Digital Collectible Card Game example
  • 🌶️The callback pattern
    • Life Simulation Game example
  • 🌽Promises
    • Music Game Example
  • 🥕Writing a function that returns a promise
    • Party game example
  • 🧄Introduction to JSON
    • Tile based game example
  • 🧅JSON.parse(string) / JSON.stringify(object)
    • Rhythm action game example
  • 🍠JSON Example for a game
    • Fetching JSON game data
  • 🥐Handling fetch errors
    • Fetch and HTTP Requests
  • 🥯ES Modules
    • Tower Defence Game Example
  • 🍞Default Export
    • Strategy Adventure Game Example
  • 🥖Fetch Wrapper
    • Strategy Role-playing game example
  • 🔌Final Shameless Plug
  • 🫓Lexical Scope and Arrow Functions
    • Vehicular Combat Game Example
  • 🥨Passing Functions
    • Vehicular simulation game example
  • 🥚Dynamic Imports
    • Video card game example
  • 🍠What is a closure
    • Video casino game example
  • 🎆Congratulations
Powered by GitBook
On this page
  1. Class Inheritance

Tower Defense Game Example

Here is an example of class inheritance in the context of a tower defense game

class Tower {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.range = 1;
    this.damage = 1;
    this.price = 10;
  }

  attack(enemies) {
    // Find the closest enemy within range
    let closestEnemy = null;
    let closestDistance = this.range + 1;
    for (const enemy of enemies) {
      const distance = Math.sqrt(Math.pow(enemy.x - this.x, 2) + Math.pow(enemy.y - this.y, 2));
      if (distance < closestDistance) {
        closestEnemy = enemy;
        closestDistance = distance;
      }
    }

    // Attack the closest enemy if it is within range
    if (closestEnemy && closestDistance <= this.range) {
      closestEnemy.health -= this.damage;
      console.log(`Tower at (${this.x}, ${this.y}) attacked enemy at (${closestEnemy.x}, ${closestEnemy.y}) for ${this.damage} damage.`);
      if (closestEnemy.health <= 0) {
        console.log(`Enemy at (${closestEnemy.x}, ${closestEnemy.y}) has been defeated!`);
      }
    }
  }
}

class MissileTower extends Tower {
  constructor(x, y) {
    super(x, y);
    this.range = 3;
    this.damage = 5;
    this.price = 30;
  }

  attack(enemies) {
    // Find all enemies within range
    const enemiesInRange = enemies.filter(enemy => {
      const distance = Math.sqrt(Math.pow(enemy.x - this.x, 2) + Math.pow(enemy.y - this.y, 2));
      return distance <= this.range;
    });

    // Attack all enemies within range
    for (const enemy of enemiesInRange) {
      enemy.health -= this.damage;
      console.log(`Missile tower at (${this.x}, ${this.y}) attacks enemy at (${enemy.x}, ${enemy.y}) for ${this.damage} damage.`);
      if (enemy.health <= 0) {
        console.log(`Enemy at (${enemy.x}, ${enemy.y}) has been defeated!`);
      }
    }
  }
}

class Enemy {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.health = 10;
  }
}

// Create a new tower and enemy
const tower = new Tower(5, 5);
const enemy = new Enemy(10, 5);

// Attack the enemy with the tower
tower.attack([enemy]);
// Output: "Tower at (5, 5) attack enemy at (10, 5) for 1 damage."

// Create a new missile tower and enemy
const missileTower = new MissileTower(5, 5);
const enemy2 = new Enemy(8,5);

// Attack the enemy with the missile tower
missileTower.attack([enemy2]);
// Output: "Missile tower at (5, 5) attacks enemy at (8, 5) for 5 damage."

// Create a new missile tower and multiple enemies
const missileTower2 = new MissileTower(5, 5);
const enemy3 = new Enemy(7, 5);
const enemy4 = new Enemy(9, 5);
const enemy5 = new Enemy(10, 5);

// Attack the enemies with the missile tower
missileTower2.attack([enemy3, enemy4, enemy5]);
// Output:
// "Missile tower at (5, 5) attacks enemy at (7, 5) for 5 damage."
// "Missile tower at (5, 5) attacks enemy at (9, 5) for 5 damage."
// "Missile tower at (5, 5) attacks enemy at (10, 5) for 5 damage."

In this example you can clearly see how Missile Tower extends the functionality of base tower using class inheritance

PreviousClass InheritanceNextUse of Super

Last updated 2 years ago

🍆