• +34 685 967 885
  • +34 695 898 191
  • antgarprats@gmail.com
  • Antonio García Prats

juegos clásicos para el móvil

Juegos clásicos con HTML CSS y Javascript

Los dispositivos móviles han evolucionado significativamente desde sus inicios, pero algunos juegos clásicos han quedado grabados en la memoria de los usuarios. En este artículo, exploraremos cinco juegos icónicos que hicieron historia en los antiguos teléfonos móviles y aprenderemos cómo recrearlos usando HTML, CSS y JavaScript. ¡Prepárate para un viaje nostálgico y técnico!.

Introducción al origen de los juegos en los primeros teléfonos móviles

El desarrollo de juegos para teléfonos móviles tiene sus raíces en los años 90, cuando los dispositivos portátiles comenzaron a ganar popularidad. Aunque hoy en día los juegos móviles cuentan con gráficos avanzados y experiencias inmersivas, sus inicios fueron mucho más modestos, marcados por limitaciones tecnológicas que fomentaron la creatividad de los desarrolladores.

El pionero indiscutible en este campo fue «Snake», un juego simple pero adictivo que debutó en 1997 en los teléfonos Nokia. Creado por Taneli Armanto, un ingeniero de software finlandés, «Snake» fue preinstalado en el modelo Nokia 6110 y se convirtió rápidamente en un fenómeno global. Su mecánica era sencilla: los jugadores controlaban una serpiente que debía comer puntos mientras crecía, evitando chocar contra las paredes o su propio cuerpo.

Lo que hizo de «Snake» un hito fue su accesibilidad y el hecho de que aprovechaba al máximo las capacidades limitadas de los dispositivos de la época. El juego no solo demostró que los teléfonos móviles podían ser herramientas de entretenimiento, sino que también estableció un estándar para el diseño de juegos móviles: simplicidad, jugabilidad directa y alto grado de rejugabilidad.

El éxito de «Snake» abrió el camino para que otros desarrolladores exploraran las posibilidades de los juegos en dispositivos móviles, dando lugar a una industria que hoy mueve miles de millones de dólares y abarca una variedad infinita de géneros y plataformas.

Una recopilación de los principales juegos clásicos con HTML CSS y Javascript

1. Snake

Origen: El juego Snake se popularizó con los teléfonos Nokia 6110 en 1997, aunque su concepto se remonta a la década de 1970.

Cómo jugar: Controla una serpiente que crece al comer puntos en la pantalla. El objetivo es evitar chocar contigo mismo o con los bordes.

Enlace de descarga: Puedes descargarte el fichero desde mi perfil de github: snake.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake Game</title>
    <style>
      body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background: linear-gradient(135deg, #1d1d1d, #333333);
    color: #fff;
    }

    .game-container {
        text-align: center;
        background-color: #222;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
    }

    canvas {
        background-color: #111;
        border: 2px solid #fff;
        display: block;
        margin: 0 auto;
    }

    .controls {
        margin-top: 20px;
    }

    button {
        background-color: #28a745;
        border: none;
        color: white;
        padding: 10px 20px;
        text-transform: uppercase;
        font-size: 16px;
        border-radius: 5px;
        cursor: pointer;
        transition: background 0.3s;
    }

    button:hover {
        background-color: #218838;
    }

    #score {
        margin-top: 10px;
        font-size: 18px;
    }
    </style>

