简体   繁体   English

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

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

It somehow works, the way i did it. 它以某种方式起作用,我做到了。 But i know there should be better and optimized way to do this check for all rows and all colors. 但是我知道应该有一种更好和优化的方法来对所有行和所有颜色进行此检查。 If you know any, please share. 如果您知道的话,请分享。 Thanks 谢谢

  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)")
    }

预习

If I understand your question correctly, you have an array of SKShapeNode s and want to check if any adjacent nodes have the same fill color. 如果我正确理解了您的问题,则您有一个SKShapeNode数组,并想检查是否有任何相邻的节点具有相同的填充颜色。 That can simply be done with: 这可以简单地通过以下方式完成:

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

Explanation: 说明:

  • squares.dropFirst() returns a sequence of the nodes without the first element. squares.dropFirst()返回包含第一个元素的节点序列。
  • zip(squares, squares.dropFirst()) returns a sequence with pairs of adjacent nodes: zip(squares, squares.dropFirst())返回带有成对的相邻节点的序列:

     (node0, node1), (node1, node2), ... 
  • contains(...) checks if there is a pair with the same fill color. contains(...)检查是否有一对颜色相同的填充色。

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

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