Sure! I've updated your Tic Tac Toe game to include the following features:
- Automatic Symbol Alternation: Each time the game is reset, the symbols (
X and O) alternate between the two players.
- Name System: Players can enter their names when creating or joining a room.
- Point System: The game now keeps track of wins for each player.
- Winning Line Highlight: When a player wins, the winning row, column, or diagonal is highlighted.
Below, I'll provide the modified code for both game.html and server.py with detailed explanations of the changes made.
game.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Multiplayer Tic Tac Toe</title>
<style>
/* Existing styles omitted for brevity */
/* Added styles for the scoreboard and winning cells */
#scoreboard {
display: none;
margin-bottom: 20px;
color: #ffffff;
text-align: center;
}
.win-cell {
background-color: #f1c40f; /* Gold color for the winning line */
color: #2c3e50; /* Dark text color for contrast */
}
</style>
</head>
<body>
<h1>Multiplayer Tic Tac Toe</h1>
<div id="room-interface">
<!-- Added input field for player name -->
<input type="text" id="name-input" placeholder="Enter Your Name" maxlength="20">
<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: #ffffff;">
Room Code: <span id="current-room-code"></span>
</div>
<!-- Added scoreboard to display player names, symbols, and points -->
<div id="scoreboard">
<div>Your Name: <span id="your-name"></span> (<span id="your-symbol"></span>) - Points: <span id="your-points">0</span></div>
<div>Opponent: <span id="opponent-name"></span> (<span id="opponent-symbol"></span>) - Points: <span id="opponent-points">0</span></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 nameInput = document.getElementById('name-input'); // New name 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');
// New elements for the scoreboard
const scoreboardDiv = document.getElementById('scoreboard');
const yourNameSpan = document.getElementById('your-name');
const yourSymbolSpan = document.getElementById('your-symbol');
const yourPointsSpan = document.getElementById('your-points');
const opponentNameSpan = document.getElementById('opponent-name');
const opponentSymbolSpan = document.getElementById('opponent-symbol');
const opponentPointsSpan = document.getElementById('opponent-points');
let socket;
let mySymbol;
let myTurn = false;
let gameActive = false;
let roomCode = null;
// Variables to store player names and points
let myName;
let opponentName;
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;
myName = message.your_name;
opponentName = message.opponent_name;
// Update scoreboard
yourNameSpan.textContent = myName;
yourSymbolSpan.textContent = mySymbol;
yourPointsSpan.textContent = message.your_points;
opponentNameSpan.textContent = opponentName;
opponentSymbolSpan.textContent = mySymbol === 'X' ? 'O' : 'X';
opponentPointsSpan.textContent = message.opponent_points;
scoreboardDiv.style.display = 'block';
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;
// Update points
if (message.your_points !== undefined) {
yourPointsSpan.textContent = message.your_points;
opponentPointsSpan.textContent = message.opponent_points;
}
// Highlight winning cells
if (message.winning_combination) {
highlightWinningCells(message.winning_combination);
}
break;
case 'reset':
resetGame();
if (message.symbol) {
mySymbol = message.symbol;
yourSymbolSpan.textContent = mySymbol;
opponentSymbolSpan.textContent = mySymbol === 'X' ? 'O' : 'X';
}
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';
scoreboardDiv.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 = opponentName + '\'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', 'symbol-placed');
}
}
function resetGame() {
cells.forEach(cell => {
cell.textContent = '';
cell.classList.remove('disabled', 'symbol-placed', 'win-cell'); // Remove win-cell class
});
restartButton.disabled = true;
statusDiv.textContent = 'Game reset. Waiting for opponent...';
myTurn = mySymbol === 'X';
gameActive = true;
updateStatus();
}
function highlightWinningCells(combination) {
combination.forEach(index => {
const cell = document.querySelector(`.cell[data-index='${index}']`);
if (cell) {
cell.classList.add('win-cell');
}
});
}
createRoomButton.addEventListener('click', () => {
const playerName = nameInput.value.trim();
if (playerName === '') {
alert('Please enter your name.');
return;
}
socket.send(JSON.stringify({ type: 'create', name: playerName }));
createRoomButton.disabled = true;
joinRoomButton.disabled = true;
roomCodeInput.disabled = true;
nameInput.disabled = true;
});
joinRoomButton.addEventListener('click', () => {
const code = roomCodeInput.value.trim().toUpperCase();
const playerName = nameInput.value.trim();
if (code.length !== 6) {
alert('Please enter a valid 6-character room code.');
return;
}
if (playerName === '') {
alert('Please enter your name.');
return;
}
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 in game.html:
- Name Input Field: Added an input field (
<input id="name-input">) for players to enter their names.
- Scoreboard: Introduced a scoreboard (
<div id="scoreboard">) to display player names, symbols, and points.
- Winning Line Highlight: Added CSS class
.win-cell to style the winning cells and a JavaScript function highlightWinningCells to apply this style.
- Symbol Alternation: Updated the client-side logic to handle symbol changes when the game resets, ensuring that symbols alternate between games.
- Points Update: Modified the client to update and display player points when receiving updates from the server.
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 Player:
def __init__(self, websocket, name):
self.websocket = websocket
self.name = name
self.symbol = None
self.points = 0
class Game:
def __init__(self, room_code, player1, player2):
self.room_code = room_code
self.players = [player1, player2]
# Assign symbols
player1.symbol = 'X'
player2.symbol = 'O'
self.board = [''] * 9
self.current_turn = player1
self.active = True
self.winning_combination = []
async def start(self):
"""Notify players that the game has started and assign symbols."""
start_msg_p1 = {
'type': 'start',
'symbol': self.players[0].symbol,
'room': self.room_code,
'your_name': self.players[0].name,
'opponent_name': self.players[1].name,
'your_points': self.players[0].points,
'opponent_points': self.players[1].points
}
start_msg_p2 = {
'type': 'start',
'symbol': self.players[1].symbol,
'room': self.room_code,
'your_name': self.players[1].name,
'opponent_name': self.players[0].name,
'your_points': self.players[1].points,
'opponent_points': self.players[0].points
}
await asyncio.gather(
self.players[0].websocket.send(json.dumps(start_msg_p1)),
self.players[1].websocket.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.current_turn.symbol
turn_msg = {'type': 'turn', 'symbol': current_symbol}
await asyncio.gather(
self.players[0].websocket.send(json.dumps(turn_msg)),
self.players[1].websocket.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]:
self.winning_combination = combo
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.websocket.send(json.dumps({'type': 'error', 'message': 'Not your turn.'}))
return
if self.board[index] != '':
await player.websocket.send(json.dumps({'type': 'error', 'message': 'Cell already occupied.'}))
return
symbol = player.symbol
self.board[index] = symbol
move_msg = {'type': 'move', 'index': index, 'symbol': symbol}
await asyncio.gather(
self.players[0].websocket.send(json.dumps(move_msg)),
self.players[1].websocket.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!'}
await asyncio.gather(
self.players[0].websocket.send(json.dumps(end_msg)),
self.players[1].websocket.send(json.dumps(end_msg))
)
else:
# Update points
winner = player
winner.points += 1
loser = self.players[0] if self.players[1] == winner else self.players[1]
end_msg_winner = {
'type': 'end',
'result': f'You win!',
'winning_combination': self.winning_combination,
'your_points': winner.points,
'opponent_points': loser.points
}
end_msg_loser = {
'type': 'end',
'result': f'{winner.name} wins!',
'winning_combination': self.winning_combination,
'your_points': loser.points,
'opponent_points': winner.points
}
await asyncio.gather(
winner.websocket.send(json.dumps(end_msg_winner)),
loser.websocket.send(json.dumps(end_msg_loser))
)
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
# Swap symbols
self.players.reverse()
self.players[0].symbol, self.players[1].symbol = self.players[1].symbol, self.players[0].symbol
# Decide who starts (alternate)
self.current_turn = self.players[0]
await asyncio.gather(
self.players[0].websocket.send(json.dumps({
'type': 'reset',
'symbol': self.players[0].symbol
})),
self.players[1].websocket.send(json.dumps({
'type': 'reset',
'symbol': self.players[1].symbol
}))
)
await self.start()
else:
# If game is active, do not allow reset
await player.websocket.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.websocket.send(json.dumps(end_msg))
# Clean up room
del rooms[self.room_code]
await asyncio.gather(
opponent.websocket.close(),
player.websocket.close()
)
async def handler(websocket, path):
try:
async for message in websocket:
data = json.loads(message)
if data['type'] == 'create':
# Create a new room
player_name = data.get('name', 'Player')
room_code = generate_room_code()
player = Player(websocket, player_name)
rooms[room_code] = {'players': [player], 'game': None}
await websocket.send(json.dumps({'type': 'created', 'room': room_code}))
print(f"Room {room_code} created by {player_name} ({websocket.remote_address})")
elif data['type'] == 'join':
# Join an existing room
room_code = data.get('room')
player_name = data.get('name', 'Player')
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:
player = Player(websocket, player_name)
rooms[room_code]['players'].append(player)
player1, player2 = rooms[room_code]['players']
game = Game(room_code, player1, player2)
rooms[room_code]['game'] = game
await game.start()
print(f"Player {player_name} joined room {room_code} from {websocket.remote_address}")
elif data['type'] == 'move':
# Handle a move
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:
# Find the player object
player = next((p for p in game.players if p.websocket == websocket), None)
if player:
await game.handle_move(player, 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
# Find the player object
player = next((p for p in game.players if p.websocket == websocket), None)
if player:
await game.handle_reset(player)
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 any(player.websocket == websocket for player in room['players']):
game = room.get('game')
player = next((p for p in room['players'] if p.websocket == websocket), None)
if game and player:
await game.handle_disconnect(player)
else:
# Room still has only one player
room['players'].remove(player)
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 in server.py:
- Player Class: Introduced a
Player class to store player-specific information like websocket, name, symbol, and points.
- Name Handling: Modified the
handler function to accept and store player names when they create or join a room.
- Game Class Modifications: Updated the
Game class to use Player instances, and included logic to send player names and points to clients.
- Point System: Implemented a point system where the winning player gains a point, and this information is sent to clients.
- Symbol Alternation: Modified the
handle_reset method to swap player symbols (X and O) when the game is reset.
- Winning Line Information: Updated the
check_winner method to store the winning combination, which is then sent to clients to highlight the winning line.
Additional Notes:
- Testing: Make sure to test the game thoroughly to confirm that all features work as expected.
- Error Handling: I've included basic error handling for invalid moves and unexpected conditions.
- Server Address: Replace
'ws://localhost:6789' in game.html with your server's actual address and port if it's running on a different host or port.
- Restart Logic: Only one player needs to click the "Restart" button to reset the game. The symbols will alternate automatically.
- User Interface: Feel free to enhance the UI further to improve the gaming experience.
Enjoy your enhanced Tic Tac Toe game!