Multiplayer Tic Tac Toe
Abstract
Multiplayer Tic Tac Toe is a Python project that allows two players to play Tic Tac Toe over a network. It demonstrates socket programming, game logic, and GUI development. This project is ideal for learning about multiplayer games, networking, and event-driven programming.
Prerequisites
- Python 3.6 or above
- socket, threading (built-in)
- tkinter (for GUI, usually pre-installed)
Before you Start
Ensure Python is installed. No external packages are required. For GUI, make sure Tkinter is available.
Getting Started
- Create a folder named
tic-tac-toetic-tac-toe. - Create a file named
multiplayer_tic_tac_toe.pymultiplayer_tic_tac_toe.py. - Copy the code below into your file.
⚙️ Multiplayer Tic Tac Toe
Multiplayer Tic Tac Toe
"""
Multiplayer Tic-Tac-Toe
A Python-based multiplayer Tic-Tac-Toe game using socket programming. Features include:
- Two players can play over a network.
- Real-time updates of the game board.
"""
import socket
import threading
# Constants
HOST = "127.0.0.1"
PORT = 65432
# Game board
board = [" " for _ in range(9)]
current_player = "X"
lock = threading.Lock()
def print_board():
"""Print the game board."""
print("\n")
for i in range(3):
print(" | ".join(board[i * 3:(i + 1) * 3]))
if i < 2:
print("-" * 5)
def check_winner():
"""Check if there is a winner."""
winning_combinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
[0, 4, 8], [2, 4, 6] # Diagonals
]
for combo in winning_combinations:
if board[combo[0]] == board[combo[1]] == board[combo[2]] != " ":
return board[combo[0]]
if " " not in board:
return "Draw"
return None
def handle_client(conn, addr):
"""Handle communication with a client."""
global current_player
conn.sendall("Welcome to Tic-Tac-Toe!\n".encode())
conn.sendall("You are player {}\n".format(current_player).encode())
player = current_player
with lock:
current_player = "O" if current_player == "X" else "X"
while True:
conn.sendall("\n".join(board).encode())
conn.sendall("\nEnter your move (0-8): ".encode())
move = conn.recv(1024).decode().strip()
if not move.isdigit() or int(move) not in range(9):
conn.sendall("Invalid move. Try again.\n".encode())
continue
move = int(move)
with lock:
if board[move] == " ":
board[move] = player
winner = check_winner()
if winner:
conn.sendall("\nGame Over! Winner: {}\n".format(winner).encode())
break
else:
conn.sendall("Spot already taken. Try again.\n".encode())
conn.close()
def main():
"""Main server function."""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(2)
print("Server started. Waiting for players...")
while True:
conn, addr = server.accept()
print(f"Player connected from {addr}")
threading.Thread(target=handle_client, args=(conn, addr)).start()
if __name__ == "__main__":
main()
Multiplayer Tic Tac Toe
"""
Multiplayer Tic-Tac-Toe
A Python-based multiplayer Tic-Tac-Toe game using socket programming. Features include:
- Two players can play over a network.
- Real-time updates of the game board.
"""
import socket
import threading
# Constants
HOST = "127.0.0.1"
PORT = 65432
# Game board
board = [" " for _ in range(9)]
current_player = "X"
lock = threading.Lock()
def print_board():
"""Print the game board."""
print("\n")
for i in range(3):
print(" | ".join(board[i * 3:(i + 1) * 3]))
if i < 2:
print("-" * 5)
def check_winner():
"""Check if there is a winner."""
winning_combinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
[0, 4, 8], [2, 4, 6] # Diagonals
]
for combo in winning_combinations:
if board[combo[0]] == board[combo[1]] == board[combo[2]] != " ":
return board[combo[0]]
if " " not in board:
return "Draw"
return None
def handle_client(conn, addr):
"""Handle communication with a client."""
global current_player
conn.sendall("Welcome to Tic-Tac-Toe!\n".encode())
conn.sendall("You are player {}\n".format(current_player).encode())
player = current_player
with lock:
current_player = "O" if current_player == "X" else "X"
while True:
conn.sendall("\n".join(board).encode())
conn.sendall("\nEnter your move (0-8): ".encode())
move = conn.recv(1024).decode().strip()
if not move.isdigit() or int(move) not in range(9):
conn.sendall("Invalid move. Try again.\n".encode())
continue
move = int(move)
with lock:
if board[move] == " ":
board[move] = player
winner = check_winner()
if winner:
conn.sendall("\nGame Over! Winner: {}\n".format(winner).encode())
break
else:
conn.sendall("Spot already taken. Try again.\n".encode())
conn.close()
def main():
"""Main server function."""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(2)
print("Server started. Waiting for players...")
while True:
conn, addr = server.accept()
print(f"Player connected from {addr}")
threading.Thread(target=handle_client, args=(conn, addr)).start()
if __name__ == "__main__":
main()
- Run the server and client scripts as described in the code comments.
Explanation
Code Breakdown
- Import modules
import socket
import threading
import tkinter as tkimport socket
import threading
import tkinter as tk- Server and client setup
def start_server():
# Accepts connections and relays moves
pass
def start_client():
# Connects to server and sends/receives moves
passdef start_server():
# Accepts connections and relays moves
pass
def start_client():
# Connects to server and sends/receives moves
pass- Game logic and GUI
root = tk.Tk()
root.title('Multiplayer Tic Tac Toe')
# ...setup grid for game board...
root.mainloop()root = tk.Tk()
root.title('Multiplayer Tic Tac Toe')
# ...setup grid for game board...
root.mainloop()Features
- Two-player networked game
- Real-time move updates
- GUI for game board
- Demonstrates sockets and threading
How It Works
- Server relays moves between clients
- Clients send/receive moves
- GUI displays board and handles input
GUI Components
- Grid: Buttons for each cell
- Status display: Shows turn and winner
Use Cases
- Learn networking basics
- Build multiplayer games
- Practice game logic
Next Steps
You can enhance this project by:
- Adding chat feature
- Supporting AI opponent
- Improving GUI design
- Keeping score history
Enhanced Version Ideas
def add_chat():
# Allow players to chat
pass
def add_ai_opponent():
# Play against computer
passdef add_chat():
# Allow players to chat
pass
def add_ai_opponent():
# Play against computer
passTroubleshooting Tips
- Connection errors: Check IP and port
- GUI not showing: Ensure Tkinter is installed
- Moves not sent: Check server/client status
Conclusion
This project teaches networking, game logic, and GUI basics. Extend it for more features and better user experience.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
