> For the complete documentation index, see [llms.txt](https://demirels-organization.gitbook.io/javascript-tutorial/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://demirels-organization.gitbook.io/javascript-tutorial/es-modules/tower-defence-game-example.md).

# Tower Defence Game Example

Here's an example of how you might use ECMAScript (ES) modules in a JavaScript tower defence game:

First, let's define a `Tower` class in a file called `Tower.js`:

```javascript
export class Tower {
  constructor(x, y, range, damage) {
    this.x = x;
    this.y = y;
    this.range = range;
    this.damage = damage;
  }

  attack(enemy) {
    // Calculate distance from tower to enemy
    const distance = Math.sqrt(Math.pow(enemy.x - this.x, 2) + Math.pow(enemy.y - this.y, 2));

    if (distance <= this.range) {
      enemy.health -= this.damage;
    }
  }
}
```

Next, let's define an `Enemy` class in a file called `Enemy.js`:

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

Now, let's create a main game file called `game.js` that imports the `Tower` and `Enemy` classes:

```javascript
import { Tower } from './Tower.js';
import { Enemy } from './Enemy.js';

const tower = new Tower(5, 5, 3, 10);
const enemy = new Enemy(7, 7, 50);

tower.attack(enemy);

console.log(enemy.health); // 40
```

In this example, we have three separate JavaScript files: `Tower.js`, `Enemy.js`, and `game.js`. The `Tower` and `Enemy` classes are defined in their own files and then exported using the `export` keyword. These classes can then be imported into the `game.js` file using the `import` keyword.

This is just a simple example, but in a more complex game you could use ES modules to organize your code into separate modules for different game entities (e.g. towers, enemies, player characters, etc.), as well as for utility functions and other game logic.
