Survival Game Example
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"]Last updated