如何在JavaScript中使用不超过3行连接两个块?像单人连线游戏

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

正在为JavaScript原型开发类似游戏的原型。我需要使用不超过3条线连接两个块。

这是我想做的

enter image description here

这些线可以将两个块连接在一起,也可以用3条线将它们分开。它不能连接有另一个块“阻塞”或对角线阻塞的块。

我已经尝试使用寻路方法,但是它无法按预期运行,因为它会寻找最短的路径,但在这种情况下,必须考虑到它应该尽可能多地走3圈才能到达目的地)

我曾考虑过使用Floodfill方法,但在此示例中无法使其正常工作。我什至在网上找到了一个有趣的解释https://www.youtube.com/watch?v=Zwh-QNlsurI

有人可以帮我找到一个起点算法吗?

谢谢,

javascript connect
1个回答
0
投票

如果网格为4x4,每个正方形都从上到下,从左到右依次编号:

 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

您希望在以下情况下匹配任意两个正方形xy

y - x == 1 3 && (x+1) % 4 > 0 //for horizontally adjacent squares 
y - x == 4 //for vertically adjacent squares
y - x == 3 && (y+1) % 4 == 0 //for squares at opposite ends of a row

更新:测试用例

let grid = document.querySelector(".grid")

for(i=0;i<16;i++){
   let sq = document.createElement("div")
   sq.classList.add("sq")
   sq.dataset.id = i
   grid.appendChild(sq)
}

let squares = document.querySelectorAll(".sq")
let x = null,y = null
squares.forEach(el => {
    el.addEventListener("click", (e) => {
        let dId = e.target.dataset.id
        if(!x){
            x = dId
            e.target.classList.add("x")
        }else if(!y){
            y = dId
            e.target.classList.add("y")
            checkIfWinner(x,y)
        }
    })
})

document.getElementById("reset").onclick = () => {
    console.clear()
    x=null
    y=null
    squares.forEach(el => {el.classList.remove("x"); el.classList.remove("y")})
}

function checkIfWinner(x,y){
    if( (y - x == 1 && (parseInt(x)+1) % 4 > 0) || y - x == 4 || (y - x == 3 && (parseInt(y)+1) % 4 == 0)){
        console.log("Winner")
    }else{
        console.log("Try Again")
    }
}
.grid{
   display:inline-grid;
   grid-template-columns: repeat(4,1fr);
   grid-gap: 4px;
}

.grid > div{
   border: solid 2px gray;
   height: 30px;
   width: 30px;
}

.x{
    background-color: dodgerblue;
}

.y{
    background-color: orangered;
}
<div class="grid"></div>
<button id="reset">Reset</button>
© www.soinside.com 2019 - 2024. All rights reserved.