Skip to content

Instantly share code, notes, and snippets.

@perjo927
Last active January 15, 2023 18:33
Show Gist options
  • Save perjo927/14f018abb9324e6de5670be109917303 to your computer and use it in GitHub Desktop.
Save perjo927/14f018abb9324e6de5670be109917303 to your computer and use it in GitHub Desktop.
Generator-based slot machine game #2
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