A suitable data structure

Viewed 58

Using Swift, iOS 15

I am working on building a simple 3D tic-tac-toe game and need a suitable data structure so that I can efficiently check for a winner. The game board looks like this.

enter image description here

Not easy to see here but it makes far more sense if you can move it around. Now in this example the blue player has won, since they have three squares in row diagonally.

In this version I have 9 x 9 nodes. I wanted to use GKOctree, but it seems to be broken and reading about it isn't the right solution.

I think some form of a linked list or simply a multidimensional array might work, but has someone come up with a better plan they could share?

1 Answers

Start off by thinking about the interface of your model rather than the actual underlying storage. Which are the questions you need to ask your model.

For example (untested, but you'll get the idea):

enum Field {
    case empty
    case blue
    case red
}

class Model {

    private let size: Int
    private var store: Array<Field> // some underlying store, in this case just a 1D-array

    init(size: Int = 3) {
         self.size = size
         self.store = Array(repeating: Field.empty, count: size*size*size)
    }
    
    func fieldAt(x: Int, y: Int, z: Int) -> Field {
        let index = x + y*self.size + z*self.size*self.size
        guard x < self.size && y < self.size && z < self.size else {  }
        return self.store[index]
    }
    func setField(value: Field, x: Int, y: Int, z: Int) {
        let index = x + y*self.size + z*self.size*self.size
        guard x < self.size && y < self.size && z < self.size else {  }
        self.store[index] = value
    }
    
}
Related