简体   繁体   English

在简单的 Memory 游戏中存储首次单击的元素

[英]Store First Clicked Element in s Simple Memory Game

I'm making a simple color memory game where originally there are 6 black boxes, and on click they change the color, taking the colors from a pre-defined array which gets shuffled at the start of the game.我正在制作一个简单的颜色 memory 游戏,最初有 6 个黑盒子,点击它们会改变颜色,从预定义的数组中取出 colors,该数组在游戏开始时被洗牌。

But I've been stuck for hours at the comparison part - handleCardClick function. It works when the colors of two boxes are the same colors, however, when colors are different, only the second clicked box goes back to black, but the first one stays colored.但是我在比较部分卡了好几个小时 - handleCardClick function。当两个盒子的colors相同colors时它有效,但是当colors不同时,只有第二个点击的盒子变回黑色,但第一个保持彩色。

I can't seem to find a way to store the first clicked box.我似乎找不到存储第一个单击框的方法。 Maybe my approach is wrong in the essence.也许我的方法本质上是错误的。 Here's my code:这是我的代码:

    let colors = ['red', 'green', 'blue', 'red', 'green', 'blue']
    const startButton = document.querySelector('.js-start-btn')
    const cards = document.querySelectorAll('.js-card')
    
    const shuffleArray = () => {
        var i = 0
          , j = 0
          , temp = null
      
        for (i = array.length - 1; i > 0; i -= 1) {
          j = Math.floor(Math.random() * (i + 1))
          temp = array[i]
          array[i] = array[j]
          array[j] = temp
        }
    }
    
    
    let emptyArr = []
    
    const handleCardClik = () => {
        // Variable to store first click card
        let firstCard
        for (let i = 0; i < cards.length; i++) {
            cards[i]?.addEventListener('click', () => {
                cards[i].style.backgroundColor = colors[i]
                firstCard = cards[i]
                //push colors into an empty array and start comparing them when there are two colors
                emptyArr.push(colors[i])
    
                if (emptyArr.length === 2) {
                // if colors are same apply them to the cards, clear the array and the storing variable    
                    if (emptyArr[0] === emptyArr[1]) {
                        firstCard = emptyArr[0]
                        cards[i].style.backgroundColor = emptyArr[1]
                        firstCard = ''
                        emptyArr = []
    
                // if colors differ keep them for 1 second, then change back to black       
                    } else if (emptyArr[0] !== emptyArr[1]) {
                        firstCard = emptyArr[0]
                        cards[i].style.backgroundColor = emptyArr[1]
                        emptyArr = []
                        setTimeout(() => {
                        firstCard = 'black'
                        cards[i].style.backgroundColor = 'black'                    
                          }, 1000)     
                        firstCard = ''
                     
                    }
                }
            })
                  
        }
    }
    
    const initializeGame = () => {
        shuffleArray(colors)
    
        for (let i = 0; i < cards.length; i++) {
            cards[i].style.backgroundColor = 'black'
        }
    
        handleCardClik()
    }
    
    startButton?.addEventListener('click', () => {
        initializeGame()   
    })
<!-- -->
    <body><section class="section-top sec-position">
        <div class="top-wrapper">
            <button class="start-btn js-start-btn">START</button>
        </div>
    </section>
    <section class="section section-main sec-position">
        <div class="main-wrapper">
            <div class="top-row">
                <div class="card js-card"></div>
                <div class="card js-card"></div>
                <div class="card js-card"></div>
            </div>
            <div class="bot-row">
                <div class="card js-card"></div>
                <div class="card js-card"></div>
                <div class="card js-card"></div>
            </div>
        </div>
    </section>
    <section class="section-bot sec-position">
        <span class="win-message">WINNER LOSER</span>
    </section>
        <script src="/scripts.js"></script>
    </body>
<!-- -->
    .sec-position {
      max-width: 1200px;
      margin: 0 auto 0 auto;
    }
    
    .main-wrapper {
      display: flex;
      flex-direction: column;
      gap: 30px;
      padding-top: 50px;
      padding-bottom: 50px;
    
    }
    
    .card {
      width: 200px;
      height: 200px;
      gap: 30px;
      background-color: black;
    }
    
    .top-row {
      display: flex;
      gap: 30px;
    }
    
    .bot-row {
      display: flex;
      gap: 30px;
    
    }

I've made some changes to the handleCardClik function it should be working the reason your code didn't work was majorly because of the settimeout function because you reset the firstcard variable before it runs and it runs after 1sec delay with the new value causing error I have simply cached the value in a variable called cachedFirstCard.我对 handleCardClik function 进行了一些更改,它应该可以正常工作,因为您的代码不起作用的主要原因是设置超时 function 因为您在运行前重置了 firstcard 变量,并且它在 1 秒延迟后运行,新值导致错误我只是将值缓存在一个名为 cachedFirstCard 的变量中。 hope this helped希望这有帮助


const handleCardClik = () => {
  // Variable to store first click card
  let firstCard
  for (let i = 0; i < cards.length; i++) {
    cards[i]?.addEventListener('click', () => {
      cards[i].style.backgroundColor = colors[i]
      //push colors into an empty array and start comparing them when there are two colors
      emptyArr.push(colors[i])

      if (emptyArr.length === 2) {
        // if colors are same apply them to the cards, clear the array and the storing variable    
        if (emptyArr[0] === emptyArr[1]) {
          cards[i].style.backgroundColor = emptyArr[1]
          firstCard = ''
          emptyArr = []

          // if colors differ keep them for 1 second, then change back to black       
        } else if (emptyArr[0] !== emptyArr[1]) {
          cards[i].style.backgroundColor = emptyArr[1]
          emptyArr = []
          let cachedFirstCard = firstCard
          setTimeout(() => {
            cachedFirstCard.style.backgroundColor = 'black'
            cards[i].style.backgroundColor = 'black'
            firstCard = ''
          }, 1000)


        }
      }
      firstCard = cards[i]
    })

  }
}

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

相关问题 记忆游戏第一张和第二张卡 - memory game first and second cards 存储ASCII艺术作品作为简单JavaScript游戏中的角色。 我可以将其存储在角色的对象中吗? - Storing ASCII art for use as a character in a simple JavaScript game. Can I store it in the character's Object? 有没有办法在 vanilla Javascript 中存储以前单击的元素 - Is there a way to store a previously clicked element in vanilla Javascript Jquery,如果它是第一次点击元素 - Jquery if its the first time element is being clicked 如何查看首先单击哪个元素? - How to see which element was clicked first? 单击的第一个元素显示第一模态,单击的第二个元素显示第二模态 - First element clicked show first modal, second element clicked show second modal 如何在简单的 memory 游戏中使用 jQuery 重置随机生成的数组 - How to get randomly generated array to reset in simple memory game with jQuery 如果单击第二个元素,jQuery each()不会继续执行第一个元素的代码? - jQuery each() not continuing code execution for first element if a second element was clicked? 如何隐藏clicked元素的祖父母的第一个孩子元素? - How to hide the first child element of grand parent of the clicked element? 有没有办法检测元素是否被 jQuery 的 click() 单击? - Is there a way to detect if an element was clicked by jQuery's click()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM