Survival Game Example

Here is an example of getters and setters in the context of a hypothetical survival computer game:

class Character {
  constructor(name, health, maxHealth) {
    this._name = name;
    this._health = health;
    this._maxHealth = maxHealth;
  }
  
  get name() {
    return this._name;
  }
  
  set name(newName) {
    this._name = newName;
  }
  
  get health() {
    return this._health;
  }
  
  set health(newHealth) {
    if (newHealth > this._maxHealth) {
      this._health = this._maxHealth;
    } else {
      this._health = newHealth;
    }
  }
  
  get maxHealth() {
    return this._maxHealth;
  }
  
  set maxHealth(newMaxHealth) {
    this._maxHealth = newMaxHealth;
  }
  
  heal(amount) {
    this.health += amount;
  }
  
  damage(amount) {
    this.health -= amount;
  }
}

class Player extends Character {
  constructor(name, health, maxHealth, inventory) {
    super(name, health, maxHealth);
    this._inventory = inventory;
  }
  
  get inventory() {
    return this._inventory;
  }
  
  set inventory(newInventory) {
    this._inventory = newInventory;
  }
  
  useItem(item) {
    // use the item
  }
}

const player = new Player("Bob", 100, 100, []);
console.log(player.name); // "Bob"
console.log(player.health); // 100
console.log(player.maxHealth); // 100
player.heal(20);
console.log(player.health); // 100
player.damage(90);
console.log(player.health); // 10
player.inventory = ["medkit", "water bottle"];
console.log(player.inventory); // ["medkit", "water bottle"]

In this example, we have a base Character class that represents any character in the game with a name, health, and max health. The Player class extends the Character class and adds an inventory property. We have defined getters and setters for all of these properties, allowing us to control how they are accessed and modified. The heal and damage methods use the setter for the health property to ensure that the character's health never exceeds their max health. The Player class also has a useItem method for using items from their inventory.

Last updated