<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2048 Game by @hannes_swe</title>
    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #faf8ef;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .game-container {
            text-align: center;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(4, 100px);
            grid-template-rows: repeat(4, 100px);
            gap: 10px;
            background-color: #bbada0;
            padding: 10px;
            border-radius: 10px;
        }

        .tile {
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 5px;
            font-size: 2rem;
            color: white;
            transition: transform 0.3s ease; /* Animation for movement */
            width: 100%; /* Set the width to match the grid */
            height: 100%; /* Set the height to match the grid */
            position: relative; /* Positioning for the sliding effect */
        }

        .tile-2 { background-color: #eee4da; color: #776e65; }
        .tile-4 { background-color: #ede0c8; color: #776e65; }
        .tile-8 { background-color: #f2b179; }
        .tile-16 { background-color: #f59563; }
        .tile-32 { background-color: #f67c5f; }
        .tile-64 { background-color: #f67c5f; }
        .tile-128 { background-color: #edcf72; }
        .tile-256 { background-color: #edcc61; }
        .tile-512 { background-color: #edc850; }
        .tile-1024 { background-color: #edc53f; }
        .tile-2048 { background-color: #edc22e; }

        button {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 1rem;
            border: none;
            border-radius: 5px;
            background-color: #4caf50;
            color: white;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        #score {
            margin-top: 20px;
            font-size: 1.5rem;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>2048 Game</h1>
        <div class="grid" id="grid">
            <!-- Tiles will be dynamically added here -->
        </div>
        <button id="restart">Restart</button>
        <p id="score">Score: 0</p>
    </div>
    <script>
        const gridElement = document.getElementById("grid");
        const restartButton = document.getElementById("restart");
        const scoreElement = document.getElementById("score");
        let score = 0;

        let grid = [
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0]
        ];

        // Initialize game
        function init() {
            score = 0;
            scoreElement.innerText = `Score: ${score}`;
            grid = [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ];
            addRandomTile();
            addRandomTile();
            updateTiles();
        }

        // Add a random tile (2 or 4)
        function addRandomTile() {
            const emptyTiles = [];
            grid.forEach((row, rowIndex) => {
                row.forEach((value, colIndex) => {
                    if (value === 0) emptyTiles.push({ row: rowIndex, col: colIndex });
                });
            });
            if (emptyTiles.length > 0) {
                const randomTile = emptyTiles[Math.floor(Math.random() * emptyTiles.length)];
                grid[randomTile.row][randomTile.col] = Math.random() < 0.9 ? 2 : 4;
            }
        }

        // Update the tile UI
        function updateTiles() {
            gridElement.innerHTML = '';
            grid.forEach((row, rowIndex) => {
                row.forEach((value, colIndex) => {
                    const tile = document.createElement("div");
                    tile.className = `tile tile-${value || 0}`;
                    tile.innerText = value !== 0 ? value : '';
                    tile.dataset.position = `${rowIndex},${colIndex}`;
                    gridElement.appendChild(tile);
                });
            });
            scoreElement.innerText = `Score: ${score}`;
        }

        // Move tiles based on direction
        function move(direction) {
            let moved = false;

            const slideAndCombine = (arr) => {
                const newArr = arr.filter(val => val !== 0);
                const combinedArr = [];
                for (let i = 0; i < newArr.length; i++) {
                    if (newArr[i] === newArr[i + 1]) {
                        combinedArr.push(newArr[i] * 2);
                        score += newArr[i] * 2;  // Update score
                        i++; // Skip the next tile
                    } else {
                        combinedArr.push(newArr[i]);
                    }
                }
                while (combinedArr.length < 4) {
                    combinedArr.push(0);
                }
                return combinedArr;
            };

            // Move based on direction
            if (direction === 'left') {
                for (let row = 0; row < 4; row++) {
                    const newRow = slideAndCombine(grid[row]);
                    if (newRow.toString() !== grid[row].toString()) {
                        moved = true;
                    }
                    grid[row] = newRow;
                }
            } else if (direction === 'right') {
                for (let row = 0; row < 4; row++) {
                    const newRow = slideAndCombine(grid[row].reverse()).reverse();
                    if (newRow.toString() !== grid[row].toString()) {
                        moved = true;
                    }
                    grid[row] = newRow;
                }
            } else if (direction === 'up') {
                for (let col = 0; col < 4; col++) {
                    const tempCol = grid.map(row => row[col]);
                    const newCol = slideAndCombine(tempCol);
                    for (let row = 0; row < 4; row++) {
                        grid[row][col] = newCol[row];
                    }
                    if (newCol.toString() !== tempCol.toString()) {
                        moved = true;
                    }
                }
            } else if (direction === 'down') {
                for (let col = 0; col < 4; col++) {
                    const tempCol = grid.map(row => row[col]);
                    const newCol = slideAndCombine(tempCol.reverse()).reverse();
                    for (let row = 0; row < 4; row++) {
                        grid[row][col] = newCol[row];
                    }
                    if (newCol.toString() !== tempCol.toString()) {
                        moved = true;
                    }
                }
            }

            // Add a new tile if moved
            if (moved) {
                addRandomTile();
                updateTiles();
            }
        }

        // Event listeners for key presses
        document.addEventListener('keydown', (event) => {
            switch (event.key) {
                case 'ArrowLeft':
                    move('left');
                    break;
                case 'ArrowRight':
                    move('right');
                    break;
                case 'ArrowUp':
                    move('up');
                    break;
                case 'ArrowDown':
                    move('down');
                    break;
            }
        });

        // Restart game
        restartButton.addEventListener('click', init);

        // Initialize the game on load
        init();
    </script>
</body>
</html>
