Mastering JavaScript: Build Your Own Slot Machine Game!

Mastering JavaScript: Build Your Own Slot Machine Game!

Slot machines have been a staple in casinos for decades, offering players a chance to win big. In this article, we will explore how to build a simple slot machine game using JavaScript and Node.js.

By the end, you'll have a fully functional game that allows players to deposit money, choose the number of lines to bet on, specify their bet amount, and spin the reels to potentially win prizes. We'll also cover how to check for winning combinations and distribute winnings.

This is just a game, no one is promoting Gambling in any way!

Prerequisites

Before diving into the code, make sure you have the following prerequisites:

  1. JavaScript Knowledge: You should have a good understanding of JavaScript programming concepts, including variables, loops, and functions.

  2. Node.js: Ensure that Node.js is installed on your computer. Node.js will allow us to run our JavaScript code outside of a web browser.

Let's start building our slot machine game step by step. I'll break down the code and explain each part as we go along.

Initialization:

Before we dive into building the game, let's set up some important constants and objects that will define the game's structure.

We have defined the number of rows and columns in the slot machine display as well as the symbols that will be used in the game, along with their respective counts and values.

const prompt = require("prompt-sync")();

const ROWS = 3;
const COLS = 3;

const SYMBOLS_COUNT = {
    A: 2,
    B: 4,
    C: 6,
    D: 8,
};

const SYMBOL_VALUES = {
    A: 5,
    B: 4,
    C: 3,
    D: 2,
};

Game Mechanics:

1. Depositing Money

The first step in our game is to allow players to deposit money. The deposit function prompts the user for a deposit amount and validates it to ensure it's a positive number.

const deposit = () => {
    while (true) {
        const depositAmount = prompt("Enter a deposit amount: ");
        const numberDepositAmount = parseFloat(depositAmount);

        if (isNaN(numberDepositAmount) || numberDepositAmount <= 0) {
            console.log("Invalid deposit amount, try again.");
        } else {
            return numberDepositAmount;
        }
    }
};

2. Choosing the Number of Lines

Next, players can choose the number of lines they want to bet on. The getNumberOfLines function handles this input.

const getNumberOfLines = () => {
    while (true) {
        const lines = prompt("Enter the number of lines to bet on (1-3): ");
        const numberOfLines = parseFloat(lines);

        if (isNaN(numberOfLines) || numberOfLines <= 0 || numberOfLines > 3) {
            console.log("Invalid number of lines, try again.");
        } else {
            return numberOfLines;
        }
    }
};

3. Setting the Bet Amount

Players can specify their bet amount per line. The getBet function ensures that the bet amount is valid and within their balance.

const getBet = (balance, lines) => {
    while (true) {
        const bet = prompt("Enter the bet per line: ");
        const numberBet = parseFloat(bet);

        if (isNaN(numberBet) || numberBet <= 0 || numberBet > balance / lines) {
            console.log("Invalid bet, try again.");
        } else {
            return numberBet;
        }
    }
};

4. Spinning the Reels

Now comes the fun part – spinning the reels. The spin function generates random outcomes for each reel position.

const spin = () => {
    const symbols = [];
    for (const [symbol, count] of Object.entries(SYMBOLS_COUNT)) {
        for (let i = 0; i < count; i++) {
            symbols.push(symbol);
        }
    }

    const reels = [];
    for (let i = 0; i < COLS; i++) {
        reels.push([]);
        const reelSymbols = [...symbols];
        for (let j = 0; j < ROWS; j++) {
            const randomIndex = Math.floor(Math.random() * reelSymbols.length);
            const selectedSymbol = reelSymbols[randomIndex];
            reels[i].push(selectedSymbol);
            reelSymbols.splice(randomIndex, 1);
        }
    }

    return reels;
};

Transpose and Print Rows:

transpose function takes an array of reels as input and returns a transposed version of the array.

printRows function takes an array of rows as input and prints the rows with appropriate formatting.

const transpose = (reels) => {
    const rows = [];

    for (let i = 0; i < ROWS; i++) {
        rows.push([]);
        for (let j = 0; j < COLS; j++) {
            rows[i].push(reels[j][i]);
        }
    }

    return rows;
};

const printRows = (rows) => {
    for (const row of rows) {
        let rowString = "";
        for (const [i, symbol] of row.entries()) {
            rowString += symbol;
            if (i != row.length - 1) {
                rowString += " | ";
            }
        }
        console.log(rowString);
    }
};

5. Checking for Winning Combinations

Once the reels stop spinning, we need to check if the player has won on any of the lines. The getWinnings function calculates the player's winnings based on the bet and winning combinations.

const getWinnings = (rows, bet, lines) => {
    let winnings = 0;

    for (let row = 0; row < lines; row++) {
        const symbols = rows[row];
        let allSame = true;

        for (const symbol of symbols) {
            if (symbol != symbols[0]) {
                allSame = false;
                break;
            }
        }

        if (allSame) {
            winnings += bet * SYMBOL_VALUES[symbols[0]];
        }
    }

    return winnings;
};

6. Playing the Game

Finally, we put it all together in the game function. This function allows players to deposit money, choose the number of lines and bet amount, spin the reels, and check for winnings. The game continues until the player decides to stop or runs out of money.

const game = () => {
    let balance = deposit();

    while (true) {
        console.log("You have a balance of $" + balance);
        const numberOfLines = getNumberOfLines();
        const bet = getBet(balance, numberOfLines);
        balance -= bet * numberOfLines;
        const reels = spin();
        const rows = transpose(reels);
        printRows(rows);
        const winnings = getWinnings(rows, bet, numberOfLines);
        balance += winnings;
        console.log("You won, $" + winnings.toString());

        if (balance <= 0) {
            console.log("You ran out of money!");
            break;
        }

        const playAgain = prompt("Do you want to play again (y/n)? ");

        if (playAgain != "y") break;
    }
};

game();

Conclusion

And there you have it, a simple and magical slot machine game built with JavaScript. With this as a reference, you can create even more exciting games and adventures on your computer.

Like the article? Drop a comment and let me know.

Let's connect on socials and learn more exciting things together.

Twitter

LinkedIn

GitHub

Did you find this article valuable?

Support Insha Ramin by becoming a sponsor. Any amount is appreciated!