fix: Hex Wars - myId aus JWT, responsives Grid, Umbenennung

This commit is contained in:
2026-06-25 23:39:21 +02:00
parent 4c349e00d3
commit 26764c5ab2
4 changed files with 136 additions and 180 deletions

View File

@@ -2,51 +2,58 @@ 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)';
const MY_COLOR = '#4ecdc4';
const OPP_COLOR = '#ff6b9d';
// User-ID aus JWT lesen (kein API-Call nötig)
function getMyId() {
try {
const token = localStorage.getItem('sk_token');
if (!token) return null;
return JSON.parse(atob(token.split('.')[1])).id || null;
} catch { return null; }
}
// ── 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,
display:'flex', alignItems:'center', justifyContent:'center', zIndex:1000, padding:20,
}}>
<div style={{ ...S.card, maxWidth:440, width:'100%', position:'relative' }}>
<div style={{ ...S.card, maxWidth:440, width:'100%' }}>
<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?
Wie funktioniert's?
</span>
<button onClick={onClose} style={{ ...S.btn('#ff6b9d', true) }}>✕ Schließen</button>
<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.
<strong style={{ color:MY_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.
Jeder Spieler startet in einer Ecke des 20×20 Rasters. Abwechselnd wählst du eine
<strong style={{ color:'rgba(255,255,255,0.9)' }}> neutrale (graue) Zelle</strong>,
die direkt an dein Gebiet grenzt oben, unten, links oder rechts.
</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!
Breite dich aus aber mauere deinen Gegner
<strong style={{ color:OPP_COLOR }}> ein</strong>, bevor er dich einsperrt!
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.
Wenn niemand mehr expandieren kann, gewinnt wer mehr Felder hat.
Du kriegst 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 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>Leuchtende Felder sind anklickbar nur Felder neben deinem Gebiet.</em>
</div>
</div>
</div>
@@ -69,7 +76,7 @@ function NewGameModal({ onClose, onCreated, toast }) {
setLoading(true);
try {
const res = await api('/tools/gebietseroberung', { body: { opponent_id: Number(oppId) } });
toast('Spiel erstellt! Dein Gegner wurde benachrichtigt 🗺️');
toast('Spiel erstellt! Dein Gegner wurde benachrichtigt ');
onCreated(res.id);
} catch(e) {
toast(e.message || 'Fehler beim Erstellen', 'error');
@@ -89,11 +96,7 @@ function NewGameModal({ onClose, onCreated, toast }) {
<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 }}
>
<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>
@@ -110,115 +113,102 @@ function NewGameModal({ onClose, onCreated, toast }) {
// ── Spielfeld ─────────────────────────────────────────────────────────────────
function GameBoard({ game, myId, onMove, toast }) {
const [hover, setHover] = useState(null);
const [hover, setHover] = useState(null);
const [moving, setMoving] = useState(false);
const grid = JSON.parse(game.grid);
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 myColor = game.owner_id === myId ? MY_COLOR : OPP_COLOR;
const oppColor = game.owner_id === myId ? OPP_COLOR : MY_COLOR;
const oppName = game.owner_id === myId ? game.opp_name : game.owner_name;
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 isAdj = (r, c) => [[-1,0],[1,0],[0,-1],[0,1]].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 canClick = (r, c) =>
isMyTurn && game.status === 'active' && grid[r][c] === 0 && isAdj(r, c);
const handleClick = async (r, c) => {
if (!canClick(r, c) || moving) return;
setMoving(true);
try {
await onMove(r, c);
} finally { setMoving(false); }
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' };
}
if (!game.winner_id) banner = { text:'Unentschieden! 🤝', color:'#ffe66d' };
else if (game.winner_id===myId) banner = { text:'Du hast gewonnen! 🎉', color:MY_COLOR };
else banner = { text:'Du hast verloren.', color:OPP_COLOR };
}
// Grid-Zellengröße responsiv
const isMob = window.innerWidth < 600;
const cellSize = isMob ? Math.floor((window.innerWidth - 48) / GRID) : 24;
// Zellgröße: passt sich ans Viewport an, nie horizontales Scrollen
const vw = Math.min(window.innerWidth, 600);
const cellSize = Math.floor((vw - 48) / GRID); // 48px = padding + gap
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>
{/* Scoreboard */}
<div style={{ display:'flex', gap:8, alignItems:'center', marginBottom:10 }}>
<div style={{ ...S.card, padding:'8px 12px', flex:1 }}>
<div style={{ color:myColor, fontFamily:'monospace', fontSize:10, marginBottom:2 }}>DU</div>
<div style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:22, fontWeight:700 }}>{myCount}</div>
</div>
<div style={{ textAlign:'center', color:'rgba(255,255,255,0.4)', fontFamily:'monospace', fontSize:11 }}>
{neutral} neutral
<div style={{ textAlign:'center', color:'rgba(255,255,255,0.35)', fontFamily:'monospace', fontSize:10, lineHeight:1.5 }}>
{neutral}<br/>frei
</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 style={{ ...S.card, padding:'8px 12px', flex:1, textAlign:'right' }}>
<div style={{ color:oppColor, fontFamily:'monospace', fontSize:10, marginBottom:2 }}>{oppName}</div>
<div style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:22, fontWeight:700 }}>{oppCount}</div>
</div>
</div>
{/* Gewinner-Banner */}
{/* Banner */}
{banner && (
<div style={{
background:`${banner.color}22`, border:`1px solid ${banner.color}55`,
borderRadius:8, padding:'10px 14px', marginBottom:12,
borderRadius:8, padding:'10px 14px', marginBottom:10,
color:banner.color, fontFamily:'Space Mono,monospace', fontSize:14,
textAlign:'center', fontWeight:700,
}}>
{banner.text}
</div>
}}>{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',
color: isMyTurn ? myColor : 'rgba(255,255,255,0.35)',
fontFamily:'monospace', fontSize:11, marginBottom:8, textAlign:'center',
}}>
{isMyTurn ? (moving ? 'Zug wird gespeichert…' : '▶ Dein Zug — klicke ein angrenzendes Feld') : '⏳ Warte auf Gegner…'}
{isMyTurn
? (moving ? 'Zug wird gespeichert…' : '▶ Dein Zug')
: `${oppName} ist dran…`}
</div>
)}
{/* Grid */}
{/* Grid — immer passend ohne Scrollen */}
<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%',
padding:3,
}}>
{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`;
const key = `${r}-${c}`;
const clic = canClick(r, c);
const hov = hover === key && clic;
let bg = 'rgba(255,255,255,0.05)';
if (cell === myId) bg = `${myColor}55`;
if (cell === opponent) bg = `${oppColor}55`;
if (isHovered) bg = HOVER_COLOR;
if (clickable && !isHovered) bg = `${myColor}25`;
if (clic && !hov) bg = `${myColor}22`;
if (hov) bg = `${myColor}66`;
return (
<div
key={key}
@@ -226,13 +216,12 @@ function GameBoard({ game, myId, onMove, toast }) {
onMouseEnter={() => setHover(key)}
onMouseLeave={() => setHover(null)}
style={{
width: cellSize, height: cellSize,
background: bg,
borderRadius: 2,
cursor: clickable ? 'pointer' : 'default',
transition: 'background 0.1s',
width:cellSize, height:cellSize,
background:bg, borderRadius:1,
cursor: clic ? 'pointer' : 'default',
transition:'background 0.08s',
border: clic ? `1px solid ${myColor}55` : '1px solid transparent',
boxSizing:'border-box',
border: clickable ? `1px solid ${myColor}66` : '1px solid transparent',
}}
/>
);
@@ -249,30 +238,25 @@ function GameList({ games, myId, onSelect, onNew }) {
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 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' };
if (!g.winner_id) result = { label:'Unentschieden', color:'#ffe66d' };
else if (g.winner_id === myId) result = { label:'Gewonnen 🎉', color:MY_COLOR };
else result = { label:'Verloren', color:OPP_COLOR };
}
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)',
}}
>
<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>}
{isMyTurn && <span style={{ color:MY_COLOR, marginRight:6 }}></span>}
vs <strong>{opp}</strong>
</div>
<div style={{ color:'rgba(255,255,255,0.4)', fontSize:11, fontFamily:'monospace' }}>
@@ -281,7 +265,7 @@ function GameList({ games, myId, onSelect, onNew }) {
</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' }}>
: <span style={{ color: isMyTurn ? MY_COLOR : 'rgba(255,255,255,0.3)', fontSize:11, fontFamily:'monospace' }}>
{isMyTurn ? 'Du bist dran' : 'Gegner dran'}
</span>
}
@@ -294,21 +278,17 @@ function GameList({ games, myId, onSelect, onNew }) {
<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} />)}
</>
)}
{active.length > 0 && <>
<div style={{ ...S.head, marginBottom:8 }}>LAUFEND ({active.length})</div>
{active.map(g => <GameRow key={g.id} g={g} />)}
</>}
{finished.length > 0 && <>
<div style={{ ...S.head, marginTop:16, marginBottom:8 }}>BEENDET</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!
Noch keine Spiele starte eines!
</div>
)}
</div>
@@ -316,27 +296,23 @@ function GameList({ games, myId, onSelect, onNew }) {
}
// ── 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);
export default function HexWars({ toast }) {
const [games, setGames] = useState([]);
const [activeId, setActiveId] = useState(null);
const [game, setGame] = 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(() => {});
}, []);
// User-ID direkt aus JWT — kein API-Call
const myId = getMyId();
const loadGames = useCallback(async () => {
try {
const gs = await api('/tools/gebietseroberung');
setGames(gs);
} catch(e) {
toast?.('Fehler beim Laden', 'error');
} finally { setLoading(false); }
} catch { toast?.('Fehler beim Laden', 'error'); }
finally { setLoading(false); }
}, []);
useEffect(() => { loadGames(); }, [loadGames]);
@@ -347,42 +323,32 @@ export default function Gebietseroberung({ toast }) {
api(`/tools/gebietseroberung/${activeId}`).then(setGame).catch(() => {});
}, [activeId]);
// Polling wenn aktives Spiel läuft und Gegner dran ist
// Polling wenn 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! 🗺️');
}
}
if (!g) return;
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 updated = await api(`/tools/gebietseroberung/${activeId}/move`, { body: { row, col } });
setGame(updated);
setGames(prev => prev.map(g => g.id === updated.id ? { ...g, ...updated } : g));
};
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'); }
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.');
};
if (loading) return (
@@ -392,38 +358,28 @@ export default function Gebietseroberung({ toast }) {
);
return (
<div style={{ maxWidth:600, margin:'0 auto', padding:'0 4px' }}>
<div style={{ maxWidth:520, margin:'0 auto', padding:'0 4px' }}>
{/* Header */}
<div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:20 }}>
<div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:16 }}>
{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>
<span style={{ ...S.head, margin:0, flex:1, fontSize:12 }}> HEX WARS</span>
<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
{!activeId
? <GameList games={games} myId={myId} onSelect={setActiveId} 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)}