首页 > 解决方案 > 试图理解内存卡匹配游戏项目的这段代码

问题描述

所以这是来自免费代码营:https ://medium.freecodecamp.org/vanilla-javascript-tutorial-build-a-memory-game-in-30-minutes-e542c4447eae

我正在尝试自己创建一个类似的游戏,但是自从我弄乱了 JS 以来,这已经是一段时间了。我无法理解这段代码的必要性......或者我想一般都理解它!该网站说这设置了匹配逻辑,但如果有人可以为我更好地分解它,我将不胜感激!如果您访问该站点,则 checkForMatch 功能对我来说是可以管理的。我知道 !使事物成为布尔值并且还???根据默认值将它们从 true 切换为 false 或相反?我也不记得我是否同时遇到了两个变量的声明以及这意味着什么。

谢谢您的帮助!已经好几个小时了,我想我这一天已经撞到了我的心理墙!

以下是来自网站的描述:

“既然我们有了翻牌,我们来处理匹配逻辑。当我们点击第一张牌时,需要等到另一张牌翻完。变量 hasFlippedCard 和 flippedCard 将管理翻牌状态。如果没有翻牌, hasFlippedCard 设置为true,flippedCard 设置为点击的卡片。我们也切换toggle方法添加:"

    const cards = document.querySelectorAll('.memory-card');

    let hasFlippedCard = false;
    let firstCard, secondCard;

    function flipCard() {
      this.classList.add('flip');

      if (!hasFlippedCard) {
         hasFlippedCard = true;
         firstCard = this;
         return;
         }

         secondCard = this;
         hasFlippedCard = false;

         checkForMatch();
       }

标签: javascriptfunction

解决方案


至于你对“!”的问题,这意味着没有。您可以使用它来检查某事是真还是假,或者一个变量是否为空,或者是否包含一个值。我添加了一些评论,这些评论将在下面解释。

var test = null;
var theBool = true;
if(!test){ // if test is null or false
 // You will enter this if statement because test is null
}
if(!theBool){ // if theBool is null or false
 // You will not enter this if statement because theBool is 
// true.
}

test = 10;

if(!test){ // if test is null or false
 // You will not enter this if statement now because test is 
 // not null, it has the value of 10.
}

theBool = false;

if(!theBool){ // if theBool is false or null
// You will enter this if statement because theBool is false.
}

我还在您提供的代码块中添加了一些注释。

 // Grabbing everything with a class .memory-card
const cards = document.querySelectorAll('.memory-card');

let hasFlippedCard = false;
let firstCard, secondCard; 
/*
  same as 
  var firstCard;
  var secondCard;
*/

function flipCard() {

  // Adds the css class flip to what you just clicked on.
  this.classList.add('flip');

  // if hasFlipped === false or is null
  if (!hasFlippedCard) {

     // Set has flipped to true
     hasFlippedCard = true;

     // the first card value now = what you have clicked on.
     firstCard = this;

     // Function complete, return and wait for the next click
     return; 
     }

     // First card was set before, currently it is true, so 
     // the if statement was skipped.
     // The second card is now what you clicked on.
     secondCard = this;

    // Setting to false so next time you click, you will be
    // setting the firstCard value again.
     hasFlippedCard = false;

     // Both card values have been set, now check if they are
     // the same as each other.
     checkForMatch();
   }

享受 JavaScript :)


推荐阅读