Last active
January 15, 2023 18:34
-
-
Save perjo927/6878ee19bf058527cf6c5fd32371df82 to your computer and use it in GitHub Desktop.
Generator-based slot machine game
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
const getRandomInt = (range) => Math.floor(Math.random() * range); | |
// Create an array of symbols for the slot machine | |
const symbols = ['🍒', '🍋', '🔔', '7️⃣', '🎱']; | |
// Define a generator function that will yield a random symbol | |
// from the array when iterated over | |
function* getReels(noOfReels = 3) { | |
let i = 0; | |
while (i++ < noOfReels) { | |
yield symbols[getRandomInt(symbols.length)]; | |
} | |
} | |
function* getSlotMachine() { | |
let balance = 0; | |
let betSize = 10; | |
let round = 1; | |
while (balance === 0) { | |
console.log('Please deposit coins!'); | |
const deposit = yield balance; | |
balance += isNaN(deposit) ? 0 : deposit; | |
} | |
console.log('Game started!'); | |
console.log(`Balance: ${balance}`); | |
while (balance > 0) { | |
// Consume any new coins | |
const deposit = yield balance; | |
balance += isNaN(deposit) ? 0 : deposit; | |
// Play game round, if enough balance | |
if (balance - betSize < 0) { | |
break; | |
} | |
console.log(`ROUND ${round++} BEGIN`); | |
balance -= betSize; | |
const result = [...getReels()]; | |
// If we land three symbols in a row, we win | |
// A set can not contain duplicates | |
// A set with size 1 means there are 3 duplicates, hence we win | |
const areSame = new Set(result).size === 1; | |
// Print reader-friendly result | |
console.log(result.join(' | ')); // 7️⃣ | 🍒 | 🍒 | |
if (areSame) { | |
// Find the weight of the winning symbol | |
const winSize = symbols.indexOf(result[0]); | |
const winInCoins = betSize * (winSize + 1); | |
// Calculate win using the weight of the index of the symbol | |
console.log(`You won ${winInCoins} coins!`); | |
balance += winInCoins; | |
} else { | |
console.log('No win'); | |
} | |
console.log(`Balance: ${balance}`); | |
} | |
console.log('Game over!'); | |
return 0; | |
} | |
let state; | |
const game = getSlotMachine(); | |
game.next(); // "Please deposit coins" | |
state = game.next(30); // "Game started!" | |
// Autoplay | |
while (state.value > 0) { | |
state = game.next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment