To enhance your multiplayer Tic Tac Toe game with automatic symbol assignment, a naming system, and a point system, you'll need to make modifications to both your client (game.html) and server (server.py) code. Below is a step-by-step guide on how to achieve this:
1. Automatically Switch Symbols ('X' and 'O') Between Players
Server-Side (server.py):
- Modify the
Game class to keep track of which player had 'X' in the previous game and swap symbols for each new game.
class Game:
def __init__(self, room_code, player1, player2, names):
self.room_code = room_code
self.players = [player1, player2]
self.names = names # Store player names
self.scores = {player1: 0, player2: 0} # Initialize scores
self.last_starter = None # Keep track of who started last game
self.board = [''] * 9
self.current_turn = None
self.active = True
self.assign_symbols() # Assign symbols
def assign_symbols(self):
# Swap symbols between games
if self.last_starter == self.players[0]:
self.symbols = {self.players[0]: 'O', self.players[1]: 'X'}
self.current_turn = self.players[1]
else:
self.symbols = {self.players[0]: 'X', self.players[1]: 'O'}
self.current_turn = self.players[0]
self.last_starter = self.current_turn
- Update the
start method to call assign_symbols():
async def start(self):
"""Notify players that the game has started and assign symbols."""
self.assign_symbols() # Assign symbols at the start of the game
# Rest of the method remains the same
2. Add a Name System
Client-Side (game.html and JavaScript):
- HTML: Add an input field for the player to enter their name.
<div id="room-interface">
<input type="text" id="player-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>
- JavaScript: Modify event listeners to include the player's name when creating or joining a room.
createRoomButton.addEventListener('click', () => {
const playerName = document.getElementById('player-name-input').value.trim();
if (!playerName) {
alert('Please enter your name.');
return;
}
socket.send(JSON.stringify({ type: 'create', name: playerName }));
// Disable buttons and inputs as before
});
joinRoomButton.addEventListener('click', () => {
const code = roomCodeInput.value.trim().toUpperCase();
const playerName = document.getElementById('player-name-input').value.trim();
if (!playerName) {
alert('Please enter your name.');
return;
}
// Validate the room code as before
socket.send(JSON.stringify({ type: 'join', room: code, name: playerName }));
// Disable buttons and inputs as before
});
- JavaScript: Store and display the opponent's name and update status messages.
let opponentName = '';
let myName = '';
let myScore = 0;
let opponentScore = 0;
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
switch(message.type) {
case 'created':
// Handle created message
break;
case 'start':
mySymbol = message.symbol;
opponentName = message.opponentName;
myName = message.yourName;
myScore = message.yourScore;
opponentScore = message.opponentScore;
// Update UI to display names and scores
updateScoreBoard();
// Rest of the code
break;
case 'end':
// Update scores
myScore = message.yourScore;
opponentScore = message.opponentScore;
// Display the result with names
statusDiv.textContent = message.result;
updateScoreBoard();
// Enable restart button
break;
// Handle other message types
}
};
function updateScoreBoard() {
// Update the UI to display player names and scores
document.getElementById('score-board').textContent = `${myName} (${mySymbol}): ${myScore} - ${opponentName} (${mySymbol === 'X' ? 'O' : 'X'}): ${opponentScore}`;
}
- HTML: Add a scoreboard to display names and scores.
<div id="score-board" style="margin-bottom: 20px; font-size: 1.2em;"></div>
Server-Side (server.py):
- Store player names when they create or join a room.
async def handler(websocket, path):
# Inside the main handler function
if data['type'] == 'create':
player_name = data.get('name', 'Player 1')
room_code = generate_room_code()
rooms[room_code] = {'players': [websocket], 'names': {websocket: player_name}, 'game': None}
await websocket.send(json.dumps({'type': 'created', 'room': room_code}))
elif data['type'] == 'join':
room_code = data.get('room')
player_name = data.get('name', 'Player 2')
if room_code in rooms and len(rooms[room_code]['players']) == 1:
rooms[room_code]['players'].append(websocket)
rooms[room_code]['names'][websocket] = player_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()
else:
await websocket.send(json.dumps({'type': 'error', 'message': 'Cannot join the room.'}))
- Modify the
Game class to store player names and use them in messages.
async def start(self):
"""Notify players that the game has started and assign symbols."""
self.assign_symbols() # Assign symbols at the start of the game
# Prepare start messages with names and scores
start_msg_p1 = {
'type': 'start',
'symbol': self.symbols[self.players[0]],
'room': self.room_code,
'yourName': self.names[self.players[0]],
'opponentName': self.names[self.players[1]],
'yourScore': self.scores[self.players[0]],
'opponentScore': self.scores[self.players[1]]
}
start_msg_p2 = {
'type': 'start',
'symbol': self.symbols[self.players[1]],
'room': self.room_code,
'yourName': self.names[self.players[1]],
'opponentName': self.names[self.players[0]],
'yourScore': self.scores[self.players[1]],
'opponentScore': self.scores[self.players[0]]
}
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()
- Include names in the
end message and update scores.
async def handle_move(self, player, index):
# Inside the method, after determining the result
if result:
self.active = False
if result == 'Draw':
end_msg = {
'type': 'end',
'result': 'It\'s a draw!',
'yourScore': self.scores[player],
'opponentScore': self.scores[opponent]
}
else:
# Update scores
self.scores[player] += 1
winner_name = self.names[player]
end_msg = {
'type': 'end',
'result': f'{winner_name} wins!',
'yourScore': self.scores[player],
'opponentScore': self.scores[opponent]
}
await asyncio.gather(
self.players[0].send(json.dumps(end_msg)),
self.players[1].send(json.dumps(end_msg))
)
else:
# Switch turn and notify
self.current_turn = opponent
await self.notify_turn()
3. Add a Point System
Server-Side (server.py):
- Initialize a score dictionary in the
Game class.
class Game:
def __init__(self, room_code, player1, player2, names):
# Existing initialization
self.scores = {player1: 0, player2: 0} # Initialize player scores
- Update scores when a player wins in the
handle_move method (shown in the previous section).
Client-Side (JavaScript):
- Update the
end message handler to receive and display updated scores.
case 'end':
gameActive = false;
myScore = message.yourScore;
opponentScore = message.opponentScore;
statusDiv.textContent = message.result;
updateScoreBoard();
restartButton.disabled = false;
break;
- Use the
updateScoreBoard() function defined earlier to refresh scores in the UI.
Additional UI Updates
- Update the status messages to include player names and whose turn it is.
function updateStatus() {
if (!gameActive) return;
if (myTurn) {
statusDiv.textContent = `Your turn (${mySymbol})`;
} else {
statusDiv.textContent = `${opponentName}'s turn`;
}
}
- Modify the game board to disable clicks when it's not the player's turn.
cells.forEach(cell => {
cell.addEventListener('click', () => {
if (!gameActive || !myTurn || cell.textContent !== '') return;
// Rest of the code
});
});
// Optionally, visually indicate when it's not the player's turn
function updateBoardInteractivity() {
cells.forEach(cell => {
if (!gameActive || !myTurn || cell.textContent !== '') {
cell.classList.add('disabled');
} else {
cell.classList.remove('disabled');
}
});
}
// Call this function in updateStatus
function updateStatus() {
if (!gameActive) return;
if (myTurn) {
statusDiv.textContent = `Your turn (${mySymbol})`;
} else {
statusDiv.textContent = `${opponentName}'s turn`;
}
updateBoardInteractivity();
}
Summary
With these modifications, your game will:
- Automatically alternate symbols between 'X' and 'O' for each new game within the same room.
- Allow players to enter their names, which will be displayed during the game.
- Keep track of points (scores) for each player across multiple games in the same room.
- Display updated scores and player names on the UI.
Remember to test thoroughly to ensure all features work as expected. Also, consider edge cases, such as handling disconnections and ensuring data consistency.
Note on Server Deployment
Make sure to update the WebSocket URL in your client code (game.html) to point to the correct server address when deploying:
socket = new WebSocket('ws://your-server-address:6789');
Replace 'your-server-address' with your actual server's domain or IP address.
By following these steps, you'll enhance the user experience of your Tic Tac Toe game, making it more engaging and interactive.