首页 > 解决方案 > 在 React 中创建数独

问题描述

我创建了一个由 js 函数生成的数独,我尝试用 react 来展示它,但我不知道为什么这不起作用。

我尝试创建 81 个正方形,它们在输入中具有 id 和值、值,当我在其中输入一个数字时,它将执行函数 comprobar 并将其背景设置为读取或白色(如果正确)。

import React, { Component } from "react";
    import ReactDOM from "react-dom";
    import "./index.css";

    /*Se genera el diseño */
    var fallo;

    // Array que contendra las posiciones que se mostrarán
    var array = new Array(9);

    // Array de 9x9 que contiene la solucion. generada
    for (var z = 0; z < 9; z++) {
      array[z] = new Array(9);
    }

    function rellenarCuad(n, m) {
      // Método que recibe el punto de comienzo del cuadrado
      var x = n * 3;
      var z = m * 3;
      var arrN = [1, 2, 3, 4, 5, 6, 7, 8, 9];

      /* En este método se procede a rellenar el cuadrado 3x3 cumpliendo que no se repita en el mismo, en la fila y en la columna */
      for (var i = x; i < 3 + x; i++) {
        for (var j = z; j < 3 + z; j++) {
          var arrayaux = new Array(9);

          for (var zn = 0; zn < 9; zn++) arrayaux[zn] = array[zn][j];

          var pr = true;
          var intentos = 0;

          do {
            do {
              var nm = Math.floor(Math.random() * 9, 0);
            } while (arrN[nm] == 0);

            if (
              array[i].indexOf(arrN[nm]) === -1 &&
              arrayaux.indexOf(arrN[nm]) === -1
            ) {
              array[i][j] = arrN[nm];
              arrN[nm] = 0;
              pr = false;
            }

            if (intentos > 50) {
              // Si rebasa 50 intentos doy por hecho que no tiene solucion

              fallo = true;
              return;
            }

            intentos++;
          } while (pr);
        }
      }
    }

    // Método que genera el sodoku. Es recursivo, si no se halla una solución se llama a si mismo hasta encontrarla
    function generarSodoku() {
      // Método que simplemente llamar a rellenarCuad por cada cuadrado 3x3, es decir, le llama 9 veces
      for (var i = 0; i < 3; i++) {
        for (var y = 0; y < 3; y++) {
          rellenarCuad(y, i);
          if (fallo) {
            //  Si el seguro se activa, regenera el array y se llama asi mismo para repetir el proceso.

            fallo = false;
            array = null;
            array = new Array(9);

            for (z = 0; z < 9; z++) array[z] = new Array(9);

            generarSodoku();
            return;
          }
        }
      }
    }

    // Función que genera el numero de posiciones a ocultar según la eleción del usuario
    function umbral() {
      var nm = 80;
      var arrayM = new Array(nm);

      for (var l = 0; l < nm; l++) {
        var alpha = true;
        while (alpha) {
          var num = Math.floor(Math.random() * 81) + 1;
          if (arrayM.indexOf(num) !== -1) {
          } else {
            arrayM[l] = num;
            alpha = false;
          }
        }
      }
    }

    generarSodoku();

    console.log(array);

    var valoresVacios = [0];

    function generarAleatorios() {
        for (let i = 1; i < 5; i++) {
            do {
                var numAlea = Math.floor(Math.random() * 80);

            } while (!valoresVacios.indexOf(valoresVacios[i]));
            valoresVacios[i] = numAlea;
        }
    }

    generarAleatorios();

    function comprobar(value, i) {
      if (valoresVacios.indexOf(i)) {
        var valor = Math.floor(i / 9);
        var segundo = (i / 9).toFixed(1);
        segundo = (segundo - valor) * 10;
        if (array[valor][segundo] !== value) {
          document.getElementById(i).style.backgroundColor = "red";
        } else {
          document.getElementById(i).style.backgroundColor = "white";
        }
      }
    } 


    function Square(props) {
        return (
          <input className="square" type="text" onkeypress={comprobar(this.value, this.id)} />
        );
      }

      class Board extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            squares: Array(81),
          };
        }

        comprobar(value, i) {
            if (valoresVacios.indexOf(i)) {
              var valor = Math.floor(i / 9);
              var segundo = (i / 9).toFixed(1);
              segundo = (segundo - valor) * 10;
              if (array[valor][segundo] !== value) {
                document.getElementById(i).style.backgroundColor = "red";
              } else {
                document.getElementById(i).style.backgroundColor = "white";
              }
            }
          } 

        renderSquare(a, i) {
            if (valoresVacios.indexOf(i)) {
              return <Square value={0} id={i} onkeypress={() => this.comprobar(a, i)}/>;
            } else {
              return <Square value={a} id={i} disabled onkeypress={() => this.comprobar(a, i)}/>;
            }
          }

        render() {
          /*const winner = calculateWinner(this.state.squares);
          let status;
          if (winner) {
            status = 'Winner: ' + winner;
          }*/

          return (
            <div>
                <div className="status">{}</div>
                <div className="board-row">
                {this.renderSquare(array[0][0], 0)}
                {this.renderSquare(array[0][1], 1)}
                {this.renderSquare(array[0][2], 2)}
                {this.renderSquare(array[0][3], 3)}
                {this.renderSquare(array[0][4], 4)}
                {this.renderSquare(array[0][5], 5)}
                {this.renderSquare(array[0][6], 6)}
                {this.renderSquare(array[0][7], 7)}
                {this.renderSquare(array[0][8], 8)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[1][0], 9)}
                {this.renderSquare(array[1][1], 10)}
                {this.renderSquare(array[1][2], 11)}
                {this.renderSquare(array[1][3], 12)}
                {this.renderSquare(array[1][4], 13)}
                {this.renderSquare(array[1][5], 14)}
                {this.renderSquare(array[1][6], 15)}
                {this.renderSquare(array[1][7], 16)}
                {this.renderSquare(array[1][8], 17)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[2][0], 18)}
                {this.renderSquare(array[2][1], 19)}
                {this.renderSquare(array[2][2], 20)}
                {this.renderSquare(array[2][3], 21)}
                {this.renderSquare(array[2][4], 22)}
                {this.renderSquare(array[2][5], 23)}
                {this.renderSquare(array[2][6], 24)}
                {this.renderSquare(array[2][7], 25)}
                {this.renderSquare(array[2][8], 26)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[3][0], 27)}
                {this.renderSquare(array[3][1], 28)}
                {this.renderSquare(array[3][2], 29)}
                {this.renderSquare(array[3][3], 30)}
                {this.renderSquare(array[3][4], 31)}
                {this.renderSquare(array[3][5], 32)}
                {this.renderSquare(array[3][6], 33)}
                {this.renderSquare(array[3][7], 34)}
                {this.renderSquare(array[3][8], 35)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[4][0], 36)}
                {this.renderSquare(array[4][1], 37)}
                {this.renderSquare(array[4][2], 38)}
                {this.renderSquare(array[4][3], 39)}
                {this.renderSquare(array[4][4], 40)}
                {this.renderSquare(array[4][5], 41)}
                {this.renderSquare(array[4][6], 42)}
                {this.renderSquare(array[4][7], 43)}
                {this.renderSquare(array[4][8], 44)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[5][0], 45)}
                {this.renderSquare(array[5][1], 46)}
                {this.renderSquare(array[5][2], 47)}
                {this.renderSquare(array[5][3], 48)}
                {this.renderSquare(array[5][4], 49)}
                {this.renderSquare(array[5][5], 50)}
                {this.renderSquare(array[5][6], 51)}
                {this.renderSquare(array[5][7], 52)}
                {this.renderSquare(array[5][8], 53)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[6][0], 54)}
                {this.renderSquare(array[6][1], 55)}
                {this.renderSquare(array[6][2], 56)}
                {this.renderSquare(array[6][3], 57)}
                {this.renderSquare(array[6][4], 58)}
                {this.renderSquare(array[6][5], 59)}
                {this.renderSquare(array[6][6], 60)}
                {this.renderSquare(array[6][7], 61)}
                {this.renderSquare(array[6][8], 62)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[7][0], 63)}
                {this.renderSquare(array[7][1], 64)}
                {this.renderSquare(array[7][2], 65)}
                {this.renderSquare(array[7][3], 66)}
                {this.renderSquare(array[7][4], 67)}
                {this.renderSquare(array[7][5], 68)}
                {this.renderSquare(array[7][6], 69)}
                {this.renderSquare(array[7][7], 70)}
                {this.renderSquare(array[7][8], 71)}
                </div>
                <div className="board-row">
                {this.renderSquare(array[8][0], 72)}
                {this.renderSquare(array[8][1], 73)}
                {this.renderSquare(array[8][2], 74)}
                {this.renderSquare(array[8][3], 75)}
                {this.renderSquare(array[8][4], 76)}
                {this.renderSquare(array[8][5], 77)}
                {this.renderSquare(array[8][6], 78)}
                {this.renderSquare(array[8][7], 79)}
                {this.renderSquare(array[8][8], 80)}
                </div>
            </div>
          );
        }
      }

      class Game extends React.Component {
        render() {
          return (
            <div className="game">
              <div className="game-board">
                <Board />
              </div>
              <div className="game-info">
                <div>{/* status */}</div>
                <ol>{/* TODO */}</ol>
              </div>
            </div>
          );
        }
      }

      // ========================================

      ReactDOM.render(
        <Game />,
        document.getElementById('root')
      );

标签: javascriptreactjs

解决方案


嗨,您使用了错误的 onKeyPress 事件处理程序,它应该接收对函数的引用,而不是以这种方式执行函数:

 function Square(props) {
    const handleKeyPress = (e) => {
       comprobar(props.value, props.id) 
    }
        return (
          <input className="square" type="text" onkeypress={handleKeyPress} />
        );
      }

使用 Square 组件时也不需要传递 onkeypress:

renderSquare(a, i) {
            if (valoresVacios.indexOf(i)) {
              return <Square value={0} id={i} />;
            } else {
              return <Square value={a} id={i} disabled />;
            }
          }

推荐阅读