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

@@ -222,6 +222,17 @@ router.get('/', authenticate, (req, res) => {
ORDER BY created_at DESC LIMIT 5
`).all(uid, like, like));
// Gebietseroberung-Spiele
const geo_games = safe(() => db.prepare(`
SELECT g.id, u1.username as owner_name, u2.username as opp_name, g.status, g.current_turn
FROM geo_games g
JOIN users u1 ON u1.id=g.owner_id
JOIN users u2 ON u2.id=g.opponent_id
WHERE (g.owner_id=? OR g.opponent_id=?)
AND (LOWER(u1.username) LIKE ? OR LOWER(u2.username) LIKE ?)
ORDER BY g.updated_at DESC LIMIT 5
`).all(uid, uid, like, like));
// Andere Benutzer für Chat-Navigation (nur Benutzernamen, keine sensiblen Daten)
const users = safe(() => db.prepare(`
SELECT id, username FROM users
@@ -231,7 +242,7 @@ router.get('/', authenticate, (req, res) => {
res.json({ links, folders, snippets, calculations, orders, todos, notes,
board_items, changelog, files, file_folders, push_schedules,
calendar_feeds, calendar_events, qr_codes, users });
calendar_feeds, calendar_events, qr_codes, users, geo_games });
});
// Debug-Endpoint: Kalender-Cache inspizieren

View File

@@ -0,0 +1,238 @@
const express = require('express');
const db = require('../../db');
const { authenticate } = require('../../middleware/auth');
const router = express.Router();
// ── DB-Migration ──────────────────────────────────────────────────────────────
(function migrate() {
const cols = db.pragma('table_info(geo_games)').map(c => c.name);
if (!cols.length) {
db.exec(`
CREATE TABLE IF NOT EXISTS geo_games (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_id INTEGER NOT NULL,
opponent_id INTEGER NOT NULL,
owner_color TEXT NOT NULL DEFAULT '#4ecdc4',
opp_color TEXT NOT NULL DEFAULT '#ff6b9d',
grid TEXT NOT NULL,
current_turn INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
winner_id INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
`);
}
})();
const GRID_SIZE = 20;
// Leeres Grid erstellen: 0=neutral, owner_id=Spieler1, opponent_id=Spieler2
function createGrid(ownerId, oppId) {
const grid = Array(GRID_SIZE).fill(null).map(() => Array(GRID_SIZE).fill(0));
// Startpositionen: Owner oben-links, Opponent unten-rechts
grid[0][0] = ownerId;
grid[GRID_SIZE - 1][GRID_SIZE - 1] = oppId;
return JSON.stringify(grid);
}
// Prüft ob Zelle an Spieler-Gebiet grenzt (oben/unten/links/rechts)
function isAdjacent(grid, row, col, playerId) {
const dirs = [[-1,0],[1,0],[0,-1],[0,1]];
for (const [dr, dc] of dirs) {
const r = row + dr, c = col + dc;
if (r >= 0 && r < GRID_SIZE && c >= 0 && c < GRID_SIZE && grid[r][c] === playerId) return true;
}
return false;
}
// Prüft ob ein Spieler noch Züge machen kann
function canMove(grid, playerId) {
for (let r = 0; r < GRID_SIZE; r++) {
for (let c = 0; c < GRID_SIZE; c++) {
if (grid[r][c] === 0 && isAdjacent(grid, r, c, playerId)) return true;
}
}
return false;
}
// Felder zählen
function countCells(grid, playerId) {
let count = 0;
for (let r = 0; r < GRID_SIZE; r++)
for (let c = 0; c < GRID_SIZE; c++)
if (grid[r][c] === playerId) count++;
return count;
}
// Pushover helper
function sendPush(userId, title, message) {
const cfg = db.prepare('SELECT user_key, app_token FROM pushover_settings WHERE user_id=?').get(userId);
if (!cfg?.app_token || !cfg?.user_key) return;
fetch('https://api.pushover.net/1/messages.json', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: cfg.app_token, user: cfg.user_key, title, message, priority: 0 }),
}).catch(() => {});
}
const uid = req => req.user.id;
// ── Alle Spiele des Users ─────────────────────────────────────────────────────
router.get('/', authenticate, (req, res) => {
const me = uid(req);
const games = db.prepare(`
SELECT g.*,
u1.username as owner_name,
u2.username as opp_name
FROM geo_games g
JOIN users u1 ON u1.id = g.owner_id
JOIN users u2 ON u2.id = g.opponent_id
WHERE g.owner_id=? OR g.opponent_id=?
ORDER BY g.updated_at DESC
`).all(me, me);
res.json(games);
});
// ── Alle User (für Einladen) ──────────────────────────────────────────────────
router.get('/users', authenticate, (req, res) => {
const me = uid(req);
const users = db.prepare('SELECT id, username FROM users WHERE id != ? AND hidden != 1 ORDER BY username').all(me);
res.json(users);
});
// ── Einzelnes Spiel ───────────────────────────────────────────────────────────
router.get('/:id', authenticate, (req, res) => {
const me = uid(req);
const game = db.prepare(`
SELECT g.*,
u1.username as owner_name,
u2.username as opp_name
FROM geo_games g
JOIN users u1 ON u1.id = g.owner_id
JOIN users u2 ON u2.id = g.opponent_id
WHERE g.id=?
`).get(req.params.id);
if (!game) return res.status(404).json({ error: 'Nicht gefunden' });
if (game.owner_id !== me && game.opponent_id !== me)
return res.status(403).json({ error: 'Kein Zugriff' });
res.json(game);
});
// ── Neues Spiel erstellen ─────────────────────────────────────────────────────
router.post('/', authenticate, (req, res) => {
const me = uid(req);
const { opponent_id } = req.body;
if (!opponent_id) return res.status(400).json({ error: 'Gegner fehlt' });
if (opponent_id === me) return res.status(400).json({ error: 'Du kannst nicht gegen dich spielen' });
const opp = db.prepare('SELECT id, username FROM users WHERE id=?').get(opponent_id);
if (!opp) return res.status(404).json({ error: 'Benutzer nicht gefunden' });
const grid = createGrid(me, opponent_id);
const result = db.prepare(`
INSERT INTO geo_games (owner_id, opponent_id, grid, current_turn)
VALUES (?, ?, ?, ?)
`).run(me, opponent_id, grid, me);
const myName = db.prepare('SELECT username FROM users WHERE id=?').get(me)?.username || 'Jemand';
sendPush(opponent_id, '🗺️ Gebietseroberung', `${myName} hat dich zu einem Spiel eingeladen! Du bist zuerst dran.`);
res.json({ id: result.lastInsertRowid });
});
// ── Zug machen ────────────────────────────────────────────────────────────────
router.post('/:id/move', authenticate, (req, res) => {
const me = uid(req);
const { row, col } = req.body;
if (row === undefined || col === undefined) return res.status(400).json({ error: 'row/col fehlt' });
const game = db.prepare('SELECT * FROM geo_games WHERE id=?').get(req.params.id);
if (!game) return res.status(404).json({ error: 'Spiel nicht gefunden' });
if (game.owner_id !== me && game.opponent_id !== me)
return res.status(403).json({ error: 'Kein Zugriff' });
if (game.status !== 'active') return res.status(400).json({ error: 'Spiel beendet' });
if (game.current_turn !== me) return res.status(400).json({ error: 'Nicht dein Zug' });
const grid = JSON.parse(game.grid);
if (row < 0 || row >= GRID_SIZE || col < 0 || col >= GRID_SIZE)
return res.status(400).json({ error: 'Ungültige Position' });
if (grid[row][col] !== 0)
return res.status(400).json({ error: 'Zelle bereits belegt' });
if (!isAdjacent(grid, row, col, me))
return res.status(400).json({ error: 'Zelle grenzt nicht an dein Gebiet' });
// Zug ausführen
grid[row][col] = me;
const opponent = game.owner_id === me ? game.opponent_id : game.owner_id;
let nextTurn = opponent;
let status = 'active';
let winnerId = null;
// Prüfen ob Gegner noch ziehen kann
if (!canMove(grid, opponent)) {
// Gegner kann nicht — prüfen ob ich auch nicht mehr kann
if (!canMove(grid, me)) {
// Spiel vorbei
status = 'finished';
const myCount = countCells(grid, me);
const oppCount = countCells(grid, opponent);
winnerId = myCount > oppCount ? me : (oppCount > myCount ? opponent : null); // null = Unentschieden
} else {
// Gegner überspringen, ich mache weiter
nextTurn = me;
}
}
const newGrid = JSON.stringify(grid);
db.prepare(`
UPDATE geo_games SET grid=?, current_turn=?, status=?, winner_id=?,
updated_at=datetime('now','localtime') WHERE id=?
`).run(newGrid, nextTurn, status, winnerId, game.id);
// Pushover
const myName = db.prepare('SELECT username FROM users WHERE id=?').get(me)?.username || 'Jemand';
const oppName = db.prepare('SELECT username FROM users WHERE id=?').get(opponent)?.username || 'Jemand';
if (status === 'finished') {
const myCount = countCells(grid, me);
const oppCount = countCells(grid, opponent);
if (winnerId === me) {
sendPush(opponent, '🗺️ Spiel beendet', `${myName} hat gewonnen! ${myCount} vs ${oppCount} Felder.`);
sendPush(me, '🗺️ Spiel beendet', `Du hast gewonnen! ${myCount} vs ${oppCount} Felder. 🎉`);
} else if (winnerId === opponent) {
sendPush(me, '🗺️ Spiel beendet', `${oppName} hat gewonnen. ${myCount} vs ${oppCount} Felder.`);
sendPush(opponent, '🗺️ Spiel beendet', `Du hast gewonnen! ${oppCount} vs ${myCount} Felder. 🎉`);
} else {
sendPush(me, '🗺️ Unentschieden!', `Gleichstand — ${myCount} vs ${oppCount} Felder.`);
sendPush(opponent, '🗺️ Unentschieden!', `Gleichstand — ${oppCount} vs ${myCount} Felder.`);
}
} else if (nextTurn === opponent) {
sendPush(opponent, '🗺️ Du bist dran!', `${myName} hat gezogen — jetzt bist du dran!`);
}
const updated = db.prepare('SELECT * FROM geo_games WHERE id=?').get(game.id);
res.json(updated);
});
// ── Spiel aufgeben ────────────────────────────────────────────────────────────
router.post('/:id/resign', authenticate, (req, res) => {
const me = uid(req);
const game = db.prepare('SELECT * FROM geo_games WHERE id=?').get(req.params.id);
if (!game) return res.status(404).json({ error: 'Nicht gefunden' });
if (game.owner_id !== me && game.opponent_id !== me)
return res.status(403).json({ error: 'Kein Zugriff' });
if (game.status !== 'active') return res.status(400).json({ error: 'Spiel bereits beendet' });
const winner = game.owner_id === me ? game.opponent_id : game.owner_id;
db.prepare(`UPDATE geo_games SET status='finished', winner_id=?, updated_at=datetime('now','localtime') WHERE id=?`).run(winner, game.id);
const myName = db.prepare('SELECT username FROM users WHERE id=?').get(me)?.username || 'Jemand';
sendPush(winner, '🗺️ Spiel gewonnen!', `${myName} hat aufgegeben. Du gewinnst! 🎉`);
res.json({ ok: true });
});
module.exports = router;

