繁体   English   中英

在数组中查找具有相同颜色的元素,如果元素彼此相邻,则显示true

[英]Find elements in array with the same color and print true if they are next to each other

它以某种方式起作用,我做到了。 但是我知道应该有一种更好和优化的方法来对所有行和所有颜色进行此检查。 如果您知道的话,请分享。 谢谢

  func checkMovesAvailable(){
    var count = 0
    var yellowArray = [0,0,0,0]
    var movesAvailable: Bool = false
    for i in 0..<3{
    square[i, 0]
    if(square.fillColor == SKColor.yellow){
    yellowArray.remove(at: i)
    yellowArray.insert(1, at: i)
    print(yellowArray)

    if yellowArray[0] == yellowArray[1] || yellowArray[1] == yellowArray[2] || 
yellowArray[2] == yellowArray[3] {
    count += 1
    }
    }
    }

    if(count>=2){
    movesAvailable = true
    }
    if(count<=1){
    movesAvailable = false
    }
    print("movesAvailable: \(movesAvailable)")
    }

预习

如果我正确理解了您的问题,则您有一个SKShapeNode数组,并想检查是否有任何相邻的节点具有相同的填充颜色。 这可以简单地通过以下方式完成:

func isMoveAvailable(squares: [SKShapeNode]) -> Bool {
    return zip(squares, squares.dropFirst()).contains(where: { $0.fillColor == $1.fillColor })
}

说明:

  • squares.dropFirst()返回包含第一个元素的节点序列。
  • zip(squares, squares.dropFirst())返回带有成对的相邻节点的序列:

     (node0, node1), (node1, node2), ... 
  • contains(...)检查是否有一对颜色相同的填充色。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM