To enhance your multiplayer Tic Tac Toe game with a room-based system and a more modern UI, we'll make several modifications:
-
Server-Side (server.py):
- Implement Room Management: Introduce a room system where each room has a unique code. Players can create or join rooms using these codes.
- Handle Multiple Rooms Concurrently: Ensure the server can manage multiple game rooms simultaneously without interference.
-
Client-Side (game.html):
- Modernize the UI: Update the HTML and CSS to provide a sleek and responsive design using Flexbox and enhanced styling.
- Add Room Functionality: Allow players to create or join rooms by entering or generating unique room codes.
Below are the updated server and client codes with detailed explanations.
Updated server.py
import asyncio
import websockets
import json
import string
import random
PORT = 6789
# Dictionary to manage all active rooms
rooms = {}
def generate_room_code(length=6):
"""Generate a unique room code."""
while True:
code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
if code not in rooms:
return code
class Game:
def __init__(self, room_code, player1, player2):
self.room_code = room_code
self.players = [player1, player2]
self.symbols = {player1: 'X', player2: 'O'}
self.board = [''] * 9
self.current_turn = player1
self.active = True
async def start(self):
"""Notify players that the game has started and assign symbols."""
start_msg_p1 = {'type': 'start', 'symbol': self.symbols[self.players[0]], 'room': self.room_code}
start_msg_p2 = {'type': 'start', 'symbol': self.symbols[self.players[1]], 'room': self.room_code}
await asyncio.gather(
self.players[0].send(json.dumps(start_msg_p1)),
self.players[1].send(json.dumps(start_msg_p2))
)
await self.notify_turn()
async def notify_turn(self):
"""Notify players whose turn it is."""
if not self.active:
return
current_symbol = self.symbols[self.current_turn]
turn_msg = {'type': 'turn', 'symbol': current_symbol}
await asyncio.gather(
self.players[0].send(json.dumps(turn_msg)),
self.players[1].send(json.dumps(turn_msg))
)
def check_winner(self):
"""Check if there's a winner or a draw."""
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:
a, b, c = combo
if self.board[a] and self.board[a] == self.board[b] == self.board[c]:
return self.board[a]
if all(cell != '' for cell in self.board):
return 'Draw'
return None
async def handle_move(self, player, index):
"""Process a player's move."""
if player != self.current_turn or not self.active:
await player.send(json.dumps({'type': 'error', 'message': 'Not your turn.'}))
return
if self.board[index] != '':
await player.send(json.dumps({'type': 'error', 'message': 'Cell already occupied.'}))
return
symbol = self.symbols[player]
self.board[index] = symbol
move_msg = {'type': 'move', 'index': index, 'symbol': symbol}
await asyncio.gather(
self.players[0].send(json.dumps(move_msg)),
self.players[1].send(json.dumps(move_msg))
)
# Check for winner
result = self.check_winner()
if result:
self.active = False
if result == 'Draw':
end_msg = {'type': 'end', 'result': 'It\'s a draw!'}
else:
end_msg = {'type': 'end', 'result': f'{result} wins!'}
await asyncio.gather(
self.players[0].send(json.dumps(end_msg)),
self.players[1].send(json.dumps(end_msg))
)
else:
# Switch turn
self.current_turn = self.players[1] if self.current_turn == self.players[0] else self.players[0]
await self.notify_turn()
async def handle_reset(self, player):
"""Handle game reset requests."""
if not self.active:
# Reset the game
self.board = [''] * 9
self.active = True
await asyncio.gather(
self.players[0].send(json.dumps({'type': 'reset'})),
self.players[1].send(json.dumps({'type': 'reset'}))
)
# Decide who starts (player1 starts)
self.current_turn = self.players[0]
await self.start()
else:
# If game is active, do not allow reset
await player.send(json.dumps({'type': 'error', 'message': 'Cannot reset during an active game.'}))
async def handle_disconnect(self, player):
"""Handle player disconnections."""
opponent = self.players[1] if self.players[0] == player else self.players[0]
if self.active:
end_msg = {'type': 'end', 'result': 'Opponent disconnected.'}
await opponent.send(json.dumps(end_msg))
# Clean up room
del rooms[self.room_code]
await asyncio.gather(
opponent.close(),
player.close()
)
async def handler(websocket, path):
"""
Handle incoming WebSocket connections.
Expected protocol:
- Client sends a JSON message to 'create' or 'join' a room.
- After joining, the game starts when two players are in the room.
"""
try:
async for message in websocket:
data = json.loads(message)
if data['type'] == 'create':
# Create a new room
room_code = generate_room_code()
rooms[room_code] = {'players': [websocket], 'game': None}
await websocket.send(json.dumps({'type': 'created', 'room': room_code}))
print(f"Room {room_code} created by {websocket.remote_address}")
elif data['type'] == 'join':
# Join an existing room
room_code = data.get('room')
if room_code not in rooms:
await websocket.send(json.dumps({'type': 'error', 'message': 'Room does not exist.'}))
elif len(rooms[room_code]['players']) >= 2:
await websocket.send(json.dumps({'type': 'error', 'message': 'Room is full.'}))
else:
rooms[room_code]['players'].append(websocket)
player1, player2 = rooms[room_code]['players']
game = Game(room_code, player1, player2)
rooms[room_code]['game'] = game
await game.start()
print(f"Player joined room {room_code} from {websocket.remote_address}")
elif data['type'] == 'move':
# Handle a move; ensure the player is part of a game
room_code = data.get('room')
game = rooms.get(room_code, {}).get('game')
if not game:
await websocket.send(json.dumps({'type': 'error', 'message': 'Game not found.'}))
continue
index = data.get('index')
if index is not None and 0 <= index < 9:
await game.handle_move(websocket, index)
else:
await websocket.send(json.dumps({'type': 'error', 'message': 'Invalid move.'}))
elif data['type'] == 'reset':
# Handle a reset request
room_code = data.get('room')
game = rooms.get(room_code, {}).get('game')
if not game:
await websocket.send(json.dumps({'type': 'error', 'message': 'Game not found.'}))
continue
await game.handle_reset(websocket)
else:
await websocket.send(json.dumps({'type': 'error', 'message': 'Unknown command.'}))
except websockets.exceptions.ConnectionClosed:
print(f"Connection closed: {websocket.remote_address}")
# Find and handle disconnection
for room_code, room in list(rooms.items()):
if websocket in room['players']:
game = room.get('game')
if game:
await game.handle_disconnect(websocket)
else:
# Room still has only one player
room['players'].remove(websocket)
del rooms[room_code]
break
# Start the WebSocket server
start_server = websockets.serve(handler, "0.0.0.0", PORT)
print(f"Server started on port {PORT}")
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Explanation of Changes:
-
Room Generation:
generate_room_code Function: Generates a unique 6-character room code consisting of uppercase letters and digits.
-
Room Management:
rooms Dictionary: Keeps track of all active rooms with their respective players and game instances.
- Handling 'create' and 'join' Messages: Clients can send a
'create' message to create a new room or a 'join' message with a specific room code to join an existing room.
-
Game Class Enhancements:
- Room Code Tracking: Each
Game instance is associated with a specific room code.
- Enhanced Error Handling: Provides feedback to players for invalid moves or actions.
- Disconnection Handling: Notifies the opponent if a player disconnects and cleans up the room accordingly.
-
Concurrency Handling:
- The server can manage multiple rooms simultaneously, each with its own
Game instance.
Updated game.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Multiplayer Tic Tac Toe</title>
<style>
/* Reset and basic styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #ece9e6, #ffffff);
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
padding: 20px;
}
h1 {
margin-bottom: 20px;
color: #333;
}
/* Room Interface */
#room-interface {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 20px;
}
#room-interface input {
padding: 10px;
margin: 5px 0;
width: 200px;
border: 1px solid #ccc;
border-radius: 5px;
}
#room-interface button {
padding: 10px 20px;
margin-top: 10px;
background-color: #4CAF50;
border: none;
color: white;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
#room-interface button:hover {
background-color: #45a049;
}
/* Status Message */
#status {
margin-bottom: 20px;
font-size: 1.2em;
color: #555;
}
/* Game Grid */
#game {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 10px;
margin-bottom: 20px;
}
.cell {
width: 100px;
height: 100px;
background-color: #fafafa;
border: 2px solid #ddd;
border-radius: 10px;
font-size: 2.5em;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.1s ease;
}
.cell:hover {
background-color: #f0f0f0;
}
.cell.disabled {
cursor: not-allowed;
background-color: #e0e0e0;
color: #999;
}
/* Restart Button */
#restart {
padding: 10px 20px;
font-size: 1em;
background-color: #2196F3;
border: none;
color: white;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
#restart:hover {
background-color: #0b7dda;
}
/* Responsive Design */
@media (max-width: 500px) {
#game {
grid-template-columns: repeat(3, 80px);
grid-gap: 8px;
}
.cell {
width: 80px;
height: 80px;
font-size: 2em;
}
#room-interface input {
width: 160px;
}
}
</style>
</head>
<body>
<h1>Multiplayer Tic Tac Toe</h1>
<div id="room-interface">
<button id="create-room">Create Room</button>
<div style="margin: 10px 0; font-weight: bold;">OR</div>
<input type="text" id="room-code-input" placeholder="Enter Room Code" maxlength="6">
<button id="join-room">Join Room</button>
</div>
<div id="current-room" style="display: none; margin-bottom: 10px; font-size: 1em; color: #333;">
Room Code: <span id="current-room-code"></span>
</div>
<div id="status">Please create or join a room to start the game.</div>
<div id="game" style="display: none;">
<!-- 9 cells -->
<div class="cell" data-index="0"></div>
<div class="cell" data-index="1"></div>
<div class="cell" data-index="2"></div>
<div class="cell" data-index="3"></div>
<div class="cell" data-index="4"></div>
<div class="cell" data-index="5"></div>
<div class="cell" data-index="6"></div>
<div class="cell" data-index="7"></div>
<div class="cell" data-index="8"></div>
</div>
<button id="restart" disabled>Restart</button>
<script>
const createRoomButton = document.getElementById('create-room');
const joinRoomButton = document.getElementById('join-room');
const roomCodeInput = document.getElementById('room-code-input');
const currentRoomDiv = document.getElementById('current-room');
const currentRoomCodeSpan = document.getElementById('current-room-code');
const statusDiv = document.getElementById('status');
const gameDiv = document.getElementById('game');
const cells = document.querySelectorAll('.cell');
const restartButton = document.getElementById('restart');
let socket;
let mySymbol;
let myTurn = false;
let gameActive = false;
let roomCode = null;
function connect() {
// Replace 'localhost' and port '6789' with your server's address and port if different
socket = new WebSocket('ws://localhost:6789');
socket.onopen = () => {
console.log('Connected to server');
};
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
switch(message.type) {
case 'created':
roomCode = message.room;
currentRoomCodeSpan.textContent = roomCode;
currentRoomDiv.style.display = 'block';
statusDiv.textContent = 'Waiting for an opponent to join...';
gameDiv.style.display = 'none';
break;
case 'start':
mySymbol = message.symbol;
roomCode = message.room;
currentRoomCodeSpan.textContent = roomCode;
currentRoomDiv.style.display = 'block';
gameDiv.style.display = 'grid';
gameActive = true;
myTurn = mySymbol === 'X'; // X always starts
updateStatus();
break;
case 'turn':
const symbol = message.symbol;
myTurn = (symbol === mySymbol);
updateStatus();
break;
case 'move':
updateBoard(message.index, message.symbol);
break;
case 'end':
gameActive = false;
statusDiv.textContent = message.result;
restartButton.disabled = false;
break;
case 'reset':
resetGame();
break;
case 'error':
alert(message.message);
break;
default:
console.log('Unknown message type:', message.type);
}
};
socket.onclose = () => {
statusDiv.textContent = 'Disconnected from server.';
gameActive = false;
gameDiv.style.display = 'none';
currentRoomDiv.style.display = 'none';
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
function updateStatus() {
if (!gameActive) return;
if (myTurn) {
statusDiv.textContent = 'Your turn (' + mySymbol + ')';
} else {
statusDiv.textContent = 'Opponent\'s turn';
}
}
function updateBoard(index, symbol) {
const cell = document.querySelector(`.cell[data-index='${index}']`);
if (cell && cell.textContent === '') {
cell.textContent = symbol;
cell.classList.add('disabled');
}
}
function resetGame() {
cells.forEach(cell => {
cell.textContent = '';
cell.classList.remove('disabled');
});
restartButton.disabled = true;
statusDiv.textContent = 'Game reset. Waiting for opponent...';
myTurn = mySymbol === 'X';
gameActive = true;
updateStatus();
}
createRoomButton.addEventListener('click', () => {
socket.send(JSON.stringify({ type: 'create' }));
createRoomButton.disabled = true;
joinRoomButton.disabled = true;
roomCodeInput.disabled = true;
});
joinRoomButton.addEventListener('click', () => {
const code = roomCodeInput.value.trim().toUpperCase();
if (code.length !== 6) {
alert('Please enter a valid 6-character room code.');
return;
}
socket.send(JSON.stringify({ type: 'join', room: code }));
createRoomButton.disabled = true;
joinRoomButton.disabled = true;
roomCodeInput.disabled = true;
});
cells.forEach(cell => {
cell.addEventListener('click', () => {
if (!gameActive || !myTurn || cell.textContent !== '') return;
const index = cell.getAttribute('data-index');
socket.send(JSON.stringify({ type: 'move', index: parseInt(index), room: roomCode }));
cell.textContent = mySymbol;
cell.classList.add('disabled');
myTurn = false;
updateStatus();
});
});
restartButton.addEventListener('click', () => {
socket.send(JSON.stringify({ type: 'reset', room: roomCode }));
restartButton.disabled = true;
});
window.addEventListener('load', () => {
connect();
});
</script>
</body>
</html>
Explanation of Changes:
-
Room Interface:
- Buttons to Create or Join a Room: Players can either create a new room or join an existing one by entering a 6-character room code.
- Display Current Room Code: Once a room is created or joined, the room code is displayed for reference.
-
Modernized UI:
- Enhanced Styling: Utilizes Flexbox for layout, improved color schemes, smoother transitions, and responsive design for better adaptability on different screen sizes.
- Responsive Design: Ensures the game looks good on both desktop and mobile devices.
-
Game Logic Enhancements:
- Room Code Management: All game-related messages include the
room field to ensure actions are scoped to the correct room.
- Dynamic Status Updates: Reflects real-time game status, including turns and game outcomes.
- Improved Error Handling: Alerts users for invalid actions, such as entering an incorrect room code or attempting invalid moves.
-
User Flow:
- Creating a Room: Clicking the "Create Room" button sends a
'create' message to the server and waits for an opponent.
- Joining a Room: Entering a room code and clicking "Join Room" sends a
'join' message to the server to connect to the specified room.
- Gameplay: Once two players are in a room, the game starts. Players take turns clicking on cells to make moves.
- Restarting the Game: After a game concludes, players can click the "Restart" button to reset the game state.
-
Visual Feedback:
- Disabled Cells: Once a cell is clicked, it becomes disabled and changes appearance to indicate it's no longer interactable.
- Status Messages: Provide clear instructions and updates on the game state, such as whose turn it is or if the game has ended.
Additional Recommendations
-
Hosting the Web Server:
- Ensure that your WebSocket server (
server.py) and the web server serving game.html are properly hosted and accessible to your intended audience.
- If hosting both on the same machine, ensure that cross-origin requests are handled appropriately or serve both from the same origin.
-
Security Considerations:
- Validate Inputs: Always validate and sanitize inputs from clients to prevent malicious activities.
- Use Secure WebSockets (WSS): For production environments, consider using WSS to encrypt WebSocket traffic.
-
Scalability:
- For handling a large number of concurrent players and rooms, consider integrating more robust frameworks or deploying the server using scalable infrastructure.
-
Enhancements:
- Player Authentication: Implement user authentication to track players more reliably.
- Chat Feature: Allow players to communicate within their game rooms.
- Leaderboard: Maintain a leaderboard to track player statistics and achievements.
By implementing these changes, you’ll have a robust, scalable, and user-friendly multiplayer Tic Tac Toe game with a modern interface and efficient room-based matchmaking.