-
-
Save renfri897/286a2e8c3e020cf2b5a91dba9c170585 to your computer and use it in GitHub Desktop.
Generator-based slot machine game
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) { | |
| 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