95 lines
1.7 KiB
JavaScript
95 lines
1.7 KiB
JavaScript
class TreasureChest {
|
|
|
|
#gold;
|
|
#silver;
|
|
#bronze;
|
|
|
|
constructor (initialLoot = {}) {
|
|
|
|
// Merge options into defaults
|
|
let {bronze, silver, gold} = Object.assign({
|
|
bronze: 0,
|
|
silver: 0,
|
|
gold: 0,
|
|
}, initialLoot);
|
|
|
|
this.#bronze = bronze;
|
|
this.#silver = silver;
|
|
this.#gold = gold;
|
|
}
|
|
|
|
addGold (qty) {
|
|
this.#gold += qty;
|
|
|
|
return this;
|
|
}
|
|
|
|
addSilver (qty) {
|
|
this.#silver += qty;
|
|
|
|
return this;
|
|
}
|
|
|
|
addBronze (qty) {
|
|
this.#bronze += qty;
|
|
|
|
return this;
|
|
}
|
|
|
|
getBronze () {
|
|
return this.#bronze;
|
|
}
|
|
|
|
getSilver () {
|
|
return this.#silver;
|
|
}
|
|
|
|
getGold () {
|
|
return this.#gold;
|
|
}
|
|
|
|
getLoot () {
|
|
return `Gold: ${this.#gold}, Silver: ${this.#silver}, Bronze: ${this.#bronze}`;
|
|
}
|
|
|
|
/**
|
|
* Randomly shuffle an array
|
|
* https://stackoverflow.com/a/2450976/1293256
|
|
* @param {Array} array The array to shuffle
|
|
* @return {Array} The shuffled array
|
|
*/
|
|
static #shuffle (array) {
|
|
let currentIndex = array.length;
|
|
let temporaryValue, randomIndex;
|
|
|
|
// While there remain elements to shuffle...
|
|
while (0 !== currentIndex) {
|
|
// Pick a remaining element...
|
|
randomIndex = Math.floor(Math.random() * currentIndex);
|
|
currentIndex -= 1;
|
|
|
|
// And swap it with the current element.
|
|
temporaryValue = array[currentIndex];
|
|
array[currentIndex] = array[randomIndex];
|
|
array[randomIndex] = temporaryValue;
|
|
}
|
|
|
|
return array;
|
|
}
|
|
|
|
static getRandomLoot () {
|
|
let amount = [];
|
|
|
|
for (let qty = 0; qty < 50; qty++) {
|
|
amount.push(qty+1);
|
|
}
|
|
|
|
return {
|
|
gold: this.#shuffle(amount)[0],
|
|
silver: this.#shuffle(amount)[0],
|
|
bronze: this.#shuffle(amount)[0],
|
|
}
|
|
}
|
|
|
|
};
|
|
|