NpcForBattle.js
Over the past couple of weeks, I’ve been working on a class that inherits the Character class. It is used in the 3rd-4th level of my game where a interaction with the Paladin Npc triggers a battle.
Implementation
The NpcForBattle class extends the Character class, inheriting it’s properties and methods. As you can see, first we define the variables and functions of the BattleNpc:
import GameEnv from "./GameEnv.js";
import Character from "./Character.js";
import Prompt from "./Prompt.js";
class NpcForBattle extends Character {
constructor(data = null) {
super(data);
this.quiz = data?.quiz?.title;
this.questions = Prompt.shuffleArray(data?.quiz?.questions || []);
this.currentQuestionIndex = 0;
this.health = data?.health || 100;
this.playerhealth = data?.playerhealth || 100;
this.playerattack = data?.playerattack || 10;
this.playerkill = data?.playerkill || 70;
this.attackInterval = null;
this.bPressCount = 0;
this.isPlayerTurn = true; // Turn flag to control whose turn it is
this.turnMessageBox = null; // New message box for turn indication
this.startTurnBasedBattle();
this.stopAttacking();
this.createAttackButton();
this.createRestButton();
this.bindEventListeners();
}
}
How does the Turn-Based system work?
The “startTurnBasedBattle()” function controls how to turns of the player and npc work in the game, forcing strict order.
startTurnBasedBattle() {
this.startPlayerTurn();
}
startPlayerTurn() {
this.isPlayerTurn = true;
this.showTurnMessage("Your turn to attack!", "player");
console.log("Player's turn.");
}
startNpcTurn() {
this.isPlayerTurn = false;
this.showTurnMessage("NPC's turn to attack!", "npc");
console.log("NPC's turn.");
// Wait for 5 seconds before the NPC attacks
setTimeout(() => {
this.attackPlayer(); // NPC attacks after the delay
this.startPlayerTurn(); // Start player's turn after NPC's action
}, 5000);
}
What about the attack?
The “attackNpc/Player” functions determine whether the player’s or npc’s health decrease or not.
attackNpc() {
if (this.isPlayerTurn) {
this.showFloatingMessage2("Player attacks NPC!", "player");
console.log("Player attacks NPC!");
this.reduceNpcHealth();
if (this.health <= 0) {
this.onNpcDefeat();
} else {
this.startNpcTurn(); // NPC's turn after player attack
}
}
}
attackPlayer() {
if (!this.isPlayerTurn) {
this.showFloatingMessage2("NPC attacks player!", "npc");
console.log("NPC attacks player!");
this.reducePlayerHealth();
if (this.playerhealth <= 0) {
this.onPlayerDefeat();
}
}
}
How the game ends!
These two commands determine how the game ends after either the player or npc is defeated.
onPlayerDefeat() {
this.showGameOverMessage();
console.log("Player defeated. Moving to next level.");
}
onNpcDefeat() {
alert("NPC has been defeated! You win this round.");
console.log("NPC has been defeated!");
this.stopAttacking();
this.hideButtons(); // Hide buttons after the NPC is defeated
}