【问题标题】:How to return .innerHTML of a 2 dimensional array?如何返回二维数组的 .innerHTML?
【发布时间】:2020-11-26 20:19:42
【问题描述】:

我是一名学生,我的任务是使用 JavaScript 开发一个井字游戏。我坚持的部分是读取正方形的 html 值。 X 和 O 作为参数 elem 传递给函数 determineWinner(elem)。如何检查所有 3 个方块是否与参数“elem”的内容匹配? 在我的 if 语句中,我尝试过使用winningPos[i][0].innerHTML 等。但它只读取索引而不是html 值。对此的任何帮助将不胜感激。

function determineWinner(elem) {

  var winningPos = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];

  var i, j;

  for (var i = 0; i < winningPos.length; i++) {
    for (var j = 0; j < winningPos[i].length; j++) {
      if (winningPos[i][0] == elem && winningPos[i][1] == elem && winningPos[i][2] == elem) {
        document.getElementById("status").innerHTML = "Game Over!";
        if (elem == "X") {
          document.getElementById("message").innerHTML = "User is the winner!!!";
        } else if (elem == "O") {
          document.getElementById("message").innerHTML = "Computer is the winner!!!";
        } else
          break;
      }
    }
  }
}
<div class="main">
  <div id="message">Welcome to the game of tic tac toe. Click on any cell to begin the game!</div>
  <div id="status">This is a new game</div>
  <button id="reset" onclick="resetGameBoard()">Reset Game</button>
  <div id="wrapper">
    <div id="1" class="row">
      <div id="0" class="col">
      </div>
      <div id="1" class="col">
      </div>
      <div id="2" class="col">
      </div>
    </div>
    <div id="2" class="row">
      <div id="3" class="col">
      </div>
      <div id="4" class="col">
      </div>
      <div id="5" class="col">
      </div>
    </div>
    <div id="3" class="row">
      <div id="6" class="col">
      </div>
      <div id="7" class="col">
      </div>
      <div id="8" class="col">
      </div>
    </div>
  </div>
</div>

