DEV Community

Harsh Prajapat
Harsh Prajapat

Posted on

🎮 Tic Tac Toe Game (2D Array in Swift)

A simple Tic Tac Toe game example using a 2D array in Swift to demonstrate how games use 2D arrays to represent the board.

🎮 Tic Tac Toe Game (2D Array in Swift)

import Foundation

// Initialize 3x3 game board
var board: [[String]] = Array(repeating: Array(repeating: " ", count: 3), count: 3)

// Function to display the board
func printBoard() {
    for row in board {
        print(row.map { $0.isEmpty ? " " : $0 }.joined(separator: " | "))
        print("---------")
    }
}

// Function to place a move
func makeMove(row: Int, col: Int, player: String) -> Bool {
    if board[row][col] == " " {
        board[row][col] = player
        return true
    }
    return false
}

// Example moves
makeMove(row: 0, col: 0, player: "X")
makeMove(row: 1, col: 1, player: "O")
makeMove(row: 0, col: 1, player: "X")
makeMove(row: 2, col: 2, player: "O")

print("Tic Tac Toe Board:")
printBoard()
Enter fullscreen mode Exit fullscreen mode

🧾 Sample Output:

X | X |  
---------
  | O |  
---------
  |   | O
---------
Enter fullscreen mode Exit fullscreen mode

🔍 Explanation:

A 3x3 board is a [[String]] 2D array.

"X" and "O" are placed by calling makeMove().

printBoard() shows the current board state.

🧠 Extendable Ideas:

Add win check logic (row/column/diagonal).

Track turns and prevent invalid moves.

Build a UI version in SwiftUI or UIKit.

Top comments (0)