选择特定的div以使用eventListener设置属性

问题描述 投票:0回答:1

我完成了这个游戏,井字游戏,但我正在研究如何在获胜者正方形上放置颜色或画一条线。制作正方形或直线的CSS很容易,但是当我的winningCombos看起来像这样时,我不知道如何只选择获胜的正方形:

const winningCombos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]

以及将玩家移动的方式插入数组以稍后检查连击的方式。例如,也许一个玩家需要5步才能获胜,但我只需要赢得3个方格即可。

xChoices = [0,1,3,6] // where 0,3,6 are winners and I want to draw a line on them or put a colour

我检查连击的方式:

function checkForXWinner(){
        return winningCombos.some(combo =>{
            return combo.every(e =>{
                return xChoices.includes(e)
            })
        })
    }

    function checkForOWinner(){
        return winningCombos.some(combo =>{
            return combo.every(e =>{
                return oChoices.includes(e)
            })
        })
    }

这里是jsfiddle,欢呼。

https://jsfiddle.net/6zbdgrmy/

javascript css
1个回答
2
投票

由于您要给那些正方形上色,您还可以在多维数组中找到相应的数组,并分别为每个正方形上色

示例:

const winningCombos = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]

xChoices = [0, 1, 3, 6]

const winArrayIndex = winningCombos
  .map(arr => arr.every(y => xChoices.includes(y)))
  .findIndex(x => x)

for (let i = 0; i < winningCombos[winArrayIndex].length; i++) {
  console.log('color:', winningCombos[winArrayIndex][i])
}

-1
投票

尝试

 boxes = Array.from(document.querySelectorAll('.col'))
 const winCombo = () => {
   let wonCombo = []
   winningCombos.forEach(combo => {
     if (boxes[combo[0]].innerHTML == boxes[combo[1]].innerHTML && boxes[combo[0]].innerHTML == boxes[combo[2]].innerHTML && boxes[combo[0]].innerHTML != "")
       wonCombo = combo
   })
   return wonCombo
 }

这将返回获胜的组合。现在,您可以在wonCombo位置使用div,然后将所需的CSS应用于它们。

© www.soinside.com 2019 - 2024. All rights reserved.