【问题讨论】:

  • 我们还需要查看您的 HTML... 一个想法是让每个 HTML 节点代表一个正方形,该正方形具有 id 及其行和列,例如:&lt;div id='02' >` 将是第一行第三列的平方。我认为这将有助于解决您的问题
  • 很抱歉。我编辑了问题以包含 HTML。
  • 第一个大问题:你重复了ids(ids 1,2 和 3 重复),ids 必须是唯一的
  • 修复它之后,您需要从循环内的 div 中获取内容,例如:let content = document.getElementById(winningPos[i][j]).innerHTML 然后对照elem 检查内容...另外,您可能不会需要第二个循环,因为您像这样直接访问索引winningPos[i][2]
  • 同意@CalvinNunes,但我更绝对,找另一位导师,身份证的唯一性,即使是申请人现在也应该这样做!

标签: javascript innerhtml tic-tac-toe


【解决方案1】:

这是一个不错的 sn-p,它不是解决方案,但有助于正确启动。

花时间阅读和理解每个函数,完成获胜,然后制作一个循环的“startGame”函数,要求玩家玩,检查是否获胜,...

//Here is a createEmpyBoard function, can be helpful...

//You should have a readBoard that reads from HTML
function createEmptyBoard(lines, columns) {
  return Array(lines).fill().map( () => Array(columns).fill('') );
}

function set(board, x, y, player) {
  if(x >= board.length) throw `${x} is greather than board lines`;
  if(y >= board[x].length) throw `${y} is greather than board columns`;
  if( board[x][y] ) throw `There is already something in ${x},${y}`;
  board[x][y] = player;
}

function checkWinning(board, player) {
  return checkWinningHorizontal(board, player) || checkWinningVertical(board, player) || checkWinningVertical(board, player);
}

function checkWinningHorizontal(board, player) {
  for(let i=0; i<board.length; i++) {
    let lineSuccess = true;
    for(let j=0; j<board[i].length; j++) {
      if( board[i][j] !== player) {
        lineSuccess = false;
        break;
      }
    }
    if( lineSuccess ) return true;
  }
  return false;
}

function checkWinningVertical(board, player) {
  return false;
}

function checkWinningVertical(board, player) {
  return false;
}

function updateWithGame(board) {
   const el = document.getElementById('game');
   if(!el) throw 'Cannot find element id=game';
   
   let value = '';
   for(let i=0; i<board.length; i++) {
     let tr = '<tr>';
     for(let j=0; j<board[i].length; j++) {
       tr += '<td>' + (board[i][j] || '-' ) + '</td>'
     }
     tr += '</tr>';
     value += tr;
   }
   console.log(el);
   el.innerHTML = value;
}

function readFromHTML() {
   const el = document.getElementById('game');
   if(!el) throw 'Cannot find element id=game';
   
   const board = [];
   el.childNodes.forEach(tr => {
     let line = [];
     tr.childNodes.forEach( td => {
       line.push(td.innerHTML);
     });
     board.push(line);
   });
   
   return board;
}

const b = createEmptyBoard(3, 3);
set(b, 1, 0, 'X');
updateWithGame(b);
console.log( readFromHTML() );
console.log(checkWinning(b, 'X'));
<html>
<body>
<table>
<tbody id='game'>
</tbody>
</table>
</body>
</htmL>

【讨论】:

  • 抱歉你在我写的时候更新了,我错过了你的实际html..希望它仍然可以帮助
【解决方案2】:

我做了另一个答案,因为这个答案考虑了提供的 html。

我添加了一些 CSS 以使其易于阅读。 你必须自己编码hasWin:p

但是你可以用boards 变量来做吗,这将非常容易!

//Put this into a <script> just before </body>

const wrapper = document.getElementById('wrapper');
const status = document.getElementById('status');

let winner = null;
let currentUser = 'O';

function resetGameBoard() {
   status.innerHTML= 'This is a new game';
   winner = null;
   currentUser = 'X';
   for( let i = 0; i< wrapper.children.length; i++) {
     const row = wrapper.children[i];
     for( let j = 0; j< row.children.length; j++) {
       const col = row.children[j];
       col.innerHTML = '';
     }
   }
}

function readFullBoard() {
  let board = [];
  for( let i = 0; i< wrapper.children.length; i++) {
    const row = wrapper.children[i];
    const rowBoard = [];
    for( let j = 0; j< row.children.length; j++) {
      const col = row.children[j];
      rowBoard.push( col.innerHTML);
    }
    board.push(rowBoard);
  }
  return board;
}
function hasWin(user){
  let board = readFullBoard();
  //Here you have board you wanted, you can check for winner
  return true;
}

wrapper.addEventListener('click', function(event){
  //Do not play if there is a winner, need to reset
  
  if( winner) return;
  const col = event.target;
  const colId = col.id;
  const row = col.parentNode;
  const rowId = row.id;
  if( col.innerHTML.trim() !== '' ) {
    console.error('This case cannot be played', rowId, colId);
  } else {
    col.innerHTML = currentUser;
    if( hasWin(currentUser) ) {
      winner = currentUser;
      status.innerHTML= 'Player '+winner+' has win';
      return;
    }
    if ( currentUser === 'O' ) currentUser = 'X';
    else currentUser = 'O';
  }
});
.row {
  display: flex;
 }
 
 .col {
  width: 50px;
  height: 50px;
  border: 1px solid black;
 }
<div class="main">
  <div id="message">Welcome to the game of tic tac toe. Click on any cell to begin the game!</div>
  <div id="status">This is a new game</div>
  <button id="reset" onclick="resetGameBoard()">Reset Game</button>
  <div id="wrapper">
    <div id="1" class="row">
      <div id="0" class="col"></div>
      <div id="1" class="col"></div>
      <div id="2" class="col"></div>
    </div>
    <div id="2" class="row">
      <div id="3" class="col"></div>
      <div id="4" class="col"></div>
      <div id="5" class="col"></div>
    </div>
    <div id="3" class="row">
      <div id="6" class="col"></div>
      <div id="7" class="col"></div>
      <div id="8" class="col"></div>
    </div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2012-08-30
    • 2014-12-19
    • 2021-02-10
    相关资源
    最近更新 更多