Created
May 18, 2024 04:49
-
-
Save EncodeTheCode/37c217cc73188ecfeef455d89d28cc98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Player { | |
constructor(name, level = 1, currentXP = 0, totalXP = 0, xpForNextLevel = 100, xpGrowthRate = 1.5) { | |
this.name = name; | |
this.level = level; | |
this.currentXP = currentXP; | |
this.totalXP = totalXP; | |
this.xpForNextLevel = xpForNextLevel; | |
this.xpGrowthRate = xpGrowthRate; | |
} | |
addXP(amount) { | |
if (amount < 0) throw new Error("XP amount must be non-negative"); | |
this.currentXP += amount; | |
this.totalXP += amount; | |
while (this.currentXP >= this.xpForNextLevel) { | |
this.levelUp(); | |
} | |
} | |
levelUp() { | |
this.currentXP -= this.xpForNextLevel; | |
this.level++; | |
this.xpForNextLevel = Math.floor(this.xpForNextLevel * this.xpGrowthRate); | |
console.log(`Level Up! ${this.name} is now level ${this.level}`); | |
} | |
removeXP(amount) { | |
if (amount < 0) throw new Error("XP amount must be non-negative"); | |
this.currentXP -= amount; | |
while (this.currentXP < 0 && this.level > 1) { | |
this.levelDown(); | |
} | |
if (this.currentXP < 0) { | |
this.currentXP = 0; | |
} | |
} | |
levelDown() { | |
this.level--; | |
this.xpForNextLevel = Math.floor(this.xpForNextLevel / this.xpGrowthRate); | |
this.currentXP += this.xpForNextLevel; | |
console.log(`Level Down! ${this.name} is now level ${this.level}`); | |
} | |
displayStatus() { | |
console.log(`Name: ${this.name}`); | |
console.log(`Level: ${this.level}`); | |
console.log(`Current XP: ${this.currentXP}`); | |
console.log(`Total XP: ${this.totalXP}`); | |
console.log(`XP for next level: ${this.xpForNextLevel}`); | |
} | |
} | |
// Manage multiple players | |
const players = { | |
'player1': new Player('Player1'), | |
'player2': new Player('Player2'), | |
'player3': new Player('Player3') | |
}; | |
// Function to give XP to a specific player | |
function giveXPToPlayer(playerName, amount) { | |
const player = players[playerName]; | |
if (player) { | |
player.addXP(amount); | |
player.displayStatus(); | |
} else { | |
console.log(`Player ${playerName} not found`); | |
} | |
} | |
// Example usage | |
giveXPToPlayer('player1', 150); | |
giveXPToPlayer('player2', 200); | |
giveXPToPlayer('player3', 50); | |
giveXPToPlayer('player1', 100); | |
giveXPToPlayer('player2', 300); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment