代码之家  ›  专栏  ›  技术社区  ›  Colton Van Bastelaere

无法重置布尔值-Javascript

  •  0
  • Colton Van Bastelaere  · 技术社区  · 5 年前

    我再次问另一个问题,关于我正在为学校开发的Simon游戏的一些代码。 我有一个布尔值设置为false,游戏首先检查按键,然后设置为true如果用户得到了错误的游戏序列,那么应该将该值重置回false出于某种原因,我的代码没有在需要时前后更改布尔值,我也不知道为什么。

    /*************VARIABLES*************/
    //store colors
    var buttonColors = [
        "green", //0
        "red", //1
        "yellow", //2
        "blue" //3
    ]
    //Game Pattern Storage
    var gamePattern = [ /*Added From nextSequence*/ ];
    var userClicks = [ /* Added from userClickHistory*/ ];
    
    var level = 0;
    var gameOn = false;
    
    /******************BASIC FUNCTIONS*********************/
    
    /*AWAIT KEYPRESS TO BEGIN GAME*/
    $(document).keypress(function () {
        if (!gameOn) {
            nextSequence();
            $(`#level-title`).text(`Level: ` + level);
            var gameOn = true;
        }
    });
    
    //log user clicks after nextSequence() has executed, check the userClicks vs gamePattern using checkAnswer(lastInArray)
    $(`.btn`).click(function () {
        var buttonClicked = $(this).attr(`id`);
        userClicks.push(buttonClicked);
        animate(buttonClicked);
        playSound(buttonClicked);
    
        checkAnswer(userClicks.length - 1);
    });
    
    
    function checkAnswer(usersLastClick) {
        //if the gamePatterns last call is equal to the users last click
        if (gamePattern[usersLastClick] === userClicks[usersLastClick]) {
            console.log("success");
            //if the userClicks and the gamePatterns lengths are equal, call nextSequence()
            if (userClicks.length === gamePattern.length) {
                setTimeout(function () {
                    nextSequence();
                    //update the titles level indicator
                    $(`#level-title`).text(`Level: ` + level);
                }, 1000);
            }
        } else {
            $(`#level-title`).text(`You have made it to level ` + level + '! Hit enter to try again')
            //play sound for incorrect click
            var wrongSound = new Audio('sounds/wrong.mp3');
            wrongSound.play();
            console.log("wrong")
            console.log(`[` + userClicks + `]`);
            console.log(`[` + gamePattern + `]`);
            reset();
        }
    
    }
    /************* NEXT SEQUENCE TO PROGRESS GAME *********/
    function nextSequence() {
        userClicks = [];
        level++;
        console.log(level);
    
        randomNumber = Math.floor(Math.random() * 4)
        randomChosenColor = buttonColors[randomNumber];
        gamePattern.push(randomChosenColor);
        animate(randomChosenColor);
        playSound(randomChosenColor);
    }
    
    function reset() {
        var level = 0;
        var gamePattern = [];
        var gameOn = false;
    }
    
    
    /******************** SOUNDS AND ANIMATIONS*************************************/
    
    //buttons animations
    function animate(clickedButton) {
        $(`#` + clickedButton).fadeOut(100).fadeIn(100);
    };
    
    //Play a sound in correlation to randomChosenColor
    function playSound(color) {
        var sound = new Audio('sounds/' + color + '.mp3');
        sound.play();
    };
    

    当我的代码运行时,boolean值在任何地方都不会改变,而且我还注意到,当游戏被重置时,我的数组不会被清空当我使用console.log(gameOn)时,无论游戏是否运行,它总是返回false。

    3 回复  |  直到 5 年前
        1
  •  1
  •   blurfus    5 年前

    在你的 $(document).keypress 函数尝试取出“ var “以前” gameOn = true ". 我想现在你好像在声明一个新的变量,当你真的想改变全局 gameOn 变量。

        2
  •  0
  •   FullStackEngineer    5 年前

    if (!gameOn) { nextSequence(); ..... var gameOn = true; }

    不要再声明gameOn变量你可以直接使用变量 游戏=。。。 ,因为它在函数的外部作用域中声明,并在内部作用域中可用

        3
  •  0
  •   JLowther    5 年前

    正如其他人所说,不要两次声明gameOn,它应该会成功的。

    但是我已经阅读了越来越多关于JavaScript中全局变量的“邪恶”的内容,特别是因为全局名称空间意味着任何东西都可以编辑这些变量,甚至其他脚本。

    很多人似乎倾向于将变量包装在一个对象中,比如:

    var globals = {
    buttonColors: [ "green", "red", "yellow", "blue"],
    gamePattern: [ /*Added From nextSequence*/ ],
    userClicks: [ /* Added from userClickHistory*/ ],
    level: 0,
    gameOn: false,
    }
    

    然后,使用“globals.buttonColors”来引用变量。

    如果你计划保持范围小,不是100%必要的,但无论如何都是一个很好的做法。