[英]Returning in correct value on a true/false statement
I am meant to be getting "Player X Won!" 我注定会获得“玩家X胜利!” but it keeps returning "Player O Won!", even though I switch turns after each player move.
但即使我在每个玩家移动后切换回合,它仍会继续返回“ Player O Won!”。 My tests keep failing as a result.
结果我的测试一直失败。 I've tried to switch turns just before showWinner() and also in checkWinner() but nothing seems to change the result
我试图在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
}
};
Maybe remove this.switchTurn();
也许删除
this.switchTurn();
line in showWinner
function ? showWinner
函数中的行?
I would also put showWinner()
call before switchTurn()
in playerMove
我还要把
showWinner()
之前调用switchTurn()
中playerMove
EDIT: I just noticed, your conditions in checkWinner
are all wrong. 编辑:我刚刚注意到,您在
checkWinner
中的条件都是错误的。 You are comparing a string with a boolean. 您正在将字符串与布尔值进行比较。 You need to compare the grid content with
this.currentPlayer()
. 您需要将网格内容与
this.currentPlayer()
进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.