在工厂函数中更新变量

时间:2020-07-22 06:53:30

标签: javascript variables factory

我有一个工厂函数来创建游戏板,当我实例化游戏板时,我会在其中创建一个数组(private fun setDoubleClick() { var numOfClicks = 0 [View].setOnClickListener { numOfClicks++ if (numOfClicks == 2) { //onDoubleClick numOfClicks = 0 } else { Handler().postDelayed({ numOfClicks = 0 }, 2000/*Set this according to desired doubleclick speed*/ ) } } } )以创建网格的坐标。然后由于游戏流程的原因,我需要更新该网格以跟踪用户单击它的位置。但是网格永远不会更新,因此我无法跟踪用户的运动。如何管理该变量let grid

编辑:

当我第一次填充网格时,我会更新网格,但是当我触发事件监听器时,我会在实例化时创建一个空网格。我的工厂功能是:

grid

这是我的事件监听器:

export const Gameboard = () => {

  let grid = [];//create grid when instantiate gameboard()
  let index = 0;
  for (let i = 65; i < 75; i++) {
    for (let j = 1; j < 11; j++) {
      const gridItem = {
        index,
        coordinates: String.fromCharCode(i) + j,
        hitStatus: false,
        shipName: null,
        shipIndex: null,
      };
      grid.push(gridItem);
      index++;
    }
  }

  const receiveAttack = (index) => {
    const gridCell = grid.find((value) => value.index === parseInt(index));
    if (gridCell.hitStatus === false) {
      gridCell.hitStatus = true;
      if (gridCell.shipName !== null) {
        const shipHit = ships.find((ship) => gridCell.shipName === ship.getName());
        shipHit.hit(gridCell.shipIndex);
        updateGrid(gridCell.index);//update grid
        return 'you hit a ship';
      }
      updateGrid(gridCell.index);//update grid
      return 'Water!';
    }
    return 'Cell already bombed!';
  };
const updateGrid = (index,shipName, shipIndex) => {
    grid[index].hitStatus = true;
  };
  const getGrid = () => grid;

  return {
    placeShip, receiveAttack, getGrid, getShips, allShipsSunk, missedShots, hitShots, updateGrid, updateGrid2, 
  };
};

这是我的游戏流程:

function createCompBoard(gameboard) {
    const computerSide = document.getElementById('computerSide');
    computerSide.innerHTML = '';
    let i=0;
    let grid = document.createElement('table');
    let grid2 = gameboard.getGrid();// every time user make an attack I get the grid and display it
    grid.className = 'grid';
    for (let r=0;r<10;++r){
        let tr = grid.appendChild(document.createElement('tr'));
        for (let c=0;c<10;++c){
            let cell = tr.appendChild(document.createElement('td'));
            cell.id = i;            
            ++i;
            cell.addEventListener('click', game().getPeg.bind(this, cell.id));
        }
    }    
    computerSide.appendChild(grid);
    return grid;
  }

0 个答案:

没有答案