Tic Tac Toe game in C#
Below is a simple console-based Tic Tac Toe game in C#. Copy and paste this code into a C# file (e.g., TicTacToe.cs) and run it.
using System; class TicTacToe { private static char[,] board = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; private static char currentPlayer = 'X'; static void Main() { PrintBoard(); PlayGame(); } private static void PlayGame() { while (true) { Console.WriteLine($"Player {currentPlayer}'s turn."); Console.Write("Enter row (0-2): "); int row = int.Parse(Console.ReadLine()); Console.Write("Enter column (0-2): "); int col = int.Parse(Console.ReadLine()); if (IsValidMove(row, col)) { board[row, col] = currentPlayer; PrintBoard(); if (CheckWin()) { Console.WriteLine($"Player {currentPlayer} wins!"); break; } else if (IsBoardFull()) { Console.WriteLine("It's a draw!"); break; } SwitchPlayer(); } else { Console.WriteLine("Invalid move. Try again."); } } } private static void PrintBoard() { Console.WriteLine("-------------"); for (int i = 0; i < 3; i++) { Console.Write("| "); for (int j = 0; j < 3; j++) { Console.Write(board[i, j] + " | "); } Console.WriteLine("\n-------------"); } } private static bool IsValidMove(int row, int col) { return row >= 0 && row < 3 && col >= 0 && col < 3 && board[row, col] == ' '; } private static void SwitchPlayer() { currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; } private static bool CheckWin() { return (CheckRows() || CheckColumns() || CheckDiagonals()); } private static bool CheckRows() { for (int i = 0; i < 3; i++) { if (board[i, 0] == currentPlayer && board[i, 1] == currentPlayer && board[i, 2] == currentPlayer) { return true; } } return false; } private static bool CheckColumns() { for (int i = 0; i < 3; i++) { if (board[0, i] == currentPlayer && board[1, i] == currentPlayer && board[2, i] == currentPlayer) { return true; } } return false; } private static bool CheckDiagonals() { return (board[0, 0] == currentPlayer && board[1, 1] == currentPlayer && board[2, 2] == currentPlayer) || (board[0, 2] == currentPlayer && board[1, 1] == currentPlayer && board[2, 0] == currentPlayer); } private static bool IsBoardFull() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i, j] == ' ') { return false; } } } return true; } }