Javascript Tic Tac Toe - 检查玩家是否赢了总是返回false

时间:2017-07-21 01:55:08

标签: javascript

尝试构建一个JS tic-tac-toe游戏。我以前在python中成功完成了这个,但是使用类似的逻辑我似乎无法使checkWin函数正确返回玩家是否赢了。

这是代码

var Game = function(){
let board = [0,1,2,3,4,5,6,7,8], turnCounter;

this.checkWin = function(){ // seems to be an issue with this check win function
    if (
        board[0] == board[1] == board[2] ||
        board[0] == board[3] == board[6] ||
        board[3] == board[4] == board[5] ||
        board[1] == board[4] == board[7] ||
        board[6] == board[7] == board[8] ||
        board[2] == board[5] == board[8] ||
        board[0] == board[4] == board[8] ||
        board[2] == board[4] == board[6]){
        return true;
    } else {
        return false;
    }
};

电路板阵列代表3x3网格,左上角0,右下角8。它会根据用户选择更新为X或O.

感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

正如Tiny Giant所说,你正在短信你的if语句!

board[0] == board[1] == board[2]等同于查看board[0]board[1]的值是否相同,然后查看该布尔值是否为true / false)相当于board[2]

的值

这是一个可能会更好的翻译。

(board[0] == board[1] && board[1] == board[2]) ||
(board[0] == board[3] && board[3] == board[6]) ||
(board[3] == board[4] && board[4] == board[5]) ||
(board[1] == board[4] && board[4] == board[7]) ||
(board[6] == board[7] && board[7] == board[8]) ||
(board[2] == board[5] && board[5] == board[8]) ||
(board[0] == board[4] && board[4] == board[8]) ||
(board[2] == board[4] && board[4] == board[6])

基本上,我只是重复了中间的一个:a == bb == c然后是a == c,相当于a == b == c。公平警告:这是未经测试的代码,我只是调整它以便它不会短路。