This project is a simple implementation of the classic Tic-Tac-Toe game in Python. It is designed for two players, with each taking turns to play as either X or O. The game is interactive and text-based, making it easy to play directly in the terminal.
- Objective: The goal of the game is to align three of your marks (
XorO) either horizontally, vertically, or diagonally on a 3x3 grid before your opponent does. - Inputs: Players input a number between 1 and 9 to place their mark in the corresponding cell of the grid. The grid cells are numbered as follows:
1 | 2 | 3 --------- 4 | 5 | 6 --------- 7 | 8 | 9 - Rules:
- A cell can only be marked if it is empty (
-). - If a player inputs an invalid number or selects an already marked cell, they will be prompted to try again.
- A cell can only be marked if it is empty (
- Interactive Gameplay: The game prompts each player with their turn and highlights errors if any invalid moves are made.
- Dynamic Board: The grid updates in real-time after each move.
- Winner Detection: The game checks for a winner after each turn and announces the result immediately.
- Tie Detection: If all cells are filled and no winner is determined, the game declares a tie.
board: Represents the 3x3 game grid.currentPlayer: Tracks the player whose turn it is (XorO).winner: Stores the winner of the game (if any).gameRunning: A flag to keep the game running until it ends.
-
printBoard(board)Displays the current state of the board in a visually appealing format. -
playerInput(board)Prompts the current player to input a move, validates the input, and updates the board accordingly. -
checkHorizontal(board)Checks for a winning condition in the horizontal rows. -
checkRow(board)Checks for a winning condition in the vertical columns. -
checkDiagonal(board)Checks for a winning condition in the diagonal lines. -
checkTie(board)Checks if the board is full and declares a tie if no winner is found. -
checkWin()Combines all winning checks and announces the winner if any. -
switchPlayer()Alternates thecurrentPlayerbetweenXandO.
The game runs in a loop, displaying the board, accepting inputs, checking for a winner or tie, and switching players until the game concludes.
- | - | -
---------
- | - | -
---------
- | - | -
Enter a number 1-9 Player (X) : 1
X | - | -
---------
- | - | -
---------
- | - | -
Enter a number 1-9 Player (O) : 5
X | - | -
---------
- | O | -
---------
- | - | -
...
The winner is X
- Install Python (if not already installed).
- Copy the code into a
.pyfile. - Open a terminal and run the script using:
python <filename>.py
- Follow the prompts to play.
- Add a graphical user interface (GUI).
- Implement an AI opponent for single-player mode.
- Allow customizable board sizes.
Enjoy playing Tic-Tac-Toe!