</head>
<body>
    <div class="game-container">
        <h1>Snake Game</h1>
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <div class="controls">
            <button id="startButton">Start Game</button>
            <p id="score">Score: 0</p>
        </div>
    </div>

    <script>
      const canvas = document.getElementById('gameCanvas');
      const ctx = canvas.getContext('2d');
      const startButton = document.getElementById('startButton');
      const scoreElement = document.getElementById('score');

      const tileSize = 20;
      const canvasSize = 400;
      const tileCount = canvasSize / tileSize;

      let snake = [{ x: 10, y: 10 }];
      let direction = { x: 0, y: 0 };
      let food = { x: 5, y: 5 };
      let score = 0;
      let gameInterval;

      function drawTile(x, y, color) {
          ctx.fillStyle = color;
          ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);
      }

      function drawSnake() {
          snake.forEach(segment => drawTile(segment.x, segment.y, '#28a745'));
      }

      function drawFood() {
          drawTile(food.x, food.y, '#dc3545');
      }

      function moveSnake() {
          const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
          snake.unshift(head);

          if (head.x === food.x && head.y === food.y) {
              score++;
              scoreElement.textContent = `Score: ${score}`;
              placeFood();
          } else {
              snake.pop();
          }

          if (head.x < 0 || head.y < 0 || head.x >= tileCount || head.y >= tileCount || checkCollision(head)) {
              clearInterval(gameInterval);
              alert('Game Over!');
          }
      }

      function placeFood() {
          food.x = Math.floor(Math.random() * tileCount);
          food.y = Math.floor(Math.random() * tileCount);
      }

      function checkCollision(head) {
          return snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y);
      }

      function updateGame() {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          drawSnake();
          drawFood();
          moveSnake();
      }

      function startGame() {
          snake = [{ x: 10, y: 10 }];
          direction = { x: 0, y: 0 };
          food = { x: 5, y: 5 };
          score = 0;
          scoreElement.textContent = `Score: ${score}`;
          clearInterval(gameInterval);
          gameInterval = setInterval(updateGame, 150);
      }

      window.addEventListener('keydown', e => {
          switch (e.key) {
              case 'ArrowUp':
                  if (direction.y === 0) direction = { x: 0, y: -1 };
                  break;
              case 'ArrowDown':
                  if (direction.y === 0) direction = { x: 0, y: 1 };
                  break;
              case 'ArrowLeft':
                  if (direction.x === 0) direction = { x: -1, y: 0 };
                  break;
              case 'ArrowRight':
                  if (direction.x === 0) direction = { x: 1, y: 0 };
                  break;
          }
      });

      startButton.addEventListener('click', startGame);
    </script>
</body>
</html>

2. Tetris

Origen: Este icónico juego de puzzles fue creado por Alexey Pajitnov en 1984 y se popularizó en Game Boy antes de llegar a dispositivos móviles.

Cómo jugar: El objetivo principal de Tetris es encajar bloques o piezas geométricas llamadas «tetriminos» en un área de juego rectangular para completar filas horizontales. Una vez que una fila está completamente llena, desaparece, y el jugador gana puntos. El juego termina cuando los tetriminos se acumulan hasta la parte superior del área de juego y ya no hay espacio para nuevas piezas.

