AI生成之4*4数独小游戏

看到百度首页增加了 AI编程 的功能,遂试用下,让 文心快码 生成了一个4*4数独小游戏。页面自动引入了 tailwind css,布局样式都不错,除了一点样式不符合要求手动修改外,没有太大问题。

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>4x4数独生成器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
      @media print {
        .no-print {
          display: none !important;
        }
      }
      .sudoku-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        border: 2px solid #334155;
      }
      .sudoku-cell {
        aspect-ratio: 1/1;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        background-color: white;
        border: 1px solid #cbd5e1;
      }
      .sudoku-cell-bg {
        background-color: #f1f5f9;
      }

      .sudoku-cell:nth-child(2),
      .sudoku-cell:nth-child(6),
      .sudoku-cell:nth-child(10),
      .sudoku-cell:nth-child(14) {
        border-right: 2px solid #334155;
      }
      .sudoku-cell:nth-child(5),
      .sudoku-cell:nth-child(6),
      .sudoku-cell:nth-child(7),
      .sudoku-cell:nth-child(8) {
        border-bottom: 2px solid #334155;
      }
    </style>
  </head>
  <body class="bg-slate-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
      <header class="mb-8 no-print">
        <h1 class="text-3xl font-bold text-center text-slate-800">4×4数独生成器</h1>
        <div class="flex justify-center mt-6 gap-4">
          <div class="flex items-center gap-2">
            <label for="difficulty" class="font-medium">难度:</label>
            <select id="difficulty" class="px-3 py-2 border rounded-md">
              <option value="easy">简单</option>
              <option value="medium">中等</option>
              <option value="hard">困难</option>
            </select>
          </div>
          <button id="generate" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition"><i class="fas fa-sync-alt mr-2"></i>生成数独</button>
          <button id="print" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition"><i class="fas fa-print mr-2"></i>打印</button>
        </div>
      </header>

      <main>
        <div id="sudoku-container" class="grid grid-cols-4 gap-6"></div>
      </main>
    </div>

    <script>
      document.addEventListener("DOMContentLoaded", () => {
        const container = document.getElementById("sudoku-container");
        const generateBtn = document.getElementById("generate");
        const printBtn = document.getElementById("print");
        const difficultySelect = document.getElementById("difficulty");

        // 生成数独
        generateBtn.addEventListener("click", generateSudokus);
        printBtn.addEventListener("click", () => window.print());

        // 初始生成
        generateSudokus();

        function generateSudokus() {
          container.innerHTML = "";
          const difficulty = difficultySelect.value;

          for (let i = 0; i < 12; i++) {
            const sudoku = generateSudoku(difficulty);
            const sudokuElement = createSudokuElement(sudoku, i + 1);
            container.appendChild(sudokuElement);
          }
        }

        function generateSudoku(difficulty) {
          // 生成完整数独
          const grid = Array(4)
            .fill()
            .map(() => Array(4).fill(0));
          fillGrid(grid);

          // 根据难度移除数字
          const cellsToRemove = difficulty === "easy" ? 4 : difficulty === "medium" ? 6 : 8;

          const puzzle = JSON.parse(JSON.stringify(grid));
          removeNumbers(puzzle, cellsToRemove);

          return {
            solution: grid,
            puzzle: puzzle,
          };
        }

        function fillGrid(grid, row = 0, col = 0) {
          if (row === 4) return true;
          if (col === 4) return fillGrid(grid, row + 1, 0);
          if (grid[row][col] !== 0) return fillGrid(grid, row, col + 1);

          const nums = [1, 2, 3, 4];
          shuffleArray(nums);

          for (const num of nums) {
            if (isValid(grid, row, col, num)) {
              grid[row][col] = num;
              if (fillGrid(grid, row, col + 1)) return true;
              grid[row][col] = 0;
            }
          }
          return false;
        }

        function isValid(grid, row, col, num) {
          // 检查行
          if (grid[row].includes(num)) return false;

          // 检查列
          for (let i = 0; i < 4; i++) {
            if (grid[i][col] === num) return false;
          }

          // 检查2x2宫
          const boxRow = Math.floor(row / 2) * 2;
          const boxCol = Math.floor(col / 2) * 2;

          for (let i = 0; i < 2; i++) {
            for (let j = 0; j < 2; j++) {
              if (grid[boxRow + i][boxCol + j] === num) return false;
            }
          }

          return true;
        }

        function removeNumbers(grid, count) {
          let removed = 0;
          while (removed < count) {
            const row = Math.floor(Math.random() * 4);
            const col = Math.floor(Math.random() * 4);
            if (grid[row][col] !== 0) {
              grid[row][col] = 0;
              removed++;
            }
          }
        }

        function shuffleArray(array) {
          for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
          }
        }

        function createSudokuElement(sudoku, index) {
          const element = document.createElement("div");
          element.className = "sudoku-page bg-white p-4 rounded-lg shadow-md";

          const grid = document.createElement("div");
          grid.className = "sudoku-grid mx-auto";
          grid.style.width = "160px";

          for (let i = 0; i < 4; i++) {
            for (let j = 0; j < 4; j++) {
              const cell = document.createElement("div");
              if (sudoku.puzzle[i][j] === 0) {
                cell.className = "sudoku-cell";
                cell.textContent = "";
              } else {
                cell.className = "sudoku-cell sudoku-cell-bg";
                cell.textContent = sudoku.puzzle[i][j];
              }

              grid.appendChild(cell);
            }
          }

          element.appendChild(grid);
          return element;
        }
      });
    </script>
  </body>
</html>

页面显示如下:
image

posted @ 2025-09-04 10:22  carol2014  阅读(9)  评论(0)    收藏  举报