井字游戏重置

时间:2020-07-02 19:47:54

标签: javascript css twitter-bootstrap reset

如何在不创建其他板的情况下重置井字游戏板?这是代码示例:

function makeBoard(boardElement) {
  let player1 = 0
  let gameIsRunning = true;
  let xPlayer = true;

  for (let i = 0; i < 3; i++) {
    var rowElement = document.createElement("div");
    rowElement.className = "row";
    if (!boardArray[i]) {
      boardArray[i] = [];
    }
  }
}
<div>
  <div>
    <div class="col-8">
      <button onclick="makeBoard(board)" id="resetButton" class="btn btn-primary btn-lg">Reset Game</button>
    </div>
    <div class="col-4"></div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以使用以下方法重置所有单元格的文本内容:

cells.forEach(cell => {
  cell.textContent = ''
})

演示

class TotTacToe {
  constructor(target, size) {
    if (typeof target === 'string') {
      target = document.querySelector(target)
    }
    this.players = [ 'O', 'X' ]
    this.currentPlayer = 0
    this.reference = target
    this.size = size
    this.initialize()
  }
  
  initialize() {
    for (let row = 0; row < this.size; row++) {
      let rowEl = document.createElement('DIV')
      rowEl.classList.add('row')
      for (let col = 0; col < this.size; col++) {
        let cell = document.createElement('DIV')
        cell.classList.add('col-sm')
        cell.addEventListener('click', e => {
          this.click(e.target)
        })
        rowEl.appendChild(cell)
      }
      this.reference.appendChild(rowEl)
    }
    
    document.querySelector('.reset').addEventListener('click', e => {
      this.reset()
    })
  }
  
  click(cell) {
    if (cell.textContent == '') {
      cell.textContent = this.players[this.currentPlayer]
      this.currentPlayer = (this.currentPlayer + 1) % this.players.length
    }
  }
  
  reset() {
    [...this.reference.querySelectorAll('.col-sm')].forEach(col => {
      col.textContent = ''
    })
    this.currentPlayer = 0
  }
}

new TotTacToe('.container', 3)
.container {
  width: 200px !important;
}

.container .row > .col,
.container .row > [class^=col-] {
  padding-top: 1rem;
  padding-bottom: 1rem;
  background-color: LightGrey;
  border: thin solid Grey;
  text-align: center;
  cursor: pointer;
  min-height: 4em;
}

.reset {
  position: fixed !important;
  top: 1em;
  right: 2em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap-grid.min.css" rel="stylesheet"/>
<div class="container"></div>
<div>
  <button type="button" class="btn btn-primary reset">Reset</button>
</div>