以下を server.js として保存し、node server.js で起動してください。
// 必要: npm install ws
const WebSocket = require("ws");
const wss = new WebSocket.Server({ port: 8080 });
let players = [];
let gameState = null;
function createDeck() {
const suits = ["♠","♥","♦","♣"];
const ranks = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"];
let deck = [];
for (let s of suits) for (let r of ranks) deck.push({suit:s, rank:r});
return deck.sort(() => Math.random() - 0.5);
}
function startGame() {
const deck = createDeck();
gameState = {
hands: [
deck.splice(0,5),
deck.splice(0,5)
],
pot: 0,
turn: 0
};
}
wss.on("connection", ws => {
players.push(ws);
if (players.length === 2) {
startGame();
players.forEach((p,i)=>{
p.send(JSON.stringify({
type:"start",
hand: gameState.hands[i],
turn: gameState.turn
}));
});
}
ws.on("message", msg => {
const data = JSON.parse(msg);
if (data.type === "bet") {
gameState.pot += data.amount;
gameState.turn = 1 - gameState.turn;
players.forEach((p,i)=>{
p.send(JSON.stringify({
type:"update",
pot: gameState.pot,
turn: gameState.turn
}));
});
}
});
});