Tactical Role Playing Game
Here is an example of method chaining in the context of a hypothetical tactical role-playing game (TRPG):
class Character {
constructor(name, health, attack, defense) {
this._name = name;
this._health = health;
this._attack = attack;
this._defense = defense;
}
get name() {
return this._name;
}
get health() {
return this._health;
}
set health(newHealth) {
this._health = newHealth;
}
get attack() {
return this._attack;
}
get defense() {
return this._defense;
}
attack(character) {
character.health -= this.attack;
}
defend() {
this.defense += 5;
return this;
}
usePotion() {
this.health += 10;
return this;
}
}
class Player extends Character {
constructor(name, health, attack, defense, level, experience) {
super(name, health, attack, defense);
this._level = level;
this._experience = experience;
}
get level() {
return this._level;
}
set level(newLevel) {
this._level = newLevel;
}
get experience() {
return this._experience;
}
set experience(newExperience) {
this._experience = newExperience;
}
levelUp() {
this.level++;
this.attack += 5;
this.defense += 5;
this.health += 10;
return this;
}
}
const player = new Player("Bob", 100, 20, 10, 1, 0);
const enemy = new Character("Goblin", 50, 15, 5);
player.attack(enemy);
console.log(enemy.health); // 35
player.defend().usePotion().levelUp().attack(enemy);
console.log(player.attack); // 25
console.log(player.defense); // 20
console.log(player.health); // 120
console.log(enemy.health); // 20
In this example, we have a base Character
class that represents any character in the game with a name, health, attack, and defense. The Player
class extends the Character
class and adds a level and experience. The Character
class has attack
, defend
, and usePotion
methods that return the character object itself, allowing the methods to be chained together. The Player
class also has a levelUp
method that increases the player's level and stats.
In the example code, we create a player and an enemy character, and then use method chaining to chain together calls to the defend
, usePotion
, and levelUp
methods before attacking the enemy again. This allows the player to increase their defense, heal themselves, level up, and then attack the enemy in a single statement
Last updated