From 7e19b2fe7faa5f9a42beb5cdf5943eff6c72cadf Mon Sep 17 00:00:00 2001 From: Dicken Date: Thu, 25 Jun 2026 23:22:25 +0200 Subject: [PATCH] feat: Gebietseroberung Multiplayer-Spiel --- backend/src/routes/search.js | 13 +- backend/src/tools/gebietseroberung/routes.js | 238 ++++++++++ frontend/src/App.jsx | 9 + frontend/src/icons.jsx | 7 + frontend/src/toolRegistry.js | 11 +- frontend/src/tools/gebietseroberung.jsx | 437 +++++++++++++++++++ frontend/src/tools/linkliste.jsx | 1 + 7 files changed, 714 insertions(+), 2 deletions(-) create mode 100644 backend/src/tools/gebietseroberung/routes.js create mode 100644 frontend/src/tools/gebietseroberung.jsx diff --git a/backend/src/routes/search.js b/backend/src/routes/search.js index cef5daf..4d6daef 100644 --- a/backend/src/routes/search.js +++ b/backend/src/routes/search.js @@ -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 diff --git a/backend/src/tools/gebietseroberung/routes.js b/backend/src/tools/gebietseroberung/routes.js new file mode 100644 index 0000000..68cd406 --- /dev/null +++ b/backend/src/tools/gebietseroberung/routes.js @@ -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; diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 229d783..734b59e 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -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 (
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 }) {
KALENDER-EINTRÄGE
{results.calendar_events.map((item,i)=>({}}/>))} + {results.geo_games?.length>0 && ( + <> +
GEBIETSEROBERUNG
+ {results.geo_games.map((item,i)=>({}}/>))} + + )}
)} {results.calendar_feeds?.length>0 && ( diff --git a/frontend/src/icons.jsx b/frontend/src/icons.jsx index f124cca..5dc8f1b 100644 --- a/frontend/src/icons.jsx +++ b/frontend/src/icons.jsx @@ -186,3 +186,10 @@ export const WhiteboardIcon = ({size=20,color='currentColor',sw}) => base(<> , size, color, sw); +export const GeoIcon = ({size=20,color='currentColor',sw}) => base(<> + + + + + +, size, color, sw); diff --git a/frontend/src/toolRegistry.js b/frontend/src/toolRegistry.js index 530b914..5f5fe0d 100644 --- a/frontend/src/toolRegistry.js +++ b/frontend/src/toolRegistry.js @@ -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, diff --git a/frontend/src/tools/gebietseroberung.jsx b/frontend/src/tools/gebietseroberung.jsx new file mode 100644 index 0000000..b114968 --- /dev/null +++ b/frontend/src/tools/gebietseroberung.jsx @@ -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 ( +
+
+
+ + 🗺️ Wie funktioniert's? + + +
+
+

+ Dein Ziel: Am Ende mehr Felder als dein Gegner besitzen. +

+

+ So geht's:
+ Jeder Spieler startet in einer Ecke des 20×20 Rasters mit einem Startfeld. + Abwechselnd wählt jeder eine neutrale (graue) Zelle, + die direkt an sein eigenes Gebiet grenzt — oben, unten, links oder rechts. + Diese Zelle gehört dann ihm. +

+

+ Taktik:
+ Breite dich schnell aus — aber pass auf: Wenn du deinen Gegner + einmauerst, kann er nicht mehr wachsen. + Blockieren ist genauso wichtig wie Expandieren! +

+

+ Ende:
+ Wenn keine neutralen Felder mehr erreichbar sind, gewinnt wer + mehr Felder besitzt. Du bekommst eine Pushover-Benachrichtigung, + wenn du dran bist. +

+
+ 💡 Klicke auf ein leuchtendes Feld um deinen Zug zu machen. Nur Felder neben deinem Gebiet sind wählbar. +
+
+
+
+ ); +} + +// ── 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 ( +
+
+
+ + Neues Spiel + + +
+ + +
+ + +
+
+
+ ); +} + +// ── 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=0 && nc 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 ( +
+ {/* Status-Leiste */} +
+
+
DU
+
{myCount}
+
+
+ {neutral} neutral +
+
+
+ {game.owner_id === myId ? game.opp_name : game.owner_name} +
+
{oppCount}
+
+
+ + {/* Gewinner-Banner */} + {banner && ( +
+ {banner.text} +
+ )} + + {/* Zug-Hinweis */} + {game.status === 'active' && ( +
+ {isMyTurn ? (moving ? 'Zug wird gespeichert…' : '▶ Dein Zug — klicke ein angrenzendes Feld') : '⏳ Warte auf Gegner…'} +
+ )} + + {/* Grid */} +
+ {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 ( +
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', + }} + /> + ); + }))} +
+
+ ); +} + +// ── 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 ( + + ); + }; + + return ( +
+ + {active.length > 0 && ( + <> +
LAUFENDE SPIELE ({active.length})
+ {active.map(g => )} + + )} + {finished.length > 0 && ( + <> +
BEENDETE SPIELE
+ {finished.map(g => )} + + )} + {games.length === 0 && ( +
+ Noch keine Spiele. Starte eines! +
+ )} +
+ ); +} + +// ── 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 ( +
+ Lade… +
+ ); + + return ( +
+ {/* Header */} +
+ {activeId && ( + + )} +

+ 🗺️ GEBIETSEROBERUNG +

+ + {activeId && game?.status === 'active' && ( + + )} +
+ + {/* Inhalt */} + {!activeId ? ( + setActiveId(id)} + onNew={() => setShowNew(true)} + /> + ) : ( + game && myId + ? + :
Lade Spiel…
+ )} + + {/* Modals */} + {showNew && ( + setShowNew(false)} + toast={toast} + onCreated={id => { setShowNew(false); setActiveId(id); loadGames(); }} + /> + )} + {showHelp && setShowHelp(false)} />} +
+ ); +} diff --git a/frontend/src/tools/linkliste.jsx b/frontend/src/tools/linkliste.jsx index 1a70c94..7ddefee 100644 --- a/frontend/src/tools/linkliste.jsx +++ b/frontend/src/tools/linkliste.jsx @@ -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' },