简体   繁体   中英

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. 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.
  • zip(squares, squares.dropFirst()) returns a sequence with pairs of adjacent nodes:

     (node0, node1), (node1, node2), ... 
  • contains(...) checks if there is a pair with the same fill color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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