Skip to content

Instantly share code, notes, and snippets.

@telagraphic
Created February 8, 2023 16:42
Show Gist options
  • Save telagraphic/8959188e8df9965db50c90c48bbfd143 to your computer and use it in GitHub Desktop.
Save telagraphic/8959188e8df9965db50c90c48bbfd143 to your computer and use it in GitHub Desktop.
treasure-chest-class
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Treasure Chest - User Options</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
</style>
</head>
<body>
<h1>Treasure Chest - Class Refactor</h1>
<p>All of the magic here happens in the console.</p>
<script>
class TreasureChest {
constructor(options = {}) {
let {
bronze,
silver,
gold,
loot
} = Object.assign({
bronze: 0,
silver: 0,
gold: 0,
loot: `You have {{gold}} gold, {{silver}} silver, and {{bronze}} bronze.`
}, options);
Object.defineProperties(this, {
bronze: {
value: bronze,
writable: true
},
silver: {
value: silver,
writable: true
},
gold: {
value: gold,
writable: true
},
_loot: {
value: loot
}
})
};
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;
};
addBronze(number) {
this.bronze += number;
return this;
};
addSilver(number) {
this.silver += number;
return this;
};
addGold(number) {
this.gold += number;
return this;
};
getLoot() {
return this._loot.replace('{{gold}}', this.gold).replace('{{silver}}', this.silver).replace('{{bronze}}', this.bronze);
};
static getRandomLoot() {
// Amount and type
let amount = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];
let type = ['bronze', 'silver', 'gold'];
// Randomize the amounts
this.shuffle(amount);
this.shuffle(type);
// Return the random loot
return {
amount: amount[0],
type: type[0]
};
};
}
let captain = new TreasureChest();
let captainLoot = captain.addGold(10).addSilver(5).addBronze(50).getLoot();
console.log(captainLoot);
let random = TreasureChest.getRandomLoot();
console.log(random);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment