基本的JavaScript问题,井字游戏问题

时间:2020-01-08 21:51:28

标签: javascript

我想知道你们是否可以帮助我解决我的问题。我有两个:

一个:是否可以使其更简洁? (请参阅下面的评论)

二:我很确定您必须在checkWin()函数中的井字游戏中做出所有可能的获胜组合,但是我不知道如何在不放入每个组合的情况下做到这一点在里面。参见下文, 注意,我正在使用code.org AppLab,大多数代码行都可以工作,有些可能行不通

var board = [];
var mode  = 0;
var turn  = 0;
var put;
var squareID;
var moveOn;
onEvent("playAloneBttn", "click", function() {
 setupGame();
 mode = 1;
});
//Is there a way to make this more efficient?
onEvent("slot1", "click", function() {
  squareID = 0;
 updateSquare(); 
});
onEvent("slot2", "click", function() {
  squareID = 1;
 updateSquare(); 
});
onEvent("slot3", "click", function() {
  squareID = 2;
 updateSquare(); 
});
onEvent("slot4", "click", function() {
  squareID = 3;
 updateSquare(); 
});
onEvent("slot5", "click", function() {
  squareID = 4;
 updateSquare(); 
});
onEvent("slot6", "click", function() {
  squareID = 5;
 updateSquare(); 
});
onEvent("slot7", "click", function() {
  squareID = 6;
 updateSquare(); 
});
onEvent("slot8", "click", function() {
  squareID = 7;
 updateSquare(); 
});
onEvent("slot9", "click", function() {
  squareID = 8;
 updateSquare(); 
});

function setupGame(){
  setScreen("game");
    turn = 1;
    board = [0,0,0,0,0,0,0,0,0];
}

function updateSquare(){
  if(turn == 1){put = 1} else {put = 2}
checkSquare();
if (moveOn == 1) 
{
  removeItem(board,squareID);
insertItem(board,squareID,put);
checkWin();
if (turn == 1){turn =2} else {turn = 1}
}
}
function checkSquare(){
  if (board[squareID]== 1 || board[squareID] == 2){
      moveOn = 0;
    }
    else {moveOn = 1}
}
function checkWin(){
///How do i do this?
}

2 个答案:

答案 0 :(得分:0)

在每个插槽上放置一个类,然后遍历插槽并创建onclick事件。

var slots = document.getElementsByClassName("slot");
for(var x = 0; x < slots.length; x++){
   slots[x].onClick = function() {
        squareID = x; // why set the id when its clicked? doesnt make sense. should have an id weather clicked or not.
        updateSquare(); 
   }
}

答案 1 :(得分:0)

下面是一个示例,说明如何实现事件委托以使代码更简单。您可以看到我们只需要应用一个事件处理程序即可跟踪所有按钮的单击,因为该处理程序属于父容器。

剩余的代码只是作为如何在click事件上更新特定方块的简单示例:

const handleClick = event => {
  if (event.target.tagName === 'TD') {
    const square = event.target;
    updateSquare(square);
  }
};

const updateSquare = square => {
  if (square.style.backgroundColor === 'red') {
    square.style.backgroundColor = 'transparent';
  } else {
    square.style.backgroundColor = 'red';
  }
};

document.querySelector('#container').addEventListener('click', handleClick);
td {
  padding: 10px;
  border-style: groove;
}
<div id="container">
  <table>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>7</td>
      <td>8</td>
      <td>9</td>
    </tr>
    <tr>
      <td></td>
      <td>0</td>
      <td></td>
    </tr>
  </table>
</div>