Open In App

Create a Bingo Game Using JavaScript

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Bingo is a fun and popular game that relies on luck and strategy. In this tutorial, we’ll show you how to make a simple Bingo game using JavaScript. Whether you’re a beginner or just looking for a fun project, this guide will walk you through the process step by step.

Prerequisites:

Approach:

Before diving into the code, it’s essential to understand the approach and logic behind creating a Bingo game:

Step 1: Opening the Game

  • Open the Bingo game on your computer using a web browser. It’s like opening any other website.

Step 2: Game Display

  • You’ll see the game board with two cards: one for “Player 1” and one for “Player 2.” Each card has a grid with numbers from 1 to 25.

Step 3: Starting the Game

  • To start the game, click the “Start” button. This will give both players their Bingo cards and enable the “Mark” button.

Step 4: Marking Numbers

  • You take turns with the other player. To mark a number on your card, type a number between 1 and 25 into the box that says “Enter a number (1-25)” and then click “Mark.”
  • If your number matches a number on your card, it will get marked with an “X.”

Step 5: Playing Back and Forth

  • The game keeps going back and forth between you and the other player. You both try to get a Bingo by marking numbers in a row, column, or diagonal.

Step 6: Winning the Game

  • The game continues until one player gets a Bingo by filling a whole row, column, or diagonal with “X” marks.

Step 7: Winning Announcement

  • When someone wins, a message appears on the screen, saying who won. It’s a fun moment!

Step 8: Resetting the Game

  • If you want to play again, just click the “Reset” button. This clears the cards and lets you start a new game.

Example: Below is the implementation of the Game.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
      initial-scale=1.0">
    <title>Bingo Game</title>
    <link rel="stylesheet" href="style.css">
</head>
  
<body>
    <div class="bingo-container">
        <h1>Bingo Game</h1>
        <div class="player-cards">
            <h1>Player 1's Card</h1>
            <div class="player-card" id="player1Card">
            </div>
            <div class="player-card" id="player2Card">
            </div>
            <h1>Player 2's Card</h1>
        </div>
        <div class="controls">
            <button id="startButton">
                Start
            </button>
            <button id="resetButton" disabled>
                Reset
            </button>
        </div>
        <div class="input-container">
            <label for="numberInput">
                Enter a number (1-25):
            </label>
            <input type="number" 
                   id="numberInput" 
                   min="1" max="25" disabled>
            <button id="markButton" disabled>
                Mark
            </button>
        </div>
        <div id="turnDisplay"></div>
        <!-- Display win message here -->
        <div id="winDisplay"></div>
    </div>
    <script src="script.js"></script>
</body>
  
</html>


CSS




body {
    font-family: Arial, sans-serif;
    background-color: #d8f3dc;
    /* Light green background color */
    margin: 0;
    padding: 0;
}
  
.bingo-container {
    text-align: center;
    padding: 20px;
}
  
h1 {
    color: #379683;
    /* Dark green text color */
}
  
.player-cards {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
}
  
.player-card {
    background-color: #fff;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 5px;
}
  
.player-card h2 {
    color: #379683;
    /* Dark green text color */
}
  
.controls {
    margin-top: 20px;
}
  
button {
    background-color: #379683;
    /* Dark green button background color */
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-weight: bold;
}
  
button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}
  
.input-container {
    margin-top: 10px;
}
  
label {
    font-weight: bold;
    color: #379683;
    /* Dark green text color */
}
  
#numberInput {
    padding: 5px;
    margin-right: 10px;
}
  
#turnDisplay {
    font-weight: bold;
    color: #ff5e78;
    /* Light red text color */
}
  
/* Style individual numbers in the player cards */
.player-card div {
    background-color: #379683;
    /* Dark green number background color */
    color: white;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}
  
.player-card div.marked {
    background-color: #ff5e78;
    /* Light red for marked numbers */
}
  
@keyframes celebrate {
  
    0%,
    100% {
        transform: translateY(0);
    }
  
    50% {
        transform: translateY(-20px);
    }
}
  
#winDisplay {
    font-weight: bold;
    font-size: large;
    text-decoration: underline;
    color: #098900de;
    /* Light red text color */
    margin-top: 30px;
    animation: celebrate 1s ease-in-out infinite;
}


Javascript




const ROWS = 5;
const COLS = 5;
const MAX_NUM = 25;
  
let currentPlayer = 1;
let player1Card, player2Card;
  
function createBingoCard() {
    const card = [];
    const usedNumbers = new Set();
  
    while (usedNumbers.size < ROWS * COLS) {
        const num =
            Math
                .floor(Math.random() *
                    MAX_NUM) + 1;
        if (!usedNumbers.has(num)) {
            usedNumbers.add(num);
        }
    }
  
    const numbersArray =
        Array.from(usedNumbers);
    for (let i = 0; i < ROWS; i++) {
        card.push(numbersArray
            .slice(i * COLS, (i + 1) * COLS));
    }
  
    return card;
}
  
