206 lines
5.1 KiB
Plaintext
206 lines
5.1 KiB
Plaintext
To add a player that uses a client connected by a socket in your dominoes game, you'll need to integrate WebSockets or Socket.io to enable real-time communication between the server and the client. This allows players to interact with the game from their web browsers or other client applications.
|
||
|
||
Here’s a step-by-step guide to adding a socket-connected player to your game:
|
||
|
||
### 1. **Setup Socket.io on the Server**
|
||
|
||
Socket.io provides a straightforward way to handle real-time communication.
|
||
|
||
#### **Install Dependencies**
|
||
|
||
First, install the necessary dependencies:
|
||
|
||
```bash
|
||
npm install express socket.io
|
||
```
|
||
|
||
#### **Server Setup**
|
||
|
||
Create an Express server and integrate Socket.io.
|
||
|
||
**server.ts**:
|
||
```typescript
|
||
import express from 'express';
|
||
import http from 'http';
|
||
import { Server } from 'socket.io';
|
||
import { DominoesGame, Player, AIPlayer } from './dominoes-game'; // Adjust the path as needed
|
||
|
||
const app = express();
|
||
const server = http.createServer(app);
|
||
const io = new Server(server);
|
||
|
||
const port = 3000;
|
||
|
||
let game: DominoesGame;
|
||
|
||
app.get('/', (req, res) => {
|
||
res.send('Dominoes Game Server');
|
||
});
|
||
|
||
// Start the server
|
||
server.listen(port, () => {
|
||
console.log(`Server running on http://localhost:${port}`);
|
||
});
|
||
```
|
||
|
||
### 2. **Integrate Socket.io into the Game**
|
||
|
||
Modify the `DominoesGame` class to support socket-connected players.
|
||
|
||
**dominoes-game.ts**:
|
||
```typescript
|
||
import { Server } from 'socket.io';
|
||
|
||
interface Player {
|
||
id: string;
|
||
name: string;
|
||
hand: number[][];
|
||
isAI: boolean;
|
||
}
|
||
|
||
class DominoesGame {
|
||
players: Player[];
|
||
board: number[][];
|
||
remainingTiles: number[][];
|
||
currentPlayerIndex: number;
|
||
gameOver: boolean;
|
||
io: Server;
|
||
|
||
constructor(io: Server) {
|
||
this.players = [];
|
||
this.board = [];
|
||
this.remainingTiles = this.generateTiles();
|
||
this.currentPlayerIndex = 0;
|
||
this.gameOver = false;
|
||
this.io = io;
|
||
}
|
||
|
||
addPlayer(id: string, name: string, isAI: boolean = false) {
|
||
const player: Player = { id, name, hand: [], isAI };
|
||
this.players.push(player);
|
||
this.dealTiles(player);
|
||
this.io.emit('playerJoined', player);
|
||
}
|
||
|
||
// Other methods remain the same...
|
||
|
||
generateTiles(): number[][] {
|
||
const tiles: number[][] = [];
|
||
for (let i = 0; i <= 6; i++) {
|
||
for (let j = i; j <= 6; j++) {
|
||
tiles.push([i, j]);
|
||
}
|
||
}
|
||
return this.shuffle(tiles);
|
||
}
|
||
|
||
shuffle(array: any[]): any[] {
|
||
for (let i = array.length - 1; i > 0; i--) {
|
||
const j = Math.floor(Math.random() * (i + 1));
|
||
[array[i], array[j]] = [array[j], array[i]];
|
||
}
|
||
return array;
|
||
}
|
||
|
||
dealTiles(player: Player): void {
|
||
const tilesPerPlayer = 7;
|
||
for (let i = 0; i < tilesPerPlayer; i++) {
|
||
player.hand.push(this.remainingTiles.pop() as number[]);
|
||
}
|
||
}
|
||
}
|
||
|
||
export { DominoesGame, Player };
|
||
```
|
||
|
||
### 3. **Handle Socket Connections**
|
||
|
||
Update the server to handle connections and manage player interactions.
|
||
|
||
**server.ts**:
|
||
```typescript
|
||
let game = new DominoesGame(io);
|
||
|
||
io.on('connection', (socket) => {
|
||
console.log(`Player connected: ${socket.id}`);
|
||
|
||
socket.on('joinGame', (name) => {
|
||
game.addPlayer(socket.id, name);
|
||
io.emit('updateGame', game);
|
||
});
|
||
|
||
socket.on('playTile', (tile) => {
|
||
const player = game.players.find(p => p.id === socket.id);
|
||
if (player) {
|
||
if (game.playTile(game.players.indexOf(player), tile)) {
|
||
io.emit('updateGame', game);
|
||
} else {
|
||
socket.emit('invalidMove', tile);
|
||
}
|
||
}
|
||
});
|
||
|
||
socket.on('disconnect', () => {
|
||
console.log(`Player disconnected: ${socket.id}`);
|
||
game.players = game.players.filter(p => p.id !== socket.id);
|
||
io.emit('updateGame', game);
|
||
});
|
||
});
|
||
```
|
||
|
||
### 4. **Client Implementation**
|
||
|
||
Create a basic client to connect to the server and interact with the game.
|
||
|
||
**client.html**:
|
||
```html
|
||
<!DOCTYPE html>
|
||
<html>
|
||
<head>
|
||
<title>Dominoes Game</title>
|
||
</head>
|
||
<body>
|
||
<h1>Dominoes Game</h1>
|
||
<div id="game"></div>
|
||
|
||
<script src="/socket.io/socket.io.js"></script>
|
||
<script>
|
||
const socket = io();
|
||
|
||
socket.on('connect', () => {
|
||
const name = prompt("Enter your name:");
|
||
socket.emit('joinGame', name);
|
||
});
|
||
|
||
socket.on('updateGame', (game) => {
|
||
console.log('Game updated:', game);
|
||
// Update UI based on game state
|
||
});
|
||
|
||
socket.on('invalidMove', (tile) => {
|
||
alert(`Invalid move: ${tile}`);
|
||
});
|
||
|
||
// Example of playing a tile
|
||
function playTile(tile) {
|
||
socket.emit('playTile', tile);
|
||
}
|
||
</script>
|
||
</body>
|
||
</html>
|
||
```
|
||
|
||
### 5. **Testing and Debugging**
|
||
|
||
1. **Run the Server**: Start your server with `node server.js`.
|
||
2. **Access the Game**: Open multiple browser windows and connect to `http://localhost:3000`.
|
||
3. **Join Game**: Each client can join the game and start interacting.
|
||
4. **Play Tiles**: Test playing tiles and ensure the game state updates correctly for all clients.
|
||
|
||
### 6. **Enhancements**
|
||
|
||
1. **Game State Persistence**: Implement game state persistence using a database.
|
||
2. **Authentication**: Add user authentication to track player progress.
|
||
3. **AI Integration**: Allow the game to mix human and AI players.
|
||
|
||
By following these steps, you can effectively add a socket-connected player to your dominoes game, enabling real-time multiplayer interaction. |