a tic tac toe game in swift

Here's a basic implementation of Tic Tac Toe game in Swift:

main.swift
enum GameMarker: String {
    case X = "X"
    case O = "O"
    case empty = "-"
}

class TicTacToe {
    
    var gameBoard: [[GameMarker]] = [
        [.empty, .empty, .empty],
        [.empty, .empty, .empty],
        [.empty, .empty, .empty]
    ]
    
    var currentPlayer: GameMarker = .X
    
    func playMove(row: Int, column: Int) -> Bool {
        if gameBoard[row][column] == .empty {
            gameBoard[row][column] = currentPlayer
            swapPlayers()
            return true
        }
        return false
    }
    
    func swapPlayers() {
        if currentPlayer == .X {
            currentPlayer = .O
        } else {
            currentPlayer = .X
        }
    }
    
    func printBoard() {
        for row in gameBoard {
            print(row)
        }
    }
    
    func checkForWin() -> Bool {
        // Check rows
        for row in gameBoard {
            if row == [.X, .X, .X] || row == [.O, .O, .O] {
                return true
            }
        }
        
        // Check columns
        for i in 0...2 {
            if gameBoard[0][i] == gameBoard[1][i] && gameBoard[1][i] == gameBoard[2][i] && gameBoard[0][i] != .empty {
                return true
            }
        }
        
        // Check diagonals
        if gameBoard[0][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][2] && gameBoard[0][0] != .empty {
            return true
        }
        if gameBoard[0][2] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][0] && gameBoard[0][2] != .empty {
            return true
        }
        
        return false
    }
    
}

let game = TicTacToe()

game.playMove(row: 0, column: 0)
game.playMove(row: 1, column: 1)
game.playMove(row: 0, column: 2)
game.playMove(row: 1, column: 2)
game.playMove(row: 0, column: 1)
game.playMove(row: 2, column: 0)

game.printBoard()
print(game.checkForWin())
1871 chars
79 lines

This implementation uses a 2D array to represent the game board and an enum to represent the game markers (X, O, and empty). The playMove function checks to see if the selected cell is already occupied and updates the board accordingly. The checkForWin function checks to see if any player has won the game by comparing all possible win conditions. Finally, the printBoard function outputs the current state of the game board in a readable format.

gistlibby LogSnag