Implemented a lobby

This commit is contained in:
2026-02-10 07:52:16 +01:00
parent bd9db87ccb
commit 8fae0a6b84
2 changed files with 235 additions and 177 deletions

View File

@@ -4,91 +4,73 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Wolf & Schafe | Pro</title> <title>Wolf & Schafe | Online</title>
<style> <style>
:root { :root {
--bg: #f0f2f5; --bg: #f0f2f5;
--wolf: #e63946; --wolf: #e63946;
--wolf-light: #ff6b78; --wolf-light: #ff707a;
--sheep: #457b9d; --sheep: #457b9d;
--sheep-light: #7db0cf; --sheep-light: #8ecae6;
--black: #1d3557; --black: #1d3557;
--white: #ffffff; --white: #ffffff;
--green: #10b981; --green: #10b981;
} }
body { body {
font-family: 'Courier New', Courier, monospace; font-family: 'Courier New', monospace;
background: var(--bg); background: var(--bg);
color: var(--black); margin: 0;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
min-height: 100vh; min-height: 100vh;
margin: 0;
padding: 10px; padding: 10px;
box-sizing: border-box; box-sizing: border-box;
} }
.game-wrapper {
width: 100%;
max-width: 800px;
}
.main-card { .main-card {
background: var(--white); background: white;
border: 4px solid var(--black); border: 4px solid var(--black);
box-shadow: 8px 8px 0px var(--black); box-shadow: 8px 8px 0px var(--black);
padding: 1.5rem; padding: 1.5rem;
width: 100%;
max-width: 650px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 15px; gap: 15px;
position: relative;
}
.room-item {
display: flex;
justify-content: space-between;
padding: 12px;
border: 3px solid var(--black);
margin-bottom: 10px;
cursor: pointer;
font-weight: 900;
background: #fff;
box-shadow: 4px 4px 0px var(--black);
}
.room-item:hover {
background: #f8fafc;
transform: translate(-2px, -2px);
box-shadow: 6px 6px 0px var(--black);
}
.hidden {
display: none !important;
} }
.info-bar { .info-bar {
display: flex; display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between; justify-content: space-between;
align-items: center;
border: 3px solid var(--black); border: 3px solid var(--black);
padding: 10px; padding: 10px;
background: #f8fafc; background: #f8fafc;
gap: 10px;
}
.room-info {
display: flex;
align-items: center;
gap: 10px;
}
.room-tag {
font-size: 0.8rem;
font-weight: bold;
background: var(--black);
color: white;
padding: 4px 8px;
text-transform: uppercase;
}
/* Connection Indicator */
.pulse {
width: 10px;
height: 10px;
border-radius: 50%;
background: #94a3b8;
display: inline-block;
transition: background 0.3s;
}
.online {
background: var(--green);
box-shadow: 0 0 8px var(--green);
}
.offline {
background: var(--wolf);
box-shadow: 0 0 8px var(--wolf);
} }
.id-box { .id-box {
@@ -109,17 +91,46 @@
color: white; color: white;
} }
.board-container { /* Connection Dot */
.conn-dot {
display: inline-block;
width: 8px;
height: 8px;
background: #ccc;
border-radius: 50%;
margin-right: 5px;
}
.conn-online {
background: var(--green);
box-shadow: 0 0 5px var(--green);
animation: pulse 2s infinite;
}
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1;
}
}
.board-wrapper {
position: relative;
width: 100%; width: 100%;
aspect-ratio: 600 / 420;
border: 3px solid var(--black); border: 3px solid var(--black);
background: #fff; background: #fff;
touch-action: manipulation;
} }
svg { svg {
width: 100%; width: 100%;
height: 100%; height: auto;
display: block; display: block;
} }
@@ -131,44 +142,53 @@
.node-circle { .node-circle {
stroke: var(--black); stroke: var(--black);
stroke-width: 2.5; stroke-width: 2.5;
transition: all 0.15s ease; transition: 0.1s;
cursor: pointer; cursor: pointer;
} }
.empty {
fill: #fff;
}
.sheep {
fill: var(--sheep);
}
.wolf { .wolf {
fill: var(--wolf); fill: var(--wolf);
} }
.sheep {
fill: var(--sheep);
}
.empty {
fill: #fff;
}
.wolf.selected { .wolf.selected {
fill: var(--wolf-light); fill: var(--wolf-light) !important;
stroke-width: 4; stroke-width: 4;
} }
.sheep.selected { .sheep.selected {
fill: var(--sheep-light); fill: var(--sheep-light) !important;
stroke-width: 4; stroke-width: 4;
} }
.possible { .possible {
fill: #fff; fill: #fff;
stroke: var(--green); stroke: var(--green);
stroke-width: 3; stroke-width: 2.5;
stroke-dasharray: 4; stroke-dasharray: 4;
} }
.node-label { #overlay {
font-family: sans-serif; position: absolute;
font-size: 14px; top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.92);
z-index: 10;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
font-weight: 900; font-weight: 900;
pointer-events: none;
} }
.controls { .controls {
@@ -177,7 +197,7 @@
gap: 10px; gap: 10px;
} }
button { .btn {
border: 3px solid var(--black); border: 3px solid var(--black);
background: white; background: white;
padding: 12px 5px; padding: 12px 5px;
@@ -188,63 +208,58 @@
font-size: 0.8rem; font-size: 0.8rem;
} }
button:active { .btn:active {
box-shadow: 0px 0px 0px var(--black); box-shadow: 0px 0px 0px;
transform: translate(2px, 2px); transform: translate(2px, 2px);
} }
#exitBtn { .btn-green {
background: #fee2e2; background: var(--green) !important;
color: #991b1b; color: white;
}
@media (max-width: 600px) {
.main-card {
padding: 10px;
}
.info-bar {
flex-direction: column;
align-items: stretch;
text-align: center;
}
#status {
text-align: center !important;
}
.controls {
grid-template-columns: 1fr;
}
} }
</style> </style>
</head> </head>
<body> <body>
<div class="game-wrapper">
<div class="main-card"> <div id="lobby" class="main-card">
<h1 style="text-align: center; margin: 0; border-bottom: 4px solid var(--black); padding-bottom: 10px;">WOLF &
SCHAFE</h1>
<button class="btn btn-green" style="font-size: 1.1rem;" onclick="createRoom()">+ NEUES SPIEL</button>
<h3 style="margin: 15px 0 5px 0;">Offene Räume:</h3>
<div id="roomList">Suche Räume...</div>
</div>
<div id="game" class="main-card hidden">
<div class="info-bar"> <div class="info-bar">
<div class="room-info">
<div> <div>
<div class="room-tag">RAUM: <span id="codeDisplay">...</span> <span id="connCircle" <div style="font-size: 0.7rem; font-weight: 900; display: flex; align-items: center;">
class="pulse"></span></div> <span id="dot" class="conn-dot"></span> RAUM: <span id="roomCode">...</span>
</div>
<div id="idBadge" class="id-box">...</div> <div id="idBadge" class="id-box">...</div>
</div> </div>
<div id="status" style="text-align: right; font-weight: 900; line-height: 1.2;">...</div>
</div> </div>
<div id="status" style="text-align: right; font-weight: 900; line-height: 1.2;">Verbinde...</div>
<div class="board-wrapper">
<div id="overlay" class="hidden">
<div>WARTEN AUF GEGNER...</div>
<p style="font-size: 0.7rem; margin-top: 10px; padding: 0 10px;">Link kopieren und Freund einladen!</p>
</div> </div>
<div class="board-container"><svg viewBox="0 0 600 420" preserveAspectRatio="xMidYMid meet"></svg></div> <svg viewBox="0 0 600 420"></svg>
</div>
<div class="controls"> <div class="controls">
<button id="copyRoomBtn">Link</button> <button class="btn" id="copyBtn">Link Kopieren</button>
<button id="restartBtn">Swap & Reset</button> <button class="btn" onclick="ws.send(JSON.stringify({type:'restart'}))">Restart</button>
<button id="exitBtn">Beenden</button> <button class="btn" onclick="location.href='/'">Lobby</button>
</div>
</div> </div>
</div> </div>
<script> <script>
let sessionId = localStorage.getItem("game_session_id") || (Math.random().toString(36).substring(2)); let sessionId = localStorage.getItem("game_session_id") || Math.random().toString(36).substring(2);
localStorage.setItem("game_session_id", sessionId); localStorage.setItem("game_session_id", sessionId);
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
let roomId = params.get("room"); let roomId = params.get("room");
let ws, myRole, state, selected = null; let ws, myRole, state, selected = null;
@@ -258,38 +273,55 @@
const protocol = location.protocol === "https:" ? "wss" : "ws"; const protocol = location.protocol === "https:" ? "wss" : "ws";
ws = new WebSocket(`${protocol}://${location.host}?room=${roomId}&sessionId=${sessionId}`); ws = new WebSocket(`${protocol}://${location.host}?room=${roomId}&sessionId=${sessionId}`);
ws.onopen = () => { ws.onopen = () => document.getElementById("dot").classList.add("conn-online");
document.getElementById("connCircle").className = "pulse online"; ws.onclose = () => document.getElementById("dot").classList.remove("conn-online");
};
ws.onmessage = e => { ws.onmessage = e => {
const msg = JSON.parse(e.data); const msg = JSON.parse(e.data);
if (msg.type === "room_list") updateRoomList(msg.rooms);
if (msg.type === "init") { if (msg.type === "init") {
roomId = msg.roomId; roomId = msg.roomId;
document.getElementById("codeDisplay").innerText = roomId; document.getElementById("roomCode").innerText = roomId.toUpperCase();
window.history.replaceState({}, '', `?room=${roomId}`); window.history.replaceState({}, '', `?room=${roomId}`);
document.getElementById("lobby").classList.add("hidden");
document.getElementById("game").classList.remove("hidden");
} }
if (msg.type === "state") { if (msg.type === "state") {
state = msg.game; myRole = msg.yourRole; state = msg.game; myRole = msg.yourRole;
updateUI(); render(); document.getElementById("overlay").className = msg.onlineCount < 2 ? "" : "hidden";
render();
} }
}; };
ws.onclose = () => {
document.getElementById("connCircle").className = "pulse offline";
setTimeout(connect, 2000);
};
} }
function updateUI() { function updateRoomList(rooms) {
const badge = document.getElementById("idBadge"); const list = document.getElementById("roomList");
badge.innerText = myRole === "wolf" ? "WOLF" : "SCHAFE"; list.innerHTML = rooms.length === 0 ? "<p style='text-align:center'>Keine aktiven Räume.</p>" : "";
badge.className = `id-box is-${myRole}`; rooms.forEach(r => {
const statusEl = document.getElementById("status"); const div = document.createElement("div");
if (state.winner) statusEl.innerHTML = `SIEG: ${state.winner.toUpperCase()}!`; div.className = "room-item";
else statusEl.innerHTML = `${state.turn === myRole ? 'DEIN ZUG' : 'WARTEN...'}<br><small>ZUG ${state.moveCount}/40</small>`; div.innerHTML = `<span>RAUM: ${r.id.toUpperCase()}</span> <span>${r.players}/2</span>`;
div.onclick = () => { window.location.search = `?room=${r.id}`; };
list.appendChild(div);
});
} }
function createRoom() {
const id = Math.random().toString(36).substring(7);
window.location.search = `?room=${id}`;
}
document.getElementById("copyBtn").onclick = async () => {
try {
await navigator.clipboard.writeText(window.location.href);
alert("Link kopiert!");
} catch (err) {
const t = document.createElement("textarea"); t.value = window.location.href;
document.body.appendChild(t); t.select(); document.execCommand('copy');
document.body.removeChild(t); alert("Link kopiert!");
}
};
function render() { function render() {
const svg = document.querySelector("svg"); const svg = document.querySelector("svg");
svg.innerHTML = ""; svg.innerHTML = "";
@@ -300,34 +332,44 @@
l.setAttribute("class", "edge"); svg.appendChild(l); l.setAttribute("class", "edge"); svg.appendChild(l);
}); });
const badge = document.getElementById("idBadge");
badge.innerText = myRole === "wolf" ? "WOLF" : "SCHAFE";
badge.className = `id-box is-${myRole}`;
const statusEl = document.getElementById("status");
if (state.winner) statusEl.innerHTML = `SIEG: ${state.winner.toUpperCase()}!`;
else statusEl.innerHTML = `${state.turn === myRole ? 'DEIN ZUG' : 'WARTEN...'}<br><small>ZUG ${state.moveCount}/40</small>`;
for (let i = 0; i <= 10; i++) { for (let i = 0; i <= 10; i++) {
const [x, y] = pos[i]; const [x, y] = pos[i];
let type = state.wolf === i ? "wolf" : (state.sheep.includes(i) ? "sheep" : "empty"); const isWolf = state.wolf === i;
const isPossible = selected !== null && (myRole === "wolf" ? bWolf[selected] : bSheep[selected]).includes(i) && state.wolf !== i && !state.sheep.includes(i); const isSheep = state.sheep.includes(i);
const type = isWolf ? "wolf" : (isSheep ? "sheep" : "empty");
const isPossible = selected !== null && (myRole === "wolf" ? bWolf[selected] : bSheep[selected]).includes(i) && !isWolf && !isSheep;
const g = document.createElementNS("http://www.w3.org/2000/svg", "g"); const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
g.onclick = () => { g.onclick = () => {
if (state.turn !== myRole || state.winner) return; if (state.turn !== myRole || state.winner) return;
const isMine = (myRole === "wolf" && state.wolf === i) || (myRole === "sheep" && state.sheep.includes(i)); const isMine = (myRole === "wolf" && isWolf) || (myRole === "sheep" && isSheep);
if (selected === null) { if (isMine) selected = i; } if (isMine) selected = i;
else { if (isMine) selected = (selected === i ? null : i); else { if (ws.readyState === 1) ws.send(JSON.stringify({ from: selected, to: i })); selected = null; } } else if (isPossible) { ws.send(JSON.stringify({ from: selected, to: i })); selected = null; }
else selected = null;
render(); render();
}; };
const c = document.createElementNS("http://www.w3.org/2000/svg", "circle"); const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", x); c.setAttribute("cy", y); c.setAttribute("r", 25); c.setAttribute("cx", x); c.setAttribute("cy", y); c.setAttribute("r", 25);
c.setAttribute("class", `node-circle ${type} ${selected === i ? 'selected' : ''} ${isPossible ? 'possible' : ''}`); c.setAttribute("class", `node-circle ${type} ${selected === i ? 'selected' : ''} ${isPossible ? 'possible' : ''}`);
g.appendChild(c); g.appendChild(c);
const t = document.createElementNS("http://www.w3.org/2000/svg", "text"); const t = document.createElementNS("http://www.w3.org/2000/svg", "text");
t.setAttribute("x", x); t.setAttribute("y", y + 5); t.setAttribute("text-anchor", "middle"); t.setAttribute("x", x); t.setAttribute("y", y + 6); t.setAttribute("text-anchor", "middle");
t.setAttribute("class", "node-label"); t.setAttribute("fill", (type === "empty" ? "black" : "white")); t.setAttribute("style", "pointer-events:none; font-weight:900; font-family:sans-serif; font-size: 18px;");
t.setAttribute("fill", (type === "empty") ? "#000" : "#fff");
t.textContent = i; g.appendChild(t); t.textContent = i; g.appendChild(t);
svg.appendChild(g); svg.appendChild(g);
} }
} }
document.getElementById("restartBtn").onclick = () => { if (ws.readyState === 1) ws.send(JSON.stringify({ type: "restart" })); };
document.getElementById("copyRoomBtn").onclick = () => { navigator.clipboard.writeText(window.location.href); alert("Kopiert!"); };
document.getElementById("exitBtn").onclick = () => { if (confirm("Beenden?")) { if (ws.readyState === 1) ws.send(JSON.stringify({ type: "leave" })); window.location.href = window.location.pathname; } };
connect(); connect();
</script> </script>
</body> </body>

View File

@@ -14,82 +14,99 @@ const board_sheep = { 0: [1, 2, 3], 1: [2, 4, 5], 2: [1, 3, 5], 3: [2, 5, 6], 4:
const rooms = {}; const rooms = {};
function broadcast(roomId) { function getRoomList() {
const room = rooms[roomId]; return Object.keys(rooms).map(id => ({
if (!room) return; id,
room.players.forEach(p => { players: rooms[id].players.length,
if (p.ws && p.ws.readyState === WebSocket.OPEN) { turn: rooms[id].game.turn
p.ws.send(JSON.stringify({ type: "state", game: room.game, yourRole: p.role })); }));
}
});
} }
// Heartbeat: Check if clients are still alive every 30s function broadcastRoomList() {
const interval = setInterval(() => { const list = JSON.stringify({ type: "room_list", rooms: getRoomList() });
wss.clients.forEach(ws => { wss.clients.forEach(client => {
if (ws.isAlive === false) return ws.terminate(); if (client.readyState === WebSocket.OPEN && !client.roomId) {
ws.isAlive = false; client.send(list);
ws.ping(); }
}); });
}, 30000); }
wss.on("connection", (ws, req) => { wss.on("connection", (ws, req) => {
const urlParams = new URLSearchParams(req.url.split('?')[1]); const urlParams = new URLSearchParams(req.url.split('?')[1]);
let roomId = urlParams.get("room"); let roomId = urlParams.get("room");
let sessionId = urlParams.get("sessionId"); let sessionId = urlParams.get("sessionId");
ws.isAlive = true; if (!roomId || roomId === "null") {
ws.on('pong', () => ws.isAlive = true); ws.send(JSON.stringify({ type: "room_list", rooms: getRoomList() }));
return;
}
if (!roomId || !rooms[roomId]) { if (!rooms[roomId]) {
if (!roomId || roomId === "null") roomId = randomBytes(3).toString("hex");
rooms[roomId] = { rooms[roomId] = {
game: { wolf: 5, sheep: [0, 1, 3], turn: "sheep", moveCount: 0, winner: null }, game: { wolf: 5, sheep: [0, 1, 3], turn: "sheep", moveCount: 0, winner: null, lastMove: null },
players: [], players: [], nextFirstRole: "sheep"
nextFirstRole: "sheep"
}; };
} }
const room = rooms[roomId]; const room = rooms[roomId];
let player = room.players.find(p => p.sessionId === sessionId); ws.roomId = roomId;
let player = room.players.find(p => p.sessionId === sessionId);
if (!player && room.players.length >= 2) { if (!player && room.players.length >= 2) {
ws.send(JSON.stringify({ type: "full" })); ws.send(JSON.stringify({ type: "full" }));
ws.close();
return; return;
} }
if (player) { if (player) {
if (player.timeout) clearTimeout(player.timeout);
player.ws = ws; player.ws = ws;
} else { } else {
const role = room.players.length === 0 ? room.nextFirstRole : (room.nextFirstRole === "sheep" ? "wolf" : "sheep"); const role = room.players.length === 0 ? room.nextFirstRole : (room.nextFirstRole === "sheep" ? "wolf" : "sheep");
player = { ws, role, sessionId }; player = { ws, role, sessionId, timeout: null };
room.players.push(player); room.players.push(player);
} }
ws.send(JSON.stringify({ type: "init", role: player.role, roomId })); ws.send(JSON.stringify({ type: "init", role: player.role, roomId }));
broadcast(roomId); broadcastRoomList();
broadcastState(roomId);
ws.on("message", msg => { ws.on("message", msg => {
let data = JSON.parse(msg); let data = JSON.parse(msg);
if (data.type === "restart") { if (data.type === "restart") {
room.players.forEach(p => p.role = (p.role === "wolf" ? "sheep" : "wolf")); room.players.forEach(p => p.role = (p.role === "wolf" ? "sheep" : "wolf"));
room.nextFirstRole = room.nextFirstRole === "sheep" ? "wolf" : "sheep"; room.nextFirstRole = room.nextFirstRole === "sheep" ? "wolf" : "sheep";
room.game = { wolf: 5, sheep: [0, 1, 3], turn: "sheep", moveCount: 0, winner: null }; room.game = { wolf: 5, sheep: [0, 1, 3], turn: "sheep", moveCount: 0, winner: null, lastMove: null };
broadcast(roomId); broadcastState(roomId);
} else if (data.type === "leave") {
room.players = room.players.filter(p => p.sessionId !== sessionId);
if (room.players.length === 0) delete rooms[roomId];
} else if (data.from !== undefined && data.to !== undefined) { } else if (data.from !== undefined && data.to !== undefined) {
handleMove(roomId, player.role, data); handleMove(roomId, player.role, data);
} }
}); });
ws.on("close", () => { ws.on("close", () => {
// We keep the player in the room for a while to allow reconnects if (player) {
player.timeout = setTimeout(() => {
room.players = room.players.filter(p => p.sessionId !== sessionId);
if (room.players.length === 0) {
delete rooms[roomId];
}
broadcastRoomList();
broadcastState(roomId);
}, 1000);
}
}); });
}); });
function broadcastState(roomId) {
const room = rooms[roomId];
if (!room) return;
const online = room.players.filter(p => p.ws?.readyState === WebSocket.OPEN).length;
room.players.forEach(p => {
if (p.ws?.readyState === WebSocket.OPEN) {
p.ws.send(JSON.stringify({ type: "state", game: room.game, yourRole: p.role, onlineCount: online }));
}
});
}
function handleMove(roomId, role, { from, to }) { function handleMove(roomId, role, { from, to }) {
const room = rooms[roomId]; const room = rooms[roomId];
if (!room || room.game.winner || room.game.turn !== role) return; if (!room || room.game.winner || room.game.turn !== role) return;
@@ -101,18 +118,17 @@ function handleMove(roomId, role, { from, to }) {
else { game.sheep[game.sheep.indexOf(from)] = to; game.turn = "wolf"; } else { game.sheep[game.sheep.indexOf(from)] = to; game.turn = "wolf"; }
game.moveCount++; game.moveCount++;
game.lastMove = { from, to, role };
game.winner = checkWinConditions(game); game.winner = checkWinConditions(game);
broadcast(roomId); broadcastState(roomId);
} }
function checkWinConditions(game) { function checkWinConditions(game) {
if (game.wolf === 0) return "wolf"; if (game.wolf === 0) return "wolf";
if (game.moveCount >= 40) return "wolf"; if (game.moveCount >= 40) return "wolf";
const canWolfMove = board_wolf[game.wolf].some(to => !game.sheep.includes(to)); const canWolfMove = board_wolf[game.wolf].some(to => !game.sheep.includes(to));
const canSheepMove = game.sheep.some(from => board_sheep[from].some(to => to !== game.wolf && !game.sheep.includes(to)));
if (!canWolfMove) return "sheep"; if (!canWolfMove) return "sheep";
if (!canSheepMove && game.turn === "sheep") return "wolf";
return null; return null;
} }
server.listen(3030, () => console.log("Server running on port 3030")); server.listen(3030, () => console.log("Server running on 3030"));