Enlace de descarga: Puedes descargarte el fichero desde mi perfil de github: tetris.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tetris Game</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background: #111;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }

    .container {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    canvas {
      background: #333;
      border: 2px solid #fff;
      display: block;
      margin-bottom: 20px;
    }

    .info {
      display: flex;
      justify-content: space-between;
      width: 300px;
    }

    .button {
      background: #444;
      color: #fff;
      border: none;
      padding: 10px 20px;
      cursor: pointer;
      font-size: 16px;
    }

    .button:hover {
      background: #555;
    }
  </style>
</head>
<body>
  <div class="container">
    <canvas id="tetris" width="300" height="600"></canvas>
    <div class="info">
      <button class="button" id="start">Start</button>
      <span id="score">Score: 0</span>
    </div>
  </div>

  <script>
    const canvas = document.getElementById('tetris');
    const context = canvas.getContext('2d');
    context.scale(30, 30);

    const ROWS = 20;
    const COLS = 10;

    let arena = createMatrix(COLS, ROWS);
    let player = {
      pos: {x: 0, y: 0},
      matrix: null,
      score: 0
    };

    const colors = [
      null,
      '#FF0D72',
      '#0DC2FF',
      '#0DFF72',
      '#F538FF',
      '#FF8E0D',
      '#FFE138',
      '#3877FF'
    ];

    const pieces = 'ILJOTSZ';

    function createMatrix(width, height) {
      const matrix = [];
      while (height--) {
        matrix.push(new Array(width).fill(0));
      }
      return matrix;
    }

    function createPiece(type) {
      switch (type) {
        case 'T':
          return [
            [0, 0, 0],
            [1, 1, 1],
            [0, 1, 0]
          ];
        case 'O':
          return [
            [2, 2],
            [2, 2]
          ];
        case 'L':
          return [
            [0, 3, 0],
            [0, 3, 0],
            [0, 3, 3]
          ];
        case 'J':
          return [
            [0, 4, 0],
            [0, 4, 0],
            [4, 4, 0]
          ];
        case 'I':
          return [
            [0, 5, 0, 0],
            [0, 5, 0, 0],
            [0, 5, 0, 0],
            [0, 5, 0, 0]
          ];
        case 'S':
          return [
            [0, 6, 6],
            [6, 6, 0],
            [0, 0, 0]
          ];
        case 'Z':
          return [
            [7, 7, 0],
            [0, 7, 7],
            [0, 0, 0]
          ];
      }
    }

    function collide(arena, player) {
      const [m, o] = [player.matrix, player.pos];
      for (let y = 0; y < m.length; ++y) {
        for (let x = 0; x < m[y].length; ++x) {
          if (m[y][x] !== 0 &&
              (arena[y + o.y] && arena[y + o.y][x + o.x]) !== 0) {
            return true;
          }
        }
      }
      return false;
    }

    function merge(arena, player) {
      player.matrix.forEach((row, y) => {
        row.forEach((value, x) => {
          if (value !== 0) {
            arena[y + player.pos.y][x + player.pos.x] = value;
          }
        });
      });
    }

    function rotate(matrix, dir) {
      for (let y = 0; y < matrix.length; ++y) {
        for (let x = 0; x < y; ++x) {
          [matrix[x][y], matrix[y][x]] = [matrix[y][x], matrix[x][y]];
        }
      }
      if (dir > 0) {
        matrix.forEach(row => row.reverse());
      } else {
        matrix.reverse();
      }
    }

    function playerDrop() {
      player.pos.y++;
      if (collide(arena, player)) {
        player.pos.y--;
        merge(arena, player);
        playerReset();
        arenaSweep();
        updateScore();
      }
      dropCounter = 0;
    }

    function playerMove(offset) {
      player.pos.x += offset;
      if (collide(arena, player)) {
        player.pos.x -= offset;
      }
    }

    function playerReset() {
      player.matrix = createPiece(pieces[pieces.length * Math.random() | 0]);
      player.pos.y = 0;
      player.pos.x = (arena[0].length / 2 | 0) - (player.matrix[0].length / 2 | 0);
      if (collide(arena, player)) {
        arena.forEach(row => row.fill(0));
        player.score = 0;
        updateScore();
      }
    }

    function arenaSweep() {
      outer: for (let y = arena.length - 1; y >= 0; --y) {
        for (let x = 0; x < arena[y].length; ++x) {
          if (arena[y][x] === 0) {
            continue outer;
          }
        }
        const row = arena.splice(y, 1)[0].fill(0);
        arena.unshift(row);
        ++player.score;
      }
    }

    function drawMatrix(matrix, offset) {
      matrix.forEach((row, y) => {
        row.forEach((value, x) => {
          if (value !== 0) {
            context.fillStyle = colors[value];
            context.fillRect(x + offset.x, y + offset.y, 1, 1);
          }
        });
      });
    }

    function draw() {
      context.fillStyle = '#000';
      context.fillRect(0, 0, canvas.width, canvas.height);

      drawMatrix(arena, {x: 0, y: 0});
      drawMatrix(player.matrix, player.pos);
    }

    let dropCounter = 0;
    let dropInterval = 1000;
    let lastTime = 0;

    function update(time = 0) {
      const deltaTime = time - lastTime;
      lastTime = time;

      dropCounter += deltaTime;
      if (dropCounter > dropInterval) {
        playerDrop();
      }

      draw();
      requestAnimationFrame(update);
    }

    function updateScore() {
      document.getElementById('score').innerText = `Score: ${player.score}`;
    }

    document.addEventListener('keydown', event => {
      if (event.key === 'ArrowLeft') {
        playerMove(-1);
      } else if (event.key === 'ArrowRight') {
        playerMove(1);
      } else if (event.key === 'ArrowDown') {
        playerDrop();
      } else if (event.key === 'ArrowUp') {
        rotate(player.matrix, 1);
        if (collide(arena, player)) {
          rotate(player.matrix, -1);
        }
      }
    });

    document.getElementById('start').addEventListener('click', () => {
      playerReset();
      updateScore();
      update();
    });
  </script>
</body>
</html>

3. Space Invaders

Origen: Lanzado en 1978 por Taito, Space Invaders llegó a los teléfonos móviles en los 2000.

Cómo jugar: En Space Invaders, el jugador controla una nave espacial que se mueve lateralmente a lo largo de la parte inferior de la pantalla, disparando proyectiles hacia formaciones de alienígenas que se desplazan de lado a lado y descienden lentamente. El objetivo principal es eliminar a todos los alienígenas antes de que lleguen al nivel inferior de la pantalla o de que destruyan la nave del jugador. Los alienígenas aumentan su velocidad a medida que son eliminados, elevando la dificultad del juego. El jugador también debe evitar o destruir los disparos que lanzan los alienígenas. Hay obstáculos, representados por estructuras que se degradan con los disparos propios y los de los enemigos. A lo largo del juego, pueden aparecer naves especiales en la parte superior que otorgan puntos adicionales al ser destruidas. El objetivo final es alcanzar la puntuación más alta posible y sobrevivir el mayor tiempo.

Enlace de descarga: Puedes descargarte el fichero desde mi perfil de github: space invaders.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Space Invaders</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background: linear-gradient(to bottom, #000, #1a1a2e);
            font-family: Arial, sans-serif;
        }

        #gameCanvas {
            display: block;
            margin: 0 auto;
            border: 2px solid #fff;
            background-color: #000;
        }

        .info-bar {
            color: #fff;
            text-align: center;
            padding: 10px;
            font-size: 18px;
        }

        .info-bar span {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="info-bar">
        Score: <span id="score">0</span>
    </div>
    <canvas id="gameCanvas" width="800" height="600"></canvas>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            const canvas = document.getElementById("gameCanvas");
            const ctx = canvas.getContext("2d");

            const player = {
                x: canvas.width / 2 - 20,
                y: canvas.height - 60,
                width: 40,
                height: 40,
                speed: 7,
                color: "#0f0",
                bullets: []
            };

            const aliens = [];
            const bullets = player.bullets;
            const alienRows = 4;
            const alienColumns = 10;
            const alienWidth = 40;
            const alienHeight = 30;
            const alienPadding = 10;
            const alienOffsetTop = 30;
            const alienOffsetLeft = 30;
            let alienDirection = 1;
            let score = 0;

            function createAliens() {
                for (let row = 0; row < alienRows; row++) {
                    for (let col = 0; col < alienColumns; col++) {
                        aliens.push({
                            x: alienOffsetLeft + col * (alienWidth + alienPadding),
                            y: alienOffsetTop + row * (alienHeight + alienPadding),
                            width: alienWidth,
                            height: alienHeight,
                            color: "#f00",
                            alive: true
                        });
                    }
                }
            }

            function drawPlayer() {
                ctx.fillStyle = player.color;
                ctx.fillRect(player.x, player.y, player.width, player.height);
            }

            function drawAliens() {
                aliens.forEach(alien => {
                    if (alien.alive) {
                        ctx.fillStyle = alien.color;
                        ctx.fillRect(alien.x, alien.y, alien.width, alien.height);
                    }
                });
            }

            function drawBullets() {
                bullets.forEach(bullet => {
                    ctx.fillStyle = "#fff";
                    ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
                });
            }

            function moveAliens() {
                let edgeReached = false;

                aliens.forEach(alien => {
                    if (alien.alive) {
                        alien.x += alienDirection * 2;
                        if (alien.x + alien.width >= canvas.width || alien.x <= 0) {
                            edgeReached = true;
                        }
                    }
                });

                if (edgeReached) {
                    alienDirection *= -1;
                    aliens.forEach(alien => alien.y += 10);
                }
            }

            function updateBullets() {
                bullets.forEach((bullet, index) => {
                    bullet.y -= 5;
                    if (bullet.y + bullet.height < 0) {
                        bullets.splice(index, 1);
                    }
                });
            }

            function checkCollisions() {
                bullets.forEach((bullet, bulletIndex) => {
                    aliens.forEach((alien, alienIndex) => {
                        if (
                            alien.alive &&
                            bullet.x < alien.x + alien.width &&
                            bullet.x + bullet.width > alien.x &&
                            bullet.y < alien.y + alien.height &&
                            bullet.y + bullet.height > alien.y
                        ) {
                            alien.alive = false;
                            bullets.splice(bulletIndex, 1);
                            score += 10;
                            $("#score").text(score);
                        }
                    });
                });
            }

            function gameLoop() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);

                drawPlayer();
                drawAliens();
                drawBullets();
                moveAliens();
                updateBullets();
                checkCollisions();

                requestAnimationFrame(gameLoop);
            }

            $(document).on("keydown", function (e) {
                if (e.key === "ArrowLeft" && player.x > 0) {
                    player.x -= player.speed;
                } else if (e.key === "ArrowRight" && player.x < canvas.width - player.width) {
                    player.x += player.speed;
                } else if (e.key === " ") {
                    player.bullets.push({
                        x: player.x + player.width / 2 - 2.5,
                        y: player.y,
                        width: 5,
                        height: 10
                    });
                }
            });

            createAliens();
            gameLoop();
        });
    </script>
