game.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">…
- User
game.html
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #121212; /* Dark background */ display: flex; flex-direction: column; align-items: center; min-height: 100vh; padding: 20px; color: #ffffff; /* White text */ } h1 { margin-bottom: 20px; color: #ffffff; } /* 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; background-color: #2c3e50; color: #ecf0f1; border: 1px solid #34495e; border-radius: 5px; } #room-interface button { padding: 10px 20px; margin-top: 10px; background-color: #1abc9c; border: none; color: #ffffff; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; } #room-interface button:hover { background-color: #16a085; } /* Status Message */ #status { margin-bottom: 20px; font-size: 1.2em; color: #cccccc; } /* Game Grid */ #game { display: grid; grid-template-columns: repeat(3, 100px); grid-gap: 10px; margin-bottom: 20px; } .cell { width: 100px; height: 100px; background-color: #2c3e50; /* Dark cell background */ border: 2px solid #34495e; /* Slightly lighter border */ border-radius: 10px; font-size: 2.5em; color: #ecf0f1; /* Light cell text color */ display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease, box-shadow 0.3s ease; } .cell:hover { background-color: #3b5998; box-shadow: 0 0 10px rgba(59, 89, 152, 0.5); } .cell.disabled { cursor: not-allowed; background-color: #34495e; /* Dark background */ color: #7f8c8d; /* Muted text color */ } .symbol-placed { animation: pop-in 0.3s ease; } @keyframes pop-in { 0% { transform: scale(0.5); opacity: 0; } 100% { transform: scale(1); opacity: 1; } } /* Restart Button */ #restart { padding: 10px 20px; font-size: 1em; background-color: #e74c3c; border: none; color: #ffffff; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; } #restart:hover { background-color: #c0392b; } /* 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>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()
make it automatcly change x to o for each user and add name system and point system.
- Assistant
To enhance your Multiplayer Tic Tac Toe game with the following features:
- Automatic Symbol Assignment and Alternation: Automatically assign 'X' and 'O' to players and alternate the symbols in subsequent games.
- Name System: Allow players to enter their names when creating or joining a room.
- Point System: Keep track of each player's wins, losses, and draws.
Below are the updated versions of both
game.htmlandserver.pywith detailed explanations of the changes.
Updated
game.htmlKey Changes:
- Name Input Fields: Added input fields for players to enter their names when creating or joining a room.
- Display Player Names and Scores: Updated the UI to show each player's name and their current score.
- Symbol Alternation: Adjusted the logic to handle symbol alternation after each game.
<!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-color: #121212; /* Dark background */ display: flex; flex-direction: column; align-items: center; min-height: 100vh; padding: 20px; color: #ffffff; /* White text */ } h1 { margin-bottom: 20px; color: #ffffff; } /* Room Interface */ #room-interface { display: flex; flex-direction: column; align-items: center; margin-bottom: 20px; width: 300px; } #room-interface input { padding: 10px; margin: 5px 0; width: 100%; background-color: #2c3e50; color: #ecf0f1; border: 1px solid #34495e; border-radius: 5px; } #room-interface button { padding: 10px 20px; margin-top: 10px; background-color: #1abc9c; border: none; color: #ffffff; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; width: 100%; } #room-interface button:hover { background-color: #16a085; } /* Status Message */ #status { margin-bottom: 20px; font-size: 1.2em; color: #cccccc; text-align: center; } /* Game Grid */ #game { display: grid; grid-template-columns: repeat(3, 100px); grid-gap: 10px; margin-bottom: 20px; } .cell { width: 100px; height: 100px; background-color: #2c3e50; /* Dark cell background */ border: 2px solid #34495e; /* Slightly lighter border */ border-radius: 10px; font-size: 2.5em; color: #ecf0f1; /* Light cell text color */ display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background-color 0.3s ease, transform 0.1s ease, box-shadow 0.3s ease; } .cell:hover { background-color: #3b5998; box-shadow: 0 0 10px rgba(59, 89, 152, 0.5); } .cell.disabled { cursor: not-allowed; background-color: #34495e; /* Dark background */ color: #7f8c8d; /* Muted text color */ } .symbol-placed { animation: pop-in 0.3s ease; } @keyframes pop-in { 0% { transform: scale(0.5); opacity: 0; } 100% { transform: scale(1); opacity: 1; } } /* Restart Button */ #restart { padding: 10px 20px; font-size: 1em; background-color: #e74c3c; border: none; color: #ffffff; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; margin-bottom: 20px; } #restart:hover { background-color: #c0392b; } /* Player Info */ #player-info { margin-bottom: 20px; width: 300px; display: flex; justify-content: space-between; } .player { background-color: #2c3e50; padding: 10px; border-radius: 5px; width: 48%; text-align: center; } .player h2 { margin-bottom: 10px; font-size: 1.2em; } .player p { margin: 5px 0; font-size: 1em; } /* 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; } #player-info { width: 100%; flex-direction: column; align-items: center; } .player { width: 80%; margin-bottom: 10px; } } </style> </head> <body> <h1>Multiplayer Tic Tac Toe</h1> <div id="room-interface"> <input type="text" id="player-name" placeholder="Enter Your Name" maxlength="20"> <button id="create-room">Create Room</button> <div style="margin: 10px 0; font-weight: bold; color: #ffffff;">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: #ffffff;"> Room Code: <span id="current-room-code"></span> </div> <div id="player-info" style="display: none;"> <div class="player"> <h2 id="player1-name">Player 1</h2> <p>Wins: <span id="player1-wins">0</span></p> <p>Losses: <span id="player1-losses">0</span></p> <p>Draws: <span id="player1-draws">0</span></p> </div> <div class="player"> <h2 id="player2-name">Player 2</h2> <p>Wins: <span id="player2-wins">0</span></p> <p>Losses: <span id="player2-losses">0</span></p> <p>Draws: <span id="player2-draws">0</span></p> </div> </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'); const playerInfoDiv = document.getElementById('player-info'); const player1Name = document.getElementById('player1-name'); const player2Name = document.getElementById('player2-name'); const player1Wins = document.getElementById('player1-wins'); const player1Losses = document.getElementById('player1-losses'); const player1Draws = document.getElementById('player1-draws'); const player2Wins = document.getElementById('player2-wins'); const player2Losses = document.getElementById('player2-losses'); const player2Draws = document.getElementById('player2-draws'); let socket; let mySymbol; let myTurn = false; let gameActive = false; let roomCode = null; let playerName = ""; let opponentName = ""; let scores = { player1: { wins: 0, losses: 0, draws: 0 }, player2: { wins: 0, losses: 0, draws: 0 } }; 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'; playerInfoDiv.style.display = 'none'; break; case 'start': handleStart(message); break; case 'turn': handleTurn(message); break; case 'move': updateBoard(message.index, message.symbol); break; case 'end': handleEnd(message); break; case 'reset': resetGame(); break; case 'error': alert(message.message); createRoomButton.disabled = false; joinRoomButton.disabled = false; roomCodeInput.disabled = false; break; case 'players_info': updatePlayerInfo(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'; playerInfoDiv.style.display = 'none'; }; socket.onerror = (error) => { console.error('WebSocket error:', error); }; } function handleStart(message) { mySymbol = message.symbol; roomCode = message.room; currentRoomCodeSpan.textContent = roomCode; currentRoomDiv.style.display = 'block'; gameDiv.style.display = 'grid'; playerInfoDiv.style.display = 'flex'; gameActive = true; myTurn = mySymbol === 'X'; // X always starts playerName = message.names[mySymbol].name; opponentName = message.names[mySymbol === 'X' ? 'O' : 'X'].name; player1Name.textContent = message.names['X'].name; player2Name.textContent = message.names['O'].name; updateStatus(); } function handleTurn(message) { const symbol = message.symbol; myTurn = (symbol === mySymbol); updateStatus(); } function updatePlayerInfo(message) { // Update point scores scores = message.scores; player1Wins.textContent = scores.player1.wins; player1Losses.textContent = scores.player1.losses; player1Draws.textContent = scores.player1.draws; player2Wins.textContent = scores.player2.wins; player2Losses.textContent = scores.player2.losses; player2Draws.textContent = scores.player2.draws; } function updateStatus() { if (!gameActive) return; if (myTurn) { statusDiv.textContent = `Your turn (${mySymbol})`; } else { statusDiv.textContent = `Opponent's turn (${mySymbol === 'X' ? 'O' : 'X'})`; } } function updateBoard(index, symbol) { const cell = document.querySelector(`.cell[data-index='${index}']`); if (cell && cell.textContent === '') { cell.textContent = symbol; cell.classList.add('disabled', 'symbol-placed'); } } function resetGame() { cells.forEach(cell => { cell.textContent = ''; cell.classList.remove('disabled', 'symbol-placed'); }); restartButton.disabled = true; statusDiv.textContent = 'Game reset. Waiting for opponent...'; myTurn = mySymbol === 'X'; gameActive = true; updateStatus(); } createRoomButton.addEventListener('click', () => { const nameInput = document.getElementById('player-name'); const name = nameInput.value.trim(); if (name === "") { alert('Please enter your name.'); return; } playerName = name; socket.send(JSON.stringify({ type: 'create', name: playerName })); createRoomButton.disabled = true; joinRoomButton.disabled = true; roomCodeInput.disabled = true; nameInput.disabled = true; }); joinRoomButton.addEventListener('click', () => { const nameInput = document.getElementById('player-name'); const name = nameInput.value.trim(); if (name === "") { alert('Please enter your name.'); return; } const code = roomCodeInput.value.trim().toUpperCase(); if (code.length !== 6) { alert('Please enter a valid 6-character room code.'); return; } playerName = name; socket.send(JSON.stringify({ type: 'join', room: code, name: playerName })); createRoomButton.disabled = true; joinRoomButton.disabled = true; roomCodeInput.disabled = true; nameInput.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', 'symbol-placed'); 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:
-
Name Input Field:
- Added an input field with
id="player-name"for players to enter their names. - Modified the event listeners for the "Create Room" and "Join Room" buttons to send the player's name to the server.
- Added an input field with
-
Player Information Display:
- Added a
#player-infodiv that displays both players' names and their win/loss/draw statistics. - The UI updates dynamically based on server messages.
- Added a
-
Symbol Alternation:
- The server now alternates the symbols after each game, and the client adjusts accordingly.
-
Point System:
- The client updates the displayed scores (
wins,losses, anddraws) based on messages received from the server.
- The client updates the displayed scores (
Updated
server.pyKey Changes:
- Name Handling: Modified the server to handle player names when creating or joining rooms.
- Point Tracking: Added a point system to track wins, losses, and draws for each player.
- Symbol Alternation: Implemented symbol alternation for each new game within a room.
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, names): self.room_code = room_code self.players = [player1, player2] self.symbols = {} self.names = names # Dictionary with player WebSocket as key and name as value self.board = [''] * 9 self.current_turn = None self.active = True self.scores = { 'player1': {'wins': 0, 'losses': 0, 'draws': 0}, 'player2': {'wins': 0, 'losses': 0, 'draws': 0} } self.symbol_order = ['X', 'O'] # To alternate symbols async def start(self): """Notify players that the game has started and assign symbols.""" # Assign symbols based on symbol_order self.symbols[self.players[0]] = self.symbol_order[0] self.symbols[self.players[1]] = self.symbol_order[1] # Notify players start_msg_p1 = { 'type': 'start', 'symbol': self.symbols[self.players[0]], 'room': self.room_code, 'names': { 'X': self.names[self.players[0]], 'O': self.names[self.players[1]] } } start_msg_p2 = { 'type': 'start', 'symbol': self.symbols[self.players[1]], 'room': self.room_code, 'names': { 'X': self.names[self.players[0]], 'O': self.names[self.players[1]] } } await asyncio.gather( self.players[0].send(json.dumps(start_msg_p1)), self.players[1].send(json.dumps(start_msg_p2)) ) # Notify players of initial scores await self.send_player_info() # Start with the first symbol in symbol_order self.current_turn = self.players[0] await self.notify_turn() async def send_player_info(self): """Send current scores to both players.""" info_msg = { 'type': 'players_info', 'scores': self.scores } await asyncio.gather( self.players[0].send(json.dumps(info_msg)), self.players[1].send(json.dumps(info_msg)) ) 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!'} # Update scores for draw self.scores['player1']['draws'] += 1 self.scores['player2']['draws'] += 1 else: # Determine winner and loser winner = None loser = None for p, s in self.symbols.items(): if s == result: winner = p else: loser = p end_msg = {'type': 'end', 'result': f'{self.names[winner]} wins!'} # Update scores if winner and loser: # Determine player1 and player2 if self.players[0] == winner: self.scores['player1']['wins'] += 1 self.scores['player2']['losses'] += 1 else: self.scores['player2']['wins'] += 1 self.scores['player1']['losses'] += 1 await asyncio.gather( self.players[0].send(json.dumps(end_msg)), self.players[1].send(json.dumps(end_msg)), self.send_player_info() ) 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 # Alternate symbols for next game self.symbol_order = self.symbol_order[::-1] self.symbols[self.players[0]] = self.symbol_order[0] self.symbols[self.players[1]] = self.symbol_order[1] reset_msg_p1 = { 'type': 'start', 'symbol': self.symbols[self.players[0]], 'room': self.room_code, 'names': { 'X': self.names[self.players[0]], 'O': self.names[self.players[1]] } } reset_msg_p2 = { 'type': 'start', 'symbol': self.symbols[self.players[1]], 'room': self.room_code, 'names': { 'X': self.names[self.players[0]], 'O': self.names[self.players[1]] } } await asyncio.gather( self.players[0].send(json.dumps(reset_msg_p1)), self.players[1].send(json.dumps(reset_msg_p2)) ) await self.send_player_info() # Start with the first symbol in the new symbol_order self.current_turn = self.players[0] await self.notify_turn() 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 if self.room_code in rooms: 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 along with their name. - 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, 'names': {websocket: data.get('name', 'Player 1')}} await websocket.send(json.dumps({'type': 'created', 'room': room_code})) print(f"Room {room_code} created by {websocket.remote_address} with name {data.get('name', 'Player 1')}") elif data['type'] == 'join': # Join an existing room room_code = data.get('room') name = data.get('name', 'Player 2') 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) rooms[room_code]['names'][websocket] = name player1, player2 = rooms[room_code]['players'] names = rooms[room_code]['names'] game = Game(room_code, player1, player2, names) rooms[room_code]['game'] = game await game.start() print(f"Player joined room {room_code} from {websocket.remote_address} with name {name}") 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:
-
Name Handling:
- Client Message: The server now expects a
namefield in thecreateandjoinmessages. - Game Initialization: The
Gameclass now takes anamesdictionary to map each player’s WebSocket to their name. - Start Message: When the game starts, the server sends each player their assigned symbol and both players' names.
- Client Message: The server now expects a
-
Point Tracking:
- Scores Dictionary: Each game instance maintains a
scoresdictionary to track wins, losses, and draws for both players. - Updating Scores: After each game ends, the server updates the scores based on the result (win, loss, or draw) and sends the updated scores to both players.
- Player Info Message: Introduced a
players_infomessage type to send current scores to clients.
- Scores Dictionary: Each game instance maintains a
-
Symbol Alternation:
- Symbol Order: Introduced
symbol_orderin theGameclass to manage symbol assignment (XandO). - Alternate Symbols: After each game reset, the symbols are alternated by reversing the
symbol_orderlist. - Reset Handling: Upon game reset, symbols are reassigned according to the new
symbol_order.
- Symbol Order: Introduced
-
Error Handling:
- Name Validation: Ensures that players provide a name when creating or joining a room.
- Game Found Check: Validates whether the game exists before processing moves or reset requests.
-
Logging:
- Console Logs: Enhanced console logs to include player names and actions for easier debugging and tracking.
Summary
With these updates:
- Players can enter their names when creating or joining a room.
- Symbols (
XandO) are automatically assigned and alternated in consecutive games. - Scores for each player (wins, losses, draws) are tracked and displayed in real-time.
- The UI reflects these changes, providing a more engaging and personalized experience.
Make sure to run the updated
server.pyand open the modifiedgame.htmlin your browsers to enjoy the enhanced Multiplayer Tic Tac Toe game!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.