0 votes
104 views
by (98.9k points)
How to build a Snake & ladder game purely in HTML , CSS & JS ?

1 Answer

0 votes
by (98.9k points)
 
Best answer

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
     .player {
            font-size: 24px;
            position: absolute;
            padding:20px;
        }

 

        #player1 {
            top: 0;
            left: 0;
        }

        #player2 {
            top: 0;
            left: 0;
        }
        /* CSS styles */
        .game-board {
            display: grid;
            grid-template-columns: repeat(10, 50px);
            grid-gap: 5px; 
        }

        .cell {
            width: 50px;
            height: 50px;
            border: 1px solid #000;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            transition: background-color 0.5s ease;
        }

        .snake {
            background-color: #ff5733;
        }

        .ladder {
            background-color: #28a745;
        }

        .current-position {
            background-color: yellow;
        }

        .player {
            font-size: 24px;
        }

        #dice {
            font-size: 32px;
            margin-top: 20px;
            animation: rollDice 1s;
        }

        @keyframes rollDice {
            0% {
                transform: rotate(0deg);
            }
            25% {
                transform: rotate(90deg);
            }
            50% {
                transform: rotate(180deg);
            }
            75% {
                transform: rotate(270deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }
    </style>
    <title>Snake & Ladder Game</title>
</head>
<body>
    <div class="game-board">
        <!-- Game cells will be dynamically generated here -->
    </div>
    <button id="roll-dice">Player 1: Roll Dice</button>
    <div id="result">Player 1 is at square 1, Player 2 is at square 1</div>
    <div id="dice" class="hidden"></div>
    <div id="player1" class="player"></div>
    <div id="player2" class="player"></div>
    <script>
        // JavaScript code
        const boardSize = 100;
        const snakeAndLadders = {
            16: 6,
            47: 26,
            49: 11,
            56: 53,
            62: 19,
            64: 60,
            87: 24,
            93: 73,
            95: 75,
            98: 78,
        };

        let currentPlayer = 1;
        let player1Position = 1;
        let player2Position = 1;

        function rollDice() {
            const diceRoll = Math.floor(Math.random() * 6) + 1;
            document.getElementById("dice").textContent = ` ${diceRoll}`;
            return diceRoll;
        }

        function movePlayer(steps, player) {
            const startPosition = player === 1 ? player1Position : player2Position;
            const endPosition = startPosition + steps;

            let currentPosition = startPosition;
            const interval = setInterval(() => {
                currentPosition++;
                if (currentPosition > endPosition) {
                    clearInterval(interval);
                    if (snakeAndLadders[currentPosition]) {
                        currentPosition = snakeAndLadders[currentPosition];
                    }
                    player === 1 ? (player1Position = currentPosition) : (player2Position = currentPosition);
                    currentPlayer = currentPlayer === 1 ? 2 : 1;
                }
                updatePlayerPosition(player, currentPosition);
            }, 500);
        }

        function updatePlayerPosition(player, position) {
            const playerElement = document.getElementById(`player${player}`);
            const cell = document.querySelector(`.cell:nth-child(${position})`);
            const cellRect = cell.getBoundingClientRect();
            playerElement.style.top = `${cellRect.top}px`;
            playerElement.style.left = `${cellRect.left}px`;
        }

        function updateUI() {
            const resultElement = document.getElementById("result");
            resultElement.textContent = `Player 1 is at square ${player1Position}, Player 2 is at square ${player2Position}`;
            document.getElementById("roll-dice").textContent = `Player ${currentPlayer}: Roll Dice`;
        }

        document.getElementById("roll-dice").addEventListener("click", function () {
            const diceRoll = rollDice();
            movePlayer(diceRoll, currentPlayer);
            updateUI();
        });

        // Create the game board dynamically (same as before)
        const gameBoard = document.querySelector(".game-board");

        for (let i = 1; i <= boardSize; i++) {
            const cell = document.createElement("div");
            cell.className = "cell";
            cell.textContent = i;

            if (snakeAndLadders[i]) {
                if (snakeAndLadders[i] > i) {
                    cell.className += " ladder";
                    cell.textContent = ""; // Ladder emoji
                } else {
                    cell.className += " snake";
                    cell.textContent = ""; // Snake emoji
                }
            }

            gameBoard.appendChild(cell);
        }
        
        function updatePlayerPosition(player, position) {
            const playerElement = document.getElementById(`player${player}`);
            const cell = document.querySelector(`.cell:nth-child(${position})`);
            const cellRect = cell.getBoundingClientRect();
            playerElement.style.top = `${cellRect.top}px`;
            playerElement.style.left = `${cellRect.left}px`;
        }
    </script>
</body>
</html>

Related questions

0 votes
1 answer 134 views
asked Aug 27, 2022 in Discuss by Doubtly (98.9k points)
0 votes
1 answer 108 views
asked Aug 19, 2022 in HTML by codelikepro (3.5k points)
0 votes
1 answer 122 views
asked Jun 24, 2023 in HTML by Doubtly (98.9k points)
0 votes
1 answer 91 views
asked Aug 19, 2022 in HTML by codelikepro (3.5k points)
0 votes
1 answer 85 views
0 votes
1 answer 93 views
asked Jun 12, 2023 in HTML by radhe (2.2k points)

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

537 users

...