</body>
</html>

4. Pong

Origen: Uno de los primeros videojuegos, creado por Atari en 1972, adaptado a teléfonos Nokia y otros modelos.

Cómo jugar: El objetivo es mover una pala (o barra) para golpear la pelota y evitar que pase por tu lado. Si logras que la pelota pase por el lado del oponente, ganas un punto. En nuestro caso, las teclas de w y s para controlar un jugador y flecha arriba/abajo para el segundo jugador.

Enlace de descarga: Puedes descargarte el fichero desde mi perfil de github: pong.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pong Game</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #000;
            overflow: hidden;
        }

        canvas {
            border: 2px solid #fff;
            background-color: #111;
        }
    </style>
</head>
<body>
    <canvas id="pongCanvas" width="800" height="400"></canvas>
    <script>
        const canvas = document.getElementById("pongCanvas");
        const ctx = canvas.getContext("2d");

        // Game settings
        const paddleWidth = 10;
        const paddleHeight = 100;
        const ballRadius = 8;

        // Paddle positions
        const player1 = { x: 0, y: canvas.height / 2 - paddleHeight / 2, score: 0 };
        const player2 = { x: canvas.width - paddleWidth, y: canvas.height / 2 - paddleHeight / 2, score: 0 };

        // Ball position and velocity
        let ball = {
            x: canvas.width / 2,
            y: canvas.height / 2,
            dx: 4 * (Math.random() > 0.5 ? 1 : -1),
            dy: 4 * (Math.random() > 0.5 ? 1 : -1),
        };

        // Key state
        const keys = {};

        // Event listeners for key presses
        window.addEventListener("keydown", (e) => (keys[e.key] = true));
        window.addEventListener("keyup", (e) => (keys[e.key] = false));

        function drawPaddle(x, y) {
            ctx.fillStyle = "#fff";
            ctx.fillRect(x, y, paddleWidth, paddleHeight);
        }

        function drawBall() {
            ctx.beginPath();
            ctx.arc(ball.x, ball.y, ballRadius, 0, Math.PI * 2);
            ctx.fillStyle = "#fff";
            ctx.fill();
            ctx.closePath();
        }

        function drawScore() {
            ctx.font = "20px Arial";
            ctx.fillStyle = "#fff";
            ctx.fillText(player1.score, canvas.width / 4, 20);
            ctx.fillText(player2.score, (3 * canvas.width) / 4, 20);
        }

        function movePaddles() {
            if (keys["w"] && player1.y > 0) player1.y -= 6;
            if (keys["s"] && player1.y < canvas.height - paddleHeight) player1.y += 6;

            if (keys["ArrowUp"] && player2.y > 0) player2.y -= 6;
            if (keys["ArrowDown"] && player2.y < canvas.height - paddleHeight) player2.y += 6;
        }

        function updateBall() {
            ball.x += ball.dx;
            ball.y += ball.dy;

            // Ball collision with top and bottom walls
            if (ball.y - ballRadius < 0 || ball.y + ballRadius > canvas.height) {
                ball.dy *= -1;
            }

            // Ball collision with paddles
            if (
                ball.x - ballRadius < player1.x + paddleWidth &&
                ball.y > player1.y &&
                ball.y < player1.y + paddleHeight
            ) {
                ball.dx *= -1;
                ball.x = player1.x + paddleWidth + ballRadius;
            }

            if (
                ball.x + ballRadius > player2.x &&
                ball.y > player2.y &&
                ball.y < player2.y + paddleHeight
            ) {
                ball.dx *= -1;
                ball.x = player2.x - ballRadius;
            }

            // Ball out of bounds
            if (ball.x - ballRadius < 0) {
                player2.score++;
                resetBall();
            }

            if (ball.x + ballRadius > canvas.width) {
                player1.score++;
                resetBall();
            }
        }

        function resetBall() {
            ball.x = canvas.width / 2;
            ball.y = canvas.height / 2;
            ball.dx = 4 * (Math.random() > 0.5 ? 1 : -1);
            ball.dy = 4 * (Math.random() > 0.5 ? 1 : -1);
        }

        function gameLoop() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            drawPaddle(player1.x, player1.y);
            drawPaddle(player2.x, player2.y);
            drawBall();
            drawScore();

            movePaddles();
            updateBall();

            requestAnimationFrame(gameLoop);
        }

        gameLoop();
    </script>