View File

@@ -1552,6 +1552,7 @@ function SearchResultItem({ item, idx, activeIdx, onNavigate, onHover }) {
if (item.type==='calendar_feed') { icon='📅'; primary=item.name; secondary='Kalender-Abo'; }
if (item.type==='calendar_event') { icon='📆'; primary=item.summary; secondary=`${item.feed_name||'Kalender'}${item.start_dt?' · '+formatIcalDate(item.start_dt):''}`; }
if (item.type==='qr') { icon='◻'; primary=item.label||item.url; secondary=`QR-Code · ${item.url}`; }
if (item.type==='geo') { icon='🗺️'; primary=`vs ${item.opp_name||item.owner_name}`; secondary=item.status==='active'?'Gebietseroberung · laufend':'Gebietseroberung · beendet'; }
return (
<div onClick={()=>onNavigate(item)} onMouseEnter={()=>onHover(idx)}
style={{display:'flex',alignItems:'center',gap:10,padding:'9px 14px',cursor:'pointer',
@@ -1588,6 +1589,7 @@ const SEARCH_TOOL_INDEX = [
{type:'tool',label:'Whiteboard',icon:'🖊',sub:'Werkzeuge',id:'whiteboard',keywords:['whiteboard','zeichnen','canvas','board','draw','skizze','malen','zeichen']},
{type:'tool',label:'Dev-Tools',icon:'🔧',sub:'Werkzeuge',id:'devtools',keywords:['entwickler','developer','tools','werkzeuge']},
{type:'tool',label:'Paywall-Killer',icon:'🔓',sub:'Werkzeuge',id:'paywallkiller',keywords:['paywall','archiv','archive','artikel','zeitung','bild','waz','heise','spiegel','zeit','bypass','umgehen','lesen','gesperrt','bezahlschranke']},
{type:'tool',label:'Gebietseroberung',icon:'🗺️',sub:'Freizeit',id:'gebietseroberung',keywords:['spiel','game','gebietseroberung','multiplayer','gebiet','strategie','raster','einladen','duell']},
{type:'tool',label:'Media',icon:'🎬',sub:'Freizeit',id:'media',keywords:['kino','film','movie','streaming','demnächst','favoriten','cinema']},
{type:'tool',label:'Kino Aktuell',icon:'🎬',sub:'Media',id:'media',keywords:['kino','kinocharts','charts','laufend','now playing']},
{type:'tool',label:'Kino Demnächst',icon:'🗓',sub:'Media',id:'media',keywords:['demnächst','neustart','upcoming','vorschau','kino']},
@@ -1741,6 +1743,7 @@ function GlobalSearch({ setActive, setDevToolsNav, mobile }) {
else if (item.type === 'push') { setActive('dashboard'); }
else if (item.type === 'calendar_feed' || item.type === 'calendar_event') { setActive('dashboard'); }
else if (item.type === 'qr') { setActive('devtools'); setDevToolsNav({tool:'qrcode', ts: Date.now()}); }
else if (item.type === 'geo') { setActive('gebietseroberung'); }
};
const onKey = e => {
@@ -1901,6 +1904,12 @@ function GlobalSearch({ setActive, setDevToolsNav, mobile }) {
<div>
<div style={{padding:'7px 14px 4px',color:'rgba(255,255,255,0.3)',fontFamily:'monospace',fontSize:9,letterSpacing:1}}>KALENDER-EINTRÄGE</div>
{results.calendar_events.map((item,i)=>(<SearchResultItem key={`ce${i}`} item={{...item,type:'calendar_event'}} idx={0} activeIdx={-1} onNavigate={navigate} onHover={()=>{}}/>))}
{results.geo_games?.length>0 && (
<>
<div style={secHead}>GEBIETSEROBERUNG</div>
{results.geo_games.map((item,i)=>(<SearchResultItem key={`geo${i}`} item={{...item,type:'geo'}} idx={0} activeIdx={-1} onNavigate={navigate} onHover={()=>{}}/>))}
</>
)}
</div>
)}
{results.calendar_feeds?.length>0 && (

View File

@@ -186,3 +186,10 @@ export const WhiteboardIcon = ({size=20,color='currentColor',sw}) => base(<>
<path d="M7 13 L10 9 L13 11 L16 7" stroke={color} strokeWidth={sw||1.5} fill="none" strokeLinecap="round" strokeLinejoin="round"/>
<line x1="3" y1="19" x2="21" y2="19" stroke={color} strokeWidth={sw||1.5} strokeLinecap="round"/>
</>, size, color, sw);
export const GeoIcon = ({size=20,color='currentColor',sw}) => base(<>
<rect x="3" y="3" width="18" height="18" rx="2" stroke={color} strokeWidth={sw||1.5} fill="none"/>
<rect x="3" y="3" width="8" height="8" rx="1" fill={color} opacity="0.7"/>
<rect x="13" y="13" width="8" height="8" rx="1" fill={color} opacity="0.4"/>
<rect x="11" y="3" width="10" height="5" rx="1" stroke={color} strokeWidth={sw||1.2} fill="none"/>
<rect x="3" y="11" width="5" height="10" rx="1" stroke={color} strokeWidth={sw||1.2} fill="none"/>
</>, size, color, sw);

View File

@@ -11,7 +11,8 @@ import Media from './tools/media.jsx';
import PaywallKiller from './tools/paywallkiller.jsx';
import Kanban from './tools/kanban.jsx';
import Whiteboard from './tools/whiteboard.jsx';
import { CalculatorIcon, ArchiveIcon, DatabaseIcon, AppsIcon, MessageIcon, LinkIcon, CodeIcon, SkizzeIcon, WrenchIcon, FilmIcon, PaywallIcon, ChartIcon, KanbanIcon, WhiteboardIcon } from './icons.jsx';
import Gebietseroberung from './tools/gebietseroberung.jsx';
import { CalculatorIcon, ArchiveIcon, DatabaseIcon, AppsIcon, MessageIcon, LinkIcon, CodeIcon, SkizzeIcon, WrenchIcon, FilmIcon, PaywallIcon, ChartIcon, KanbanIcon, WhiteboardIcon, GeoIcon } from './icons.jsx';
export const TOOLS = [
{
@@ -62,6 +63,14 @@ export const TOOLS = [
group: 'Werkzeuge',
component: Whiteboard,
},
{
id: 'gebietseroberung',
Icon: GeoIcon,
label: 'Gebietseroberung',
navLabel: 'Gebiete',
group: 'Freizeit',
component: Gebietseroberung,
},
{
id: 'dateien',
Icon: DatabaseIcon,

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>
);
}

View File

@@ -16,6 +16,7 @@ const TOOL_ENTRIES = [
{ url:'tool://linkliste', label:'🔗 Linkliste', group:'Werkzeuge' },
{ url:'tool://codeschnipsel', label:'</> Code-Schnipsel', group:'Werkzeuge' },
{ url:'tool://media', label:'🎬 Media / Kino', group:'Freizeit' },
{ url:'tool://gebietseroberung', label:'🗺️ Gebietseroberung', group:'Freizeit' },
{ url:'tool://devtools', label:'🔧 Dev-Tools (alle)', group:'Dev-Tools' },
{ url:'tool://devtools?sub=cron', label:'⏱ Crontab', group:'Dev-Tools' },
{ url:'tool://devtools?sub=elektro', label:'⚡ Elektro', group:'Dev-Tools' },