Javascript Simon Game,如何检查答案

时间:2019-06-04 17:01:29

标签: javascript arrays

我正在尝试用Javascript制作一款适合学校的simon游戏。我目前已设置代码以自行创建颜色数组序列,并且还成功将用户答案保存到其自己的数组中,该序列在新序列上清除。我现在正在尝试查看所说的颜色序列是否与用户的颜色序列匹配,但是我不确定如何检查是否存在任何漏洞。我得到的最好的结果是能够测试userClicks数组的长度到gamePattern数组的长度,并确保最后一次点击的确是正确的,但是无法找到一种很好的方法来测试整个userClicks数组是否等效于gamePattern数组。我还将遇到必须在指定时间内填充数组的问题,我可能会使用setTimout()函数来实现这一点。必须有一种更简单的方法来测试给定数组是否等于另一个。

/*************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*/
//some document listener to look for keypress changing gameOn to `true`
//display the level to user
//activate nextSequence();

//log user clicks after nextSequence has executed, check the userClicks vs gamePattern
$(`.btn`).click(function () {
    var buttonClicked = $(this).attr(`id`);
    userClicks.push(buttonClicked);
    animate(buttonClicked);
    playSound(buttonClicked);

    checkAnswer(userClicks);
});

function checkAnswer(userClicksArray) {
    //display the current level to user
    //NOT SURE WHAT TO DO ANYMORE
}

/************* NEXT SEQUENCE TO PROGRESS GAME *********/
function nextSequence() {
    userClickPattern = [];
    level++;
    console.log(level);

    randomNumber = Math.floor(Math.random() * 4)
    randomChosenColor = buttonColors[randomNumber];
    gamePattern.push(randomChosenColor);
    animate(randomChosenColor);
    playSound(randomChosenColor);
}


/******************** SOUNDS AND ANIMATIONS*************************************/

//buttons animations
function animate(clickedButton) {
    $(`#` + clickedButton).fadeOut(100).fadeIn(100);
};

//Play a sound in corellation to randomChosenColor
function playSound(color) {
    var sound = new Audio('sounds/' + color + '.mp3');
    sound.play();
};

1 个答案:

答案 0 :(得分:2)

您应该先比较长度,如果长度相同,则循环遍历数组,并检查每个索引处的值是否相同。

如果数组是“ flat”(无嵌套数组或对象),则效果很好。如果您有嵌套的对象,则需要这样的内容:How to compare arrays in JavaScript?

function checkAnswer(gamePattern, userClicks) {
  const len = gamePattern.length;

  if (len !== userClicks.length) {
    // The lengths of the arrays don't match
    return false;
  }
  
  for (let i = 0; i < len; i++) {
    if (gamePattern[i] !== userClicks[i]) {
      // The values at the same index don't match
      return false;
    }
  }

  return true;
}

console.log(checkAnswer(['red', 'blue', 'green'], ['red', 'blue', 'green']));
console.log(checkAnswer(['red', 'blue', 'green'], ['red', 'yellow', 'green']));