Sure! Below is a simple implementation of a Tic-Tac-Toe game in Python that you can play in the console. This game allows two players to play against each other on a 3x3 grid.
def draw_board(board):
print("\n")
print(" | | ")
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("_____|_____|_____")
print(" | | ")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("_____|_____|_____")
print(" | | ")
print(f" {board[6]} | {board[7]} | {board[8]} ")
print(" | | ")
print("\n")
def check_win(board, player):
# Check horizontal, vertical and diagonal conditions
win_conditions = [
[board[0], board[1], board[2]], # Top row
[board[3], board[4], board[5]], # Middle row
[board[6], board[7], board[8]], # Bottom row
[board[0], board[3], board[6]], # Left column
[board[1], board[4], board[7]], # Middle column
[board[2], board[5], board[8]], # Right column
[board[0], board[4], board[8]], # Diagonal from top-left
[board[2], board[4], board[6]], # Diagonal from top-right
]
return [player, player, player] in win_conditions
def check_draw(board):
return all(space != ' ' for space in board)
def tic_tac_toe():
board = [' ' for _ in range(9)]
current_player = 'X'
while True:
draw_board(board)
try:
choice = int(input(f"Player {current_player}, choose an empty spot between 1-9: ")) - 1
if choice < 0 or choice > 8:
print("Invalid choice. Please select a spot between 1 and 9.")
continue
if board[choice] != ' ':
print("Spot already taken. Choose another spot.")
continue
board[choice] = current_player
if check_win(board, current_player):
draw_board(board)
print(f"Congratulations! Player {current_player} wins!")
break
if check_draw(board):
draw_board(board)
print("It's a draw!")
break
# Switch player
current_player = 'O' if current_player == 'X' else 'X'
except ValueError:
print("Invalid input. Please enter a number between 1 and 9.")
if __name__ == "__main__":
tic_tac_toe()
How to Run the Game:
- Copy the code into a file named
tic_tac_toe.py.
- Open your terminal or command prompt.
- Navigate to the directory containing the
tic_tac_toe.py file.
- Run the game by typing
python tic_tac_toe.py (you may need to use python3 instead of python depending on your system configuration).
Game Instructions:
- The game is played on a grid that's 3 squares by 3 squares.
- Player X goes first, and players alternate placing Xs and Os on the board.
- To place your mark, input a number from 1 to 9 corresponding to the board positions as shown below:
1 | 2 | 3
-----------
4 | 5 | 6
-----------
7 | 8 | 9
- The first player to get 3 of their marks in a row (up, down, across, or diagonally) is the winner.
- If all 9 squares are full and neither player has 3 in a row, the game ends in a draw.
Code Explanation:
- draw_board(board): Renders the current state of the board.
- check_win(board, player): Checks all possible winning combinations to see if the current player has won.
- check_draw(board): Checks if the board is full without any winner.
- tic_tac_toe(): Main function that runs the game loop, handles player input, and switches turns.
Enhancements You Can Try:
- Input Validation: Enhance the input validation to handle unexpected inputs more gracefully.
- AI Opponent: Modify the game to allow one player to play against the computer using simple AI.
- Graphical Interface: Use libraries like
tkinter or pygame to create a graphical version of the game.
- Score Keeping: Implement a scoring system that keeps track of wins, losses, and draws over multiple games.
Enjoy your game of Tic-Tac-Toe!