function displayBingoCard(card, containerId) {
    const container =
        document.getElementById(containerId);
    container.innerHTML = '';
  
    for (let i = 0; i < ROWS; i++) {
        for (let j = 0; j < COLS; j++) {
            const cell =
                document.createElement('div');
            cell.textContent = card[i][j];
            if (card[i][j] === 'X') {
                cell.classList.add('marked');
            }
            container.appendChild(cell);
        }
    }
}
  
function markNumber(card, number) {
    for (let i = 0; i < ROWS; i++) {
        for (let j = 0; j < COLS; j++) {
            if (card[i][j] === number) {
                card[i][j] = 'X';
                return true;
            }
        }
    }
    return false;
}
  
  
function checkWin(card) {
  
    // Check rows and columns for a Bingo pattern
    for (let i = 0; i < ROWS; i++) {
        let rowFilled = true;
        let colFilled = true;
        for (let j = 0; j < COLS; j++) {
            if (card[i][j] !== 'X') {
                rowFilled = false;
            }
            if (card[j][i] !== 'X') {
                colFilled = false;
            }
        }
        if (rowFilled || colFilled) {
            return true;
        }
    }
  
    // Check diagonals for a Bingo pattern
    let diagonal1Filled = true;
    let diagonal2Filled = true;
    for (let i = 0; i < ROWS; i++) {
        if (card[i][i] !== 'X') {
            diagonal1Filled = false;
        }
        if (card[i][COLS - 1 - i] !== 'X') {
            diagonal2Filled = false;
        }
    }
    if (diagonal1Filled || diagonal2Filled) {
        return true;
    }
  
    return false;
}
  
document
    .getElementById('startButton')
    .addEventListener('click', () => {
        player1Card = createBingoCard();
        player2Card = createBingoCard();
        displayBingoCard(player1Card, 'player1Card');
        displayBingoCard(player2Card, 'player2Card');
        document
            .getElementById('markButton')
            .disabled = false;
        document
            .getElementById('startButton')
            .disabled = true;
        document
            .getElementById('resetButton')
            .disabled = false;
        document
            .getElementById('numberInput')
            .disabled = false;
        document
            .getElementById('turnDisplay')
            .textContent = 'Player 1\'s Turn';
    });
  
document
    .getElementById('resetButton')
    .addEventListener('click', () => {
        player1Card = createBingoCard();
        player2Card = createBingoCard();
        displayBingoCard(player1Card, 'player1Card');
        displayBingoCard(player2Card, 'player2Card');
        currentPlayer = 1;
        document
            .getElementById('numberInput')
            .value = '';
        document
            .getElementById('markButton')
            .disabled = false;
        document
            .getElementById('startButton')
            .disabled = true;
        document
            .getElementById('resetButton')
            .disabled = false;
        document
            .getElementById('numberInput')
            .disabled = false;
        document
            .getElementById('turnDisplay')
            .textContent = 'Player 1\'s Turn';
        document
            .getElementById('winDisplay')
            .textContent = ''; // Clear win message
    });
  
document.getElementById('markButton')
    .addEventListener('click', () => {
        const numberInput = document
            .getElementById('numberInput');
        const number = parseInt(numberInput.value);
  
        if (number >= 1 &&
            number <= MAX_NUM) {
            if (markNumber(player1Card, number) &&
                markNumber(player2Card, number)) {
                displayBingoCard(player1Card, 'player1Card');
                displayBingoCard(player2Card, 'player2Card');
  
                if (checkWin(player1Card)) {
                    document
                        .getElementById('winDisplay')
                        .textContent = 
                            '???? Player 1 has won the game! ????';
                    document
                        .getElementById('markButton')
                        .disabled = true;
                    document
                        .getElementById('numberInput')
                        .disabled = true;
                } else if (checkWin(player2Card)) {
                    document
                        .getElementById('winDisplay')
                        .textContent = 
                            '???? Player 2 has won the game! ????';
                    document
                        .getElementById('markButton')
                        .disabled = true;
                    document
                        .getElementById('numberInput')
                        .disabled = true;
                } else {
                    numberInput.value = '';
                    currentPlayer = 
                        currentPlayer === 1 ? 2 : 1;
                    document
                        .getElementById('turnDisplay')
                        .textContent =
                        `Player ${currentPlayer}'s Turn`;
                }
            } else {
                alert(
                    'Number already marked or not 
                     found on any player card.');
            }
        } else {
            alert('Please enter a valid 
                   number between 1 and 25.');
        }
    });


Steps to Start the Game:

  • Open the Web Page: Just like you’d open any website, you open the Bingo game in your web browser.
  • Start the Game: To begin, click the “Start” button. This gets the game going by giving both players their cards and enabling the “Mark” button.
  • Start Playing: Now you’re ready to play! You can start marking numbers on your card and try to get a Bingo.

Output:

bingogif



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads