wirte online multiplayer js html css game game one file tic tac teo and write python…
- User
wirte online multiplayer js html css game game one file tic tac teo and write python script for game server
- Assistant
wirte online multiplayer js html css game game one file tic tac teo and write python script for game server
Creating an online multiplayer Tic-Tac-Toe game involves both frontend (HTML, CSS, JavaScript) and backend (Python) components. Below is a simple implementation where the frontend is contained within a single HTML file, and the backend Python script uses Flask and Flask-SocketIO to handle real-time communication between players.
This HTML file includes embedded CSS for styling and JavaScript for game logic and real-time communication using Socket.IO.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Online Multiplayer Tic-Tac-Toe</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#status {
margin-bottom: 20px;
font-size: 1.2em;
}
#board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 5px;
justify-content: center;
margin: 0 auto;
}
.cell {
width: 100px;
height: 100px;
background-color: #f2f2f2;
font-size: 2em;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.cell:hover {
background-color: #e6e6e6;
}
#restart {
margin-top: 20px;
padding: 10px 20px;
font-size: 1em;
}
</style>
</head>
<body>
<h1>Online Multiplayer Tic-Tac-Toe</h1>
<div id="status">Connecting to server...</div>
<div id="board">
<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" style="display:none;">Restart Game</button>
<!-- Include Socket.IO -->
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"
integrity="sha384-XuPaNlqGI3X0URP9CFi7uIQ7/Jxt10zVpd3JkLrZO45xvk6tSJ3BX7R8Jvj6xL0y"
crossorigin="anonymous"></script>
<script>
const socket = io();
const statusDiv = document.getElementById('status');
const cells = document.querySelectorAll('.cell');
const restartBtn = document.getElementById('restart');
let playerSymbol = '';
let myTurn = false;
let gameActive = false;
socket.on('connect', () => {
statusDiv.textContent = 'Connected. Waiting for opponent...';
});
socket.on('game_start', data => {
playerSymbol = data.symbol;
gameActive = true;
statusDiv.textContent = `Game started. You are '${playerSymbol}'. ${data.turn === playerSymbol ? "Your turn." : "Opponent's turn."}`;
myTurn = data.turn === playerSymbol;
});
socket.on('update', data => {
updateBoard(data.board);
if (data.winner) {
if (data.winner === 'draw') {
statusDiv.textContent = "It's a draw!";
} else if (data.winner === playerSymbol) {
statusDiv.textContent = "You win!";
} else {
statusDiv.textContent = "You lose!";
}
gameActive = false;
restartBtn.style.display = 'inline-block';
} else {
myTurn = data.turn === playerSymbol;
statusDiv.textContent = myTurn ? "Your turn." : "Opponent's turn.";
}
});
socket.on('opponent_left', () => {
statusDiv.textContent = "Opponent left the game.";
gameActive = false;
restartBtn.style.display = 'inline-block';
});
cells.forEach(cell => {
cell.addEventListener('click', () => {
if (!gameActive || !myTurn || cell.textContent !== '') return;
const index = cell.getAttribute('data-index');
socket.emit('make_move', { index: index });
});
});
restartBtn.addEventListener('click', () => {
location.reload();
});
function updateBoard(board) {
board.forEach((cellValue, index) => {
cells[index].textContent = cellValue;
});
}
</script>
</body>
</html>
game_start, update, and opponent_left to manage game state.The following Python script uses Flask and Flask-SocketIO to manage game sessions and handle real-time communication between players.
You can install the necessary packages using pip:
pip install flask flask-socketio eventlet
server.py):from flask import Flask, send_from_directory
from flask_socketio import SocketIO, emit, join_room, leave_room
import uuid
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins='*')
# Store waiting players and active game rooms
waiting_player = None
games = {}
# Helper function to check for a win
def check_winner(board):
win_conditions = [
[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 condition in win_conditions:
a, b, c = condition
if board[a] == board[b] == board[c] and board[a] != '':
return board[a]
if '' not in board:
return 'draw'
return None
@app.route('/')
def index():
return send_from_directory('.', 'index.html')
@socketio.on('connect')
def handle_connect():
global waiting_player
print(f"Client connected: {uuid.uuid4()}")
if waiting_player is None:
waiting_player = request.sid
emit('status', {'message': 'Waiting for an opponent...'})
else:
room = str(uuid.uuid4())
emit('game_start', {'symbol': 'X', 'turn': 'X'}, room=waiting_player)
emit('game_start', {'symbol': 'O', 'turn': 'X'}, room=request.sid)
games[room] = {
'players': [waiting_player, request.sid],
'board': [''] * 9,
'turn': 'X'
}
join_room(room, sid=waiting_player)
join_room(room, sid=request.sid)
waiting_player = None
@socketio.on('make_move')
def handle_make_move(data):
room = None
for r, g in games.items():
if request.sid in g['players']:
room = r
break
if room is None:
emit('status', {'message': 'No game found.'})
return
game = games[room]
board = game['board']
symbol = 'X' if game['players'][0] == request.sid else 'O'
if game['turn'] != symbol or board[int(data['index'])] != '':
return # Invalid move
board[int(data['index'])] = symbol
winner = check_winner(board)
if not winner:
game['turn'] = 'O' if game['turn'] == 'X' else 'X'
emit('update', {
'board': board,
'turn': game['turn'],
'winner': winner
}, room=room)
if winner:
# Clean up the game room
for player in game['players']:
leave_room(room, sid=player)
del games[room]
@socketio.on('disconnect')
def handle_disconnect():
global waiting_player
print('Client disconnected')
if waiting_player == request.sid:
waiting_player = None
else:
# Remove player from any game they were part of
for room, game in list(games.items()):
if request.sid in game['players']:
other_player = game['players'][0] if game['players'][1] == request.sid else game['players'][1]
emit('opponent_left', room=other_player)
leave_room(room, sid=other_player)
leave_room(room, sid=request.sid)
del games[room]
break
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)
Flask and Flask-SocketIO Setup:
index.html file when the root URL is accessed.Managing Players and Games:
waiting_player: Holds the Socket.IO session ID of a player waiting for an opponent.games: A dictionary mapping unique room IDs to game state, including players, board state, and current turn.Event Handlers:
connect: When a client connects, if there's no waiting player, they wait for an opponent. Otherwise, a new game starts between the two players.make_move: Handles a player's move, updates the game state, checks for a winner, and notifies both players.disconnect: Handles player disconnections by notifying the opponent and cleaning up the game state.Game Logic:
check_winner function determines if there's a winner or a draw after each move.Save the Frontend File:
index.html in your desired directory.Save the Server Script:
server.py in the same directory.Install Dependencies:
Ensure you have Python installed.
Install required packages using pip:
pip install flask flask-socketio eventlet
Run the Server:
Navigate to the directory containing server.py and index.html in your terminal.
Start the server by running:
python server.py
The server will start listening on http://0.0.0.0:5000.
Access the Game:
http://localhost:5000.Error Handling: This basic implementation lacks comprehensive error handling. In production, you should handle edge cases and potential errors gracefully.
Scalability: For multiple concurrent games, this setup should handle separate rooms efficiently. However, for large-scale deployment, consider more robust solutions and optimizations.
Security: Always ensure that the server is secure, especially if deploying publicly. Implement necessary security measures to prevent unauthorized access and other vulnerabilities.
User Experience: Enhance the frontend with better styling, animations, and user-friendly features to improve the gaming experience.
This setup provides a foundational online multiplayer Tic-Tac-Toe game. You can further expand and customize it based on your requirements.
Not yet included in a published release.