</body>
</html> 

5. Sudoku

Origen: Aunque no es un videojuego en sí, Sudoku se popularizó en dispositivos como Palm Pilots y primeros smartphones.

Cómo jugar: El Sudoku es un juego de lógica y razonamiento cuyo objetivo es completar una cuadrícula de 9×9 celdas dividiéndola en 9 subcuadrículas de 3×3, de manera que cada fila, columna y subcuadrícula contenga los números del 1 al 9 sin repetir ninguno. Al inicio del juego, algunas celdas están pre-rellenadas con números, proporcionando pistas que el jugador debe utilizar para deducir el resto. No se pueden repetir números en las filas, columnas ni en los bloques 3×3, lo que convierte al Sudoku en un desafío de eliminación y deducción lógica. El objetivo principal es llenar correctamente toda la cuadrícula siguiendo estas reglas, asegurando que cada número se utilice exactamente una vez por fila, columna y subcuadrícula. Aunque no requiere cálculos matemáticos, sí exige concentración, paciencia y estrategia para resolver cada desafío. El juego se adapta a diferentes niveles de dificultad según la cantidad y posición de los números iniciales.

Enlace de descarga: Puedes descargarte el fichero desde mi perfil de github: sudoku.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sudoku Game</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f9;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }

    #sudoku-container {
      display: grid;
      grid-template-columns: repeat(9, 1fr);
      grid-gap: 1px;
      background-color: #333;
      width: 360px;
      height: 360px;
    }

    .cell {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #fff;
      font-size: 18px;
      font-weight: bold;
      border: 1px solid #ccc;
    }

    .cell input {
      width: 100%;
      height: 100%;
      text-align: center;
      border: none;
      font-size: 18px;
      font-weight: bold;
      background: none;
    }

    .cell input:focus {
      outline: 2px solid #007BFF;
    }

    .fixed {
      background-color: #ddd;
    }

    #controls {
      margin-top: 20px;
      text-align: center;
    }

    button {
      padding: 10px 20px;
      font-size: 16px;
      margin: 5px;
      cursor: pointer;
      background-color: #007BFF;
      color: #fff;
      border: none;
      border-radius: 5px;
    }

    button:hover {
      background-color: #0056b3;
    }
  </style>
