简体   繁体   English

重新初始化时,计数变量在javascript中不会重置

[英]Count variable does not reset in javascript when re-initialized

I've encountered an odd situation. 我遇到了一个奇怪的情况。 I'm building a nice little Tic-Tac-Toe game in JS, and I can't figure out why the count variable will not reset when I init() a second time. 我正在JS中构建一个漂亮的小Tic-Tac-Toe游戏,我无法弄清楚为什么count变量在我第二次init()时不会重置。

The first game works well; 第一场比赛运作良好; the second game count does not reset to 0 even though the var count resets in init(). 即使var count在init()中重置,第二个游戏计数也不会重置为0。

Game rules: game starts with X and should always start with X. You'll note that the second game starts with O. 游戏规则:游戏从X开始,应始终以X开头。你会注意到第二个游戏以O开头。

Would anyone care to take a look? 有人想看看吗? Fiddle: http://jsfiddle.net/1ommcdxg/ 小提琴: http//jsfiddle.net/1ommcdxg/

var board;
var gameBoard;
var winners = [ 
                [0,1,2],
                [3,4,5],
                [6,7,8],
                [0,3,6],
                [1,4,7],
                [2,5,8],
                [0,4,8],
                [2,4,6]
];
var count;

var checkWin = function (a) {

    for (var i = 0; i < winners.length; i++) {

        if (gameBoard[winners[i][0]] === a && 
            gameBoard[winners[i][1]] === a && 
            gameBoard[winners[i][2]] === a) 
        {
            return a;
        };

    };

};

var gamePlay = function (ev) {

    console.log(ev);

    ev = ev || window.event; // browser compatibility
    var target = ev.target || ev.srcElement; //browser c...
    var choice = target.id; //sets a variable from the id
    choice = parseInt(choice.substring(1,2));

    // console.log(target);
    // console.log(choice);

    console.log("in gameplay " + count);

    if (count < 9) {

        if (count % 2 === 0) {

            target.innerHTML = "X";
            target.className = target.className + " x";
            gameBoard[choice] = "x";
            if (checkWin(gameBoard[choice])) {
                alert("X wins!");
                init();
            };

        } else {
            target.innerHTML = "O";
            target.className = target.className + " o";
            gameBoard[choice] = "o";
            if (checkWin(gameBoard[choice])) {
                alert("O wins!");
                init();
            };
        };

    } else {
        console.log("no more turns!");
    };

    count++;

};

var init = function () {

    gameBoard = new Array();
    xPlayer = [];
    oPlayer = [];
    count = 0;

    board = document.getElementById("board");

    if (board.hasChildNodes()) {
        board.removeChild(board.firstChild);
    };

    var b = document.createElement("b");
    board.appendChild(b);

    for (var i = 0; i < 9; i++) {
        var el = document.createElement("div");
        el.className = "square";
        el.id = "t" + i;
        b.appendChild(el);
        console.log(el);
        el.addEventListener('click', gamePlay);
    };

    console.log(count);

};

init();

Felix Kling is right, it's because of the count++ at the end of gamePlay function, it's called after init(). Felix Kling是对的,这是因为gamePlay函数结束时的count ++,它是在init()之后调用的。

You may return from gamePlay function right after calling init(), to fix this issue. 您可以在调用init()后立即从gamePlay函数返回,以解决此问题。

 var board; var gameBoard; var winners = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]; var count; var checkWin = function (a) { for (var i = 0; i < winners.length; i++) { if (gameBoard[winners[i][0]] === a && gameBoard[winners[i][1]] === a && gameBoard[winners[i][2]] === a) { return a; }; }; }; var gamePlay = function (ev) { console.log(ev); ev = ev || window.event; // browser compatibility var target = ev.target || ev.srcElement; //browser c... var choice = target.id; //sets a variable from the id choice = parseInt(choice.substring(1,2)); // console.log(target); // console.log(choice); console.log("in gameplay " + count); if (count < 9) { if (count % 2 === 0) { target.innerHTML = "X"; target.className = target.className + " x"; gameBoard[choice] = "x"; if (checkWin(gameBoard[choice])) { alert("X wins!"); init(); return; }; } else { target.innerHTML = "O"; target.className = target.className + " o"; gameBoard[choice] = "o"; if (checkWin(gameBoard[choice])) { alert("O wins!"); init(); return; }; }; } else { console.log("no more turns!"); }; count++; }; var init = function () { gameBoard = new Array(); xPlayer = []; oPlayer = []; count = 0; board = document.getElementById("board"); if (board.hasChildNodes()) { board.removeChild(board.firstChild); }; var b = document.createElement("b"); board.appendChild(b); for (var i = 0; i < 9; i++) { var el = document.createElement("div"); el.className = "square"; el.id = "t" + i; b.appendChild(el); console.log(el); el.addEventListener('click', gamePlay); }; console.log(count); }; init(); 
 #board { width: 400px; } .square { width: 100px; height: 100px; border: 2px solid #333; margin: 2px; float: left; text-align: center; } .x { background-color: blue; color: white; } .o { background-color: red; color: white; } 
 <body> <h1>Tic Tac Toe</h1> <div id="board"></div> </body> 

I found 2 issues in your code: 我在您的代码中发现了2个问题:

  1. As you are not breaking your code execution once user wins( init() is being called) count++ will still execute 一旦用户获胜(正在调用init()您就不会破坏代码执行,而count ++仍将执行
  2. You need to remove the event listener once click event triggers or else your counter will still keep on increamenting but game will never finish 您需要在点击事件触发器后删除事件监听器,否则您的计数器仍会继续增加,但游戏永远不会完成

Try this snippet: 试试这个片段:

 var board; var gameBoard; var winners = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; var count; var checkWin = function(a) { for (var i = 0; i < winners.length; i++) { if (gameBoard[winners[i][0]] === a && gameBoard[winners[i][1]] === a && gameBoard[winners[i][2]] === a) { return a; } } }; var gamePlay = function(ev) { ev = ev || window.event; // browser compatibility var target = ev.target || ev.srcElement; //browser c... target.removeEventListener('click', gamePlay); var choice = target.id; //sets a variable from the id choice = parseInt(choice.substring(1, 2)); console.log("in gameplay " + count); if (count < 9) { if (count % 2 === 0) { target.innerHTML = "X"; target.className = target.className + " x"; gameBoard[choice] = "x"; if (checkWin(gameBoard[choice])) { alert("X wins!"); return init(); } } else { target.innerHTML = "O"; target.className = target.className + " o"; gameBoard[choice] = "o"; if (checkWin(gameBoard[choice])) { alert("O wins!"); return init(); } } } else { console.log("no more turns!"); } count++; }; var init = function() { gameBoard = []; xPlayer = []; oPlayer = []; count = 0; board = document.getElementById("board"); if (board.hasChildNodes()) { board.removeChild(board.firstChild); } var b = document.createElement("b"); board.appendChild(b); for (var i = 0; i < 9; i++) { var el = document.createElement("div"); el.className = "square"; el.id = "t" + i; b.appendChild(el); el.addEventListener('click', gamePlay); } console.log(count); }; init(); 
 #board { width: 400px; } .square { width: 100px; height: 100px; border: 2px solid #333; margin: 2px; float: left; text-align: center; } .x { background-color: blue; color: white; } .o { background-color: red; color: white; } 
 <h1>Tic Tac Toe</h1> <div id="board"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM