Created
May 18, 2024 04:47
-
-
Save EncodeTheCode/e99cb9d46b8e1cef9b5955f972105c8c 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(level = 1, currentXP = 0, totalXP = 0, xpForNextLevel = 100, xpGrowthRate = 1.5) { | |
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! You are 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! You are now level ${this.level}`); | |
} | |
displayStatus() { | |
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}`); | |
} | |
} | |
// Example usage | |
const player = new Player(); | |
player.displayStatus(); | |
player.addXP(150); | |
player.displayStatus(); | |
player.addXP(200); | |
player.displayStatus(); | |
player.removeXP(100); | |
player.displayStatus(); | |
player.removeXP(300); | |
player.displayStatus(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment