How to write the Tic-Tac-Toe game in Swift

1 Answer

0 votes
/*
    A simple Tic‑Tac‑Toe game written in Swift.

    Highlights:
      - The board is represented as an Array<Character> of length 9.
      - Functions handle printing, move validation, win checking,
        and turn progression.
      - The game loop is clear and easy to follow.
      - Comments explain the reasoning behind each part of the program.
*/

import Foundation

// Print the board in a 3×3 layout
func printBoard(_ board: [Character]) {
    print()
    for i in board.indices {
        print(board[i], terminator: "")
        if (i + 1) % 3 == 0 {
            print()
        } else {
            print(" | ", terminator: "")
        }
    }
    print()
}

// Check if a player has won
func checkWin(_ board: [Character], _ player: Character) -> Bool {
    let wins = [
        [0,1,2], [3,4,5], [6,7,8],   // rows
        [0,3,6], [1,4,7], [2,5,8],   // columns
        [0,4,8], [2,4,6]             // diagonals
    ]

    return wins.contains { combo in
        let (a, b, c) = (combo[0], combo[1], combo[2])
        return board[a] == player && board[b] == player && board[c] == player
    }
}

// Check if the board is full (draw)
func boardFull(_ board: [Character]) -> Bool {
    return !board.contains(" ")
}

// Attempt to place a move; return updated board or nil if invalid
func placeMove(_ board: inout [Character], pos: Int, player: Character) -> Bool {
    guard pos >= 0 && pos < 9 else { return false }
    guard board[pos] == " " else { return false }
    board[pos] = player
    return true
}

// Perform a single turn; retry on invalid input
func takeTurn(board: inout [Character], player: Character) {
    print("Player \(player), enter position (0‑8): ", terminator: "")
    guard let input = readLine(), let pos = Int(input) else {
        print("Invalid input. Try again.")
        return takeTurn(board: &board, player: player)
    }

    if !placeMove(&board, pos: pos, player: player) {
        print("Invalid move. Try again.")
        return takeTurn(board: &board, player: player)
    }
}

var board: [Character] = Array(repeating: " ", count: 9)
var currentPlayer: Character = "X"

print("Tic‑Tac‑Toe")
printBoard(board)

while true {
    takeTurn(board: &board, player: currentPlayer)
    printBoard(board)

    if checkWin(board, currentPlayer) {
        print("Player \(currentPlayer) wins!")
        break
    }

    if boardFull(board) {
        print("It's a draw!")
        break
    }

    currentPlayer = (currentPlayer == "X") ? "O" : "X"
}



/*
run:

Tic‑Tac‑Toe

  |   |  
  |   |  
  |   |  

Player X, enter position (0‑8): 3

  |   |  
X |   |  
  |   |  

Player O, enter position (0‑8): 4

  |   |  
X | O |  
  |   |  

Player X, enter position (0‑8): 7

  |   |  
X | O |  
  | X |  

Player O, enter position (0‑8): 8

  |   |  
X | O |  
  | X | O

Player X, enter position (0‑8): 1

  | X |  
X | O |  
  | X | O

Player O, enter position (0‑8): 2

  | X | O
X | O |  
  | X | O

Player X, enter position (0‑8): 0

X | X | O
X | O |  
  | X | O

Player O, enter position (0‑8): 5

X | X | O
X | O | O
  | X | O

Player O wins!

*/

 



answered Aug 27 by avibootz
...