</head>
<body>
  <div>
    <div id="sudoku-container"></div>
    <div id="controls">
      <button onclick="checkSolution()">Check Solution</button>
      <button onclick="resetBoard()">Reset</button>
    </div>
  </div>

  <script>
    const sudokuContainer = document.getElementById("sudoku-container");

    const initialBoard = [
      [5, 3, 0, 0, 7, 0, 0, 0, 0],
      [6, 0, 0, 1, 9, 5, 0, 0, 0],
      [0, 9, 8, 0, 0, 0, 0, 6, 0],
      [8, 0, 0, 0, 6, 0, 0, 0, 3],
      [4, 0, 0, 8, 0, 3, 0, 0, 1],
      [7, 0, 0, 0, 2, 0, 0, 0, 6],
      [0, 6, 0, 0, 0, 0, 2, 8, 0],
      [0, 0, 0, 4, 1, 9, 0, 0, 5],
      [0, 0, 0, 0, 8, 0, 0, 7, 9]
    ];

    const solution = [
      [5, 3, 4, 6, 7, 8, 9, 1, 2],
      [6, 7, 2, 1, 9, 5, 3, 4, 8],
      [1, 9, 8, 3, 4, 2, 5, 6, 7],
      [8, 5, 9, 7, 6, 1, 4, 2, 3],
      [4, 2, 6, 8, 5, 3, 7, 9, 1],
      [7, 1, 3, 9, 2, 4, 8, 5, 6],
      [9, 6, 1, 5, 3, 7, 2, 8, 4],
      [2, 8, 7, 4, 1, 9, 6, 3, 5],
      [3, 4, 5, 2, 8, 6, 1, 7, 9]
    ];

    function createBoard() {
      sudokuContainer.innerHTML = "";
      for (let row = 0; row < 9; row++) {
        for (let col = 0; col < 9; col++) {
          const cell = document.createElement("div");
          cell.classList.add("cell");
          if (initialBoard[row][col] !== 0) {
            cell.textContent = initialBoard[row][col];
            cell.classList.add("fixed");
          } else {
            const input = document.createElement("input");
            input.type = "number";
            input.min = 1;
            input.max = 9;
            cell.appendChild(input);
          }
          sudokuContainer.appendChild(cell);
        }
      }
    }

    function checkSolution() {
      const cells = sudokuContainer.querySelectorAll(".cell");
      let isCorrect = true;
      cells.forEach((cell, index) => {
        const row = Math.floor(index / 9);
        const col = index % 9;
        const value = cell.textContent || cell.querySelector("input").value;
        if (parseInt(value) !== solution[row][col]) {
          isCorrect = false;
        }
      });

      if (isCorrect) {
        alert("Congratulations! You solved the puzzle!");
      } else {
        alert("Some cells are incorrect. Keep trying!");
      }
    }

    function resetBoard() {
      createBoard();
    }

    createBoard();
  </script>
</body>
</html>

Estos juegos clásicos marcaron un antes y un después en el entretenimiento móvil. Con el código proporcionado, puedes experimentar la nostalgia mientras practicas tus habilidades de programación. ¡Espero que te diviertas creando y jugando!.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *