feat: Gebietseroberung Multiplayer-Spiel

This commit is contained in:
2026-06-25 23:22:25 +02:00
parent 580b49a0a1
commit 7e19b2fe7f
7 changed files with 714 additions and 2 deletions

View File

@@ -0,0 +1,437 @@
import { useState, useEffect, useCallback } from 'react';
import { api, S } from '../lib.js';
const GRID = 20;
const OWNER_COLOR = '#4ecdc4';
const OPP_COLOR = '#ff6b9d';
const NEUTRAL_COLOR = 'rgba(255,255,255,0.06)';
const HOVER_COLOR = 'rgba(255,255,255,0.18)';
// ── Spielerklärung ────────────────────────────────────────────────────────────
function HelpModal({ onClose }) {
return (
<div style={{
position:'fixed', inset:0, background:'rgba(0,0,0,0.75)',
display:'flex', alignItems:'center', justifyContent:'center', zIndex:1000,
padding:20,
}}>
<div style={{ ...S.card, maxWidth:440, width:'100%', position:'relative' }}>
<div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
<span style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:15, fontWeight:700 }}>
🗺 Wie funktioniert's?
</span>
<button onClick={onClose} style={{ ...S.btn('#ff6b9d', true) }}>✕ Schließen</button>
</div>
<div style={{ color:'rgba(255,255,255,0.75)', fontSize:13, lineHeight:1.8, fontFamily:'monospace' }}>
<p style={{ marginTop:0 }}>
<strong style={{ color:OWNER_COLOR }}>Dein Ziel:</strong> Am Ende mehr Felder als dein Gegner besitzen.
</p>
<p>
<strong style={{ color:'#fff' }}>So geht's:</strong><br/>
Jeder Spieler startet in einer Ecke des 20×20 Rasters mit einem Startfeld.
Abwechselnd wählt jeder eine <strong style={{ color:'rgba(255,255,255,0.9)' }}>neutrale (graue) Zelle</strong>,
die direkt an sein eigenes Gebiet grenzt oben, unten, links oder rechts.
Diese Zelle gehört dann ihm.
</p>
<p>
<strong style={{ color:'#fff' }}>Taktik:</strong><br/>
Breite dich schnell aus aber pass auf: Wenn du deinen Gegner
<strong style={{ color:OPP_COLOR }}> einmauerst</strong>, kann er nicht mehr wachsen.
Blockieren ist genauso wichtig wie Expandieren!
</p>
<p>
<strong style={{ color:'#fff' }}>Ende:</strong><br/>
Wenn keine neutralen Felder mehr erreichbar sind, gewinnt wer
mehr Felder besitzt. Du bekommst eine <strong>Pushover-Benachrichtigung</strong>,
wenn du dran bist.
</p>
<div style={{ background:'rgba(255,255,255,0.04)', borderRadius:8, padding:'10px 14px', marginTop:8, border:'1px solid rgba(255,255,255,0.08)' }}>
💡 <em>Klicke auf ein leuchtendes Feld um deinen Zug zu machen. Nur Felder neben deinem Gebiet sind wählbar.</em>
</div>
</div>
</div>
</div>
);
}
// ── Neues Spiel Modal ─────────────────────────────────────────────────────────
function NewGameModal({ onClose, onCreated, toast }) {
const [users, setUsers] = useState([]);
const [oppId, setOppId] = useState('');
const [loading, setLoading] = useState(false);
useEffect(() => {
api('/tools/gebietseroberung/users').then(setUsers).catch(() => {});
}, []);
const create = async () => {
if (!oppId) return;
setLoading(true);
try {
const res = await api('/tools/gebietseroberung', { body: { opponent_id: Number(oppId) } });
toast('Spiel erstellt! Dein Gegner wurde benachrichtigt 🗺️');
onCreated(res.id);
} catch(e) {
toast(e.message || 'Fehler beim Erstellen', 'error');
} finally { setLoading(false); }
};
return (
<div style={{
position:'fixed', inset:0, background:'rgba(0,0,0,0.75)',
display:'flex', alignItems:'center', justifyContent:'center', zIndex:1000, padding:20,
}}>
<div style={{ ...S.card, maxWidth:360, width:'100%' }}>
<div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
<span style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:14, fontWeight:700 }}>
Neues Spiel
</span>
<button onClick={onClose} style={S.btn('#666666', true)}></button>
</div>
<label style={{ ...S.head, display:'block', marginBottom:6 }}>GEGNER WÄHLEN</label>
<select
value={oppId}
onChange={e => setOppId(e.target.value)}
style={{ ...S.inp, marginBottom:16 }}
>
<option value=''>-- Benutzer wählen --</option>
{users.map(u => <option key={u.id} value={u.id}>{u.username}</option>)}
</select>
<div style={{ display:'flex', gap:8 }}>
<button onClick={onClose} style={{ ...S.btn('#666666'), flex:1 }}>Abbrechen</button>
<button onClick={create} disabled={!oppId || loading} style={{ ...S.btn('#4ecdc4'), flex:1 }}>
{loading ? 'Erstelle…' : 'Spiel starten'}
</button>
</div>
</div>
</div>
);
}
// ── Spielfeld ─────────────────────────────────────────────────────────────────
function GameBoard({ game, myId, onMove, toast }) {
const [hover, setHover] = useState(null);
const [moving, setMoving] = useState(false);
const grid = JSON.parse(game.grid);
const isMyTurn = game.current_turn === myId;
const opponent = game.owner_id === myId ? game.opponent_id : game.owner_id;
const myColor = game.owner_id === myId ? OWNER_COLOR : OPP_COLOR;
const oppColor = game.owner_id === myId ? OPP_COLOR : OWNER_COLOR;
const isAdjacent = (r, c) => {
const dirs = [[-1,0],[1,0],[0,-1],[0,1]];
return dirs.some(([dr,dc]) => {
const nr = r+dr, nc = c+dc;
return nr>=0 && nr<GRID && nc>=0 && nc<GRID && grid[nr][nc] === myId;
});
};
const canClick = (r, c) => isMyTurn && game.status === 'active' && grid[r][c] === 0 && isAdjacent(r, c);
const handleClick = async (r, c) => {
if (!canClick(r, c) || moving) return;
setMoving(true);
try {
await onMove(r, c);
} finally { setMoving(false); }
};
const myCount = grid.flat().filter(v => v === myId).length;
const oppCount = grid.flat().filter(v => v === opponent).length;
const neutral = grid.flat().filter(v => v === 0).length;
// Gewinner-Banner
let banner = null;
if (game.status === 'finished') {
if (!game.winner_id) {
banner = { text: 'Unentschieden! 🤝', color: '#ffe66d' };
} else if (game.winner_id === myId) {
banner = { text: 'Du hast gewonnen! 🎉', color: '#4ecdc4' };
} else {
banner = { text: 'Du hast verloren.', color: '#ff6b9d' };
}
}
// Grid-Zellengröße responsiv
const isMob = window.innerWidth < 600;
const cellSize = isMob ? Math.floor((window.innerWidth - 48) / GRID) : 24;
return (
<div>
{/* Status-Leiste */}
<div style={{ display:'flex', gap:10, alignItems:'center', marginBottom:12, flexWrap:'wrap' }}>
<div style={{ ...S.card, padding:'8px 14px', flex:1, minWidth:120 }}>
<div style={{ color:myColor, fontFamily:'monospace', fontSize:11, marginBottom:2 }}>DU</div>
<div style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:20, fontWeight:700 }}>{myCount}</div>
</div>
<div style={{ textAlign:'center', color:'rgba(255,255,255,0.4)', fontFamily:'monospace', fontSize:11 }}>
{neutral} neutral
</div>
<div style={{ ...S.card, padding:'8px 14px', flex:1, minWidth:120, textAlign:'right' }}>
<div style={{ color:oppColor, fontFamily:'monospace', fontSize:11, marginBottom:2 }}>
{game.owner_id === myId ? game.opp_name : game.owner_name}
</div>
<div style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:20, fontWeight:700 }}>{oppCount}</div>
</div>
</div>
{/* Gewinner-Banner */}
{banner && (
<div style={{
background:`${banner.color}22`, border:`1px solid ${banner.color}55`,
borderRadius:8, padding:'10px 14px', marginBottom:12,
color:banner.color, fontFamily:'Space Mono,monospace', fontSize:14,
textAlign:'center', fontWeight:700,
}}>
{banner.text}
</div>
)}
{/* Zug-Hinweis */}
{game.status === 'active' && (
<div style={{
color: isMyTurn ? myColor : 'rgba(255,255,255,0.4)',
fontFamily:'monospace', fontSize:11, marginBottom:10, textAlign:'center',
}}>
{isMyTurn ? (moving ? 'Zug wird gespeichert…' : '▶ Dein Zug — klicke ein angrenzendes Feld') : '⏳ Warte auf Gegner…'}
</div>
)}
{/* Grid */}
<div style={{
display:'grid',
gridTemplateColumns:`repeat(${GRID}, ${cellSize}px)`,
gap:1,
background:'rgba(255,255,255,0.04)',
borderRadius:8,
padding:4,
overflow:'auto',
maxWidth:'100%',
}}>
{grid.map((row, r) => row.map((cell, c) => {
const key = `${r}-${c}`;
const clickable = canClick(r, c);
const isHovered = hover === key && clickable;
let bg = NEUTRAL_COLOR;
if (cell === myId) bg = `${myColor}55`;
if (cell === opponent) bg = `${oppColor}55`;
if (isHovered) bg = HOVER_COLOR;
if (clickable && !isHovered) bg = `${myColor}25`;
return (
<div
key={key}
onClick={() => handleClick(r, c)}
onMouseEnter={() => setHover(key)}
onMouseLeave={() => setHover(null)}
style={{
width: cellSize, height: cellSize,
background: bg,
borderRadius: 2,
cursor: clickable ? 'pointer' : 'default',
transition: 'background 0.1s',
boxSizing:'border-box',
border: clickable ? `1px solid ${myColor}66` : '1px solid transparent',
}}
/>
);
}))}
</div>
</div>
);
}
// ── Spielliste ────────────────────────────────────────────────────────────────
function GameList({ games, myId, onSelect, onNew }) {
const active = games.filter(g => g.status === 'active');
const finished = games.filter(g => g.status === 'finished');
const GameRow = ({ g }) => {
const isMyTurn = g.status === 'active' && g.current_turn === myId;
const opp = g.owner_id === myId ? g.opp_name : g.owner_name;
const grid = JSON.parse(g.grid);
const myCount = grid.flat().filter(v => v === myId).length;
const oppCount = grid.flat().filter(v => v !== myId && v !== 0).length;
let result = null;
if (g.status === 'finished') {
if (!g.winner_id) result = { label:'Unentschieden', color:'#ffe66d' };
else if (g.winner_id === myId) result = { label:'Gewonnen 🎉', color:'#4ecdc4' };
else result = { label:'Verloren', color:'#ff6b9d' };
}
return (
<button
onClick={() => onSelect(g.id)}
style={{
...S.card, width:'100%', textAlign:'left', cursor:'pointer',
padding:'12px 14px', marginBottom:8, display:'flex',
alignItems:'center', gap:12, border: isMyTurn
? '1px solid rgba(78,205,196,0.4)'
: '1px solid rgba(255,255,255,0.07)',
}}
>
<div style={{ flex:1 }}>
<div style={{ color:'#fff', fontFamily:'monospace', fontSize:13, marginBottom:3 }}>
{isMyTurn && <span style={{ color:'#4ecdc4', marginRight:6 }}></span>}
vs <strong>{opp}</strong>
</div>
<div style={{ color:'rgba(255,255,255,0.4)', fontSize:11, fontFamily:'monospace' }}>
{myCount} : {oppCount} Felder
</div>
</div>
{result
? <span style={{ color:result.color, fontSize:11, fontFamily:'monospace' }}>{result.label}</span>
: <span style={{ color: isMyTurn ? '#4ecdc4' : 'rgba(255,255,255,0.3)', fontSize:11, fontFamily:'monospace' }}>
{isMyTurn ? 'Du bist dran' : 'Gegner dran'}
</span>
}
</button>
);
};
return (
<div>
<button onClick={onNew} style={{ ...S.btn('#4ecdc4'), marginBottom:20, width:'100%' }}>
+ Neues Spiel starten
</button>
{active.length > 0 && (
<>
<div style={{ ...S.head, marginBottom:8 }}>LAUFENDE SPIELE ({active.length})</div>
{active.map(g => <GameRow key={g.id} g={g} />)}
</>
)}
{finished.length > 0 && (
<>
<div style={{ ...S.head, marginTop:16, marginBottom:8 }}>BEENDETE SPIELE</div>
{finished.map(g => <GameRow key={g.id} g={g} />)}
</>
)}
{games.length === 0 && (
<div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', fontSize:13, textAlign:'center', paddingTop:40 }}>
Noch keine Spiele. Starte eines!
</div>
)}
</div>
);
}
// ── Hauptkomponente ───────────────────────────────────────────────────────────
export default function Gebietseroberung({ toast }) {
const [games, setGames] = useState([]);
const [activeId, setActiveId] = useState(null);
const [game, setGame] = useState(null);
const [myId, setMyId] = useState(null);
const [showNew, setShowNew] = useState(false);
const [showHelp, setShowHelp] = useState(false);
const [loading, setLoading] = useState(true);
// Eigene User-ID aus JWT ermitteln
useEffect(() => {
api('/auth/me').then(u => setMyId(u.id)).catch(() => {});
}, []);
const loadGames = useCallback(async () => {
try {
const gs = await api('/tools/gebietseroberung');
setGames(gs);
} catch(e) {
toast?.('Fehler beim Laden', 'error');
} finally { setLoading(false); }
}, []);
useEffect(() => { loadGames(); }, [loadGames]);
// Aktives Spiel laden
useEffect(() => {
if (!activeId) { setGame(null); return; }
api(`/tools/gebietseroberung/${activeId}`).then(setGame).catch(() => {});
}, [activeId]);
// Polling wenn aktives Spiel läuft und Gegner dran ist
useEffect(() => {
if (!activeId || !game || !myId) return;
if (game.status !== 'active' || game.current_turn === myId) return;
const iv = setInterval(async () => {
const g = await api(`/tools/gebietseroberung/${activeId}`).catch(() => null);
if (g) {
setGame(g);
if (g.current_turn === myId) {
toast?.('Du bist dran! 🗺️');
}
}
}, 10000);
return () => clearInterval(iv);
}, [activeId, game, myId]);
const handleMove = async (row, col) => {
try {
const updated = await api(`/tools/gebietseroberung/${activeId}/move`, { body: { row, col } });
setGame(updated);
// Spielliste auch aktualisieren
setGames(prev => prev.map(g => g.id === updated.id ? { ...g, ...updated } : g));
} catch(e) {
toast?.(e.message || 'Fehler beim Zug', 'error');
}
};
const handleResign = async () => {
if (!window.confirm('Wirklich aufgeben?')) return;
try {
await api(`/tools/gebietseroberung/${activeId}/resign`, { body: {} });
const updated = await api(`/tools/gebietseroberung/${activeId}`);
setGame(updated);
setGames(prev => prev.map(g => g.id === updated.id ? { ...g, ...updated } : g));
toast('Du hast aufgegeben.');
} catch(e) { toast?.(e.message, 'error'); }
};
if (loading) return (
<div style={{ color:'rgba(255,255,255,0.4)', fontFamily:'monospace', padding:40, textAlign:'center' }}>
Lade
</div>
);
return (
<div style={{ maxWidth:600, margin:'0 auto', padding:'0 4px' }}>
{/* Header */}
<div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:20 }}>
{activeId && (
<button onClick={() => { setActiveId(null); setGame(null); }} style={S.btn('#666666', true)}>
Zurück
</button>
)}
<h2 style={{ ...S.head, margin:0, flex:1, fontSize:12 }}>
🗺 GEBIETSEROBERUNG
</h2>
<button onClick={() => setShowHelp(true)} style={S.btn('#ffe66d', true)}>? Regeln</button>
{activeId && game?.status === 'active' && (
<button onClick={handleResign} style={S.btn('#ff6b9d', true)}> Aufgeben</button>
)}
</div>
{/* Inhalt */}
{!activeId ? (
<GameList
games={games}
myId={myId}
onSelect={id => setActiveId(id)}
onNew={() => setShowNew(true)}
/>
) : (
game && myId
? <GameBoard game={game} myId={myId} onMove={handleMove} toast={toast} />
: <div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', textAlign:'center', paddingTop:40 }}>Lade Spiel</div>
)}
{/* Modals */}
{showNew && (
<NewGameModal
onClose={() => setShowNew(false)}
toast={toast}
onCreated={id => { setShowNew(false); setActiveId(id); loadGames(); }}
/>
)}
{showHelp && <HelpModal onClose={() => setShowHelp(false)} />}
</div>
);
}