在正确/错误语句上返回正确的值

时间:2019-01-20 19:25:34

标签: javascript

我注定会获得“玩家X胜利!”但即使我在每个玩家移动后切换回合,它仍会继续返回“ Player O Won!”。结果我的测试一直失败。我试图在showWinner()之前和checkWinner()中切换转弯,但似乎没有任何改变

function Game() {
  this.current_player = "X";
  this.grid = [[null, null, null], [null, null, null], [null, null, null]];
  this.move_counter = 0;
}

Game.prototype.currentPlayer = function() {
  return this.current_player;
};

Game.prototype.switchTurn = function() {
  if (this.currentPlayer() === "X") {
    this.current_player = "O";
  } else if (this.currentPlayer() === "O") {
    this.current_player = "X";
  }
};

Game.prototype.showGrid = function() {
  return this.grid;
};

Game.prototype.playerMove = function(row, column) {
  this.grid[row][column] = this.currentPlayer();
  this.move_counter++;
  this.switchTurn();
  this.showWinner();
};

Game.prototype.moveCounter = function() {
  return this.move_counter;
};

Game.prototype.checkWinner = function() {
  for(var i = 0; i < this.grid.length; i++) {
    if (this.grid[i][0] != null && this.grid[i][0] === (this.grid[i][1] && this.grid[i][2])) {
      return true
    } else if (this.grid[0][i] != null && this.grid[0][i] === (this.grid[1][i] && this.grid[2][i])) {
      return true
    } else if (this.grid[0][0] != null && this.grid[0][0] === (this.grid[1][1] && this.grid[2][2])) {
      return true
    } else if (this.grid[2][0] != null && this.grid[2][0] === (this.grid[1][1] && this.grid[0][2])) {
      return true
    } else {
      return false
    }
  }
};

Game.prototype.showWinner = function() {
  if (this.checkWinner() === true) {
    this.switchTurn();
    return "Player " + this.current_player + " Won!";
  }
};

Game.prototype.checkDraw = function() {
  if (this.moveCounter() === 9) {
    return "It's a draw!"
  } else {
    return null
  }
};

1 个答案:

答案 0 :(得分:0)

也许要删除this.switchTurn();函数中的showWinner行?

我也将showWinner()中的switchTurn()之前的playerMove呼叫

编辑: 我刚刚注意到,您在checkWinner中的条件都是错误的。您正在将字符串与布尔值进行比较。您需要将网格内容与this.currentPlayer()进行比较。