Last active
January 15, 2023 18:33
-
-
Save perjo927/14f018abb9324e6de5670be109917303 to your computer and use it in GitHub Desktop.
Generator-based slot machine game #2
This file contains hidden or 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) { | |
const deposit = yield 'Please deposit money'; | |
balance += isNaN(deposit) ? 0 : deposit; | |
} | |
while (balance > 0) { | |
const deposit = yield `\nRound ${round++}. Balance: ${balance}`; | |
balance += isNaN(deposit) ? 0 : deposit; | |
if (balance - betSize < 0) { | |
break; | |
} | |
balance -= betSize; | |
const result = [...getReels()]; | |
const areSame = new Set(result).size === 1; | |
yield result.join(' | '); | |
if (areSame) { | |
const winSize = symbols.indexOf(result[0]); | |
const winInCoins = betSize * (winSize + 1); | |
balance += winInCoins; | |
yield `Win: ${winInCoins}`; | |
} else { | |
yield 'No win'; | |
} | |
} | |
} | |
let state; | |
const game = getSlotMachine(); | |
game.next(); | |
state = game.next(30); | |
console.log(state.value); | |
const gameRounds = [...game]; | |
gameRounds.forEach(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment