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

1 Answer

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

    Highlights:
      - Uses readlnOrNull() instead of deprecated readLine().
      - The board is represented as a MutableList<Char>.
      - Functions handle printing, move validation, win checking,
        and turn progression.
*/

// Print the board in a 3×3 layout
fun printBoard(board: List<Char>) {
    println()
    for (i in board.indices) {
        print(board[i])
        if ((i + 1) % 3 == 0) println()
        else print(" | ")
    }
    println()
}

// Check if a player has won
fun checkWin(board: List<Char>, player: Char): Boolean {
    val wins = listOf(
        listOf(0,1,2), listOf(3,4,5), listOf(6,7,8),   // rows
        listOf(0,3,6), listOf(1,4,7), listOf(2,5,8),   // columns
        listOf(0,4,8), listOf(2,4,6)                   // diagonals
    )

    return wins.any { (a, b, c) ->
        board[a] == player && board[b] == player && board[c] == player
    }
}

// Check if the board is full (draw)
fun boardFull(board: List<Char>): Boolean =
    board.none { it == ' ' }

// Attempt to place a move; return true if successful
fun placeMove(board: MutableList<Char>, pos: Int, player: Char): Boolean {
    if (pos !in 0..8) return false
    if (board[pos] != ' ') return false
    board[pos] = player
    return true
}

// Perform a single turn; retry on invalid input
fun takeTurn(board: MutableList<Char>, player: Char): MutableList<Char> {
    print("Player $player, enter position (0-8): ")
    val input = readlnOrNull()?.trim() ?: ""

    if (!input.matches(Regex("\\d+"))) {
        println("Invalid input. Try again.")
        return takeTurn(board, player)
    }

    val pos = input.toInt()

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

    return board
}

fun main() {
    val board = MutableList(9) { ' ' }
    var currentPlayer = 'X'

    println("Tic-Tac-Toe")
    printBoard(board)

    while (true) {
        takeTurn(board, currentPlayer)
        printBoard(board)

        if (checkWin(board, currentPlayer)) {
            println("Player $currentPlayer wins!")
            break
        }

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

        currentPlayer = if (currentPlayer == 'X') 'O' else 'X'
    }
}



/*
run:

Tic-Tac-Toe

  |   |  
  |   |  
  |   |  

Player X, enter position (0-8): 4

  |   |  
  | X |  
  |   |  

Player O, enter position (0-8): 1

  | O |  
  | X |  
  |   |  

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

X | O |  
  | X |  
  |   |  

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

X | O |  
  | X | O
  |   |  

Player X, enter position (0-8): 5
Invalid move. Try again.
Player X, enter position (0-8): 3

X | O |  
X | X | O
  |   |  

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

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

Player X, enter position (0-8): 6

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

Player X wins!

*/

 



answered Aug 27 by avibootz
...