有趣的if / else if条件链问题

时间:2019-01-11 15:00:36

标签: javascript if-statement conditional

我很难弄清楚为什么这段代码按原样工作。下面,我拥有所有制作井字游戏的代码。该游戏将按预期工作,直到我们达到'O''X'的胜利为止。我当前的逻辑有时会按预期工作并选择正确的获胜者,但是在大多数情况下,即使最后一个平方的最后移动会导致获胜,也会产生'DRAW'。考虑到if/else if链,我不知道它如何工作?适用的if/else if语句是第二组。

这是我的代码:

$(document).ready(function() {
    let addX = "<h1>X</h1>"
    let addO = "<h1>O</h1>"
    let turn = []
    let board = [$("#one"), $("#two"), $("#three"), $("#four"), $("#five"),$("#six"), $("#seven"), $("#eight"), $("#nine")]
    let combos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2]]
    for (let i = 0; i < board.length; i++){
        board[i].click(function(){
            if (turn.length === 0){
                turn.push(board.indexOf(board[i].html(addX)) + "X")
            } else if (turn.length % 2 !== 0 && board[i].html() === ''){
                turn.push(board.indexOf(board[i].html(addO)) + "O")
            } else if (turn.length % 2 === 0 && board[i].html() === ''){
                turn.push(board.indexOf(board[i].html(addX)) + "X")
            }
            for(let i = 0; i < combos.length; i++){
                if (turn.includes(combos[i][0] + 'O') && turn.includes(combos[i][1] + 'O') && turn.includes(combos[i][2] + 'O') ){
                    alert('O IS WINNER!')
                    setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
                    turn.length = 0
                } else if(turn.includes(combos[i][0] + 'X') && turn.includes(combos[i][1] + 'X') && turn.includes(combos[i][2] + 'X') ){
                    alert('X IS WINNER!')
                    setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
                    turn.length = 0
                    break
                } else if (turn.length === 9){
                    alert('DRAW!')
                    setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
                    turn.length = 0
                }
            }
        })
    }
});

下面是一个代码笔,用于测试游戏本身:

https://codepen.io/tylerp33/pen/NeOxyY

基本上,游戏不应该看到有获胜组合:

else if(turn.join("").includes(combos[i][0] + 'X') && turn.join("").includes(combos[i][1] + 'X') && turn.join("").includes(combos[i][2] + 'X') 

在最后一个

之前

else if (turn.length === 9)产生“草稿”?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

无需更改或进行大量重构,就将其添加到最后一个有效的条件中。基本上,在决定平局之前让if / else贯穿所有连击就可以了。感谢您的所有帮助!

 else if (turn.length === 9 && combos[i] === combos[combos.length - 1]) {
                    alert('DRAW!')
                    setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
                    turn.length = 0
                }