fix: Hex Wars - undefined-Bug, Diagonale, Topliste, move_count
This commit is contained in:
@@ -12,60 +12,56 @@ const router = express.Router();
|
|||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
owner_id INTEGER NOT NULL,
|
owner_id INTEGER NOT NULL,
|
||||||
opponent_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,
|
grid TEXT NOT NULL,
|
||||||
current_turn INTEGER NOT NULL,
|
current_turn INTEGER NOT NULL,
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
winner_id INTEGER,
|
winner_id INTEGER,
|
||||||
|
move_count INTEGER NOT NULL DEFAULT 0,
|
||||||
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
|
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
|
||||||
updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
|
updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
|
||||||
);
|
);
|
||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
|
// move_count nachrüsten falls Tabelle schon existiert
|
||||||
|
if (!cols.includes('move_count')) {
|
||||||
|
db.exec(`ALTER TABLE geo_games ADD COLUMN move_count INTEGER NOT NULL DEFAULT 0`);
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const GRID_SIZE = 20;
|
const GRID = 20;
|
||||||
|
|
||||||
// Leeres Grid erstellen: 0=neutral, owner_id=Spieler1, opponent_id=Spieler2
|
|
||||||
function createGrid(ownerId, oppId) {
|
function createGrid(ownerId, oppId) {
|
||||||
const grid = Array(GRID_SIZE).fill(null).map(() => Array(GRID_SIZE).fill(0));
|
const grid = Array(GRID).fill(null).map(() => Array(GRID).fill(0));
|
||||||
// Startpositionen: Owner oben-links, Opponent unten-rechts
|
|
||||||
grid[0][0] = ownerId;
|
grid[0][0] = ownerId;
|
||||||
grid[GRID_SIZE - 1][GRID_SIZE - 1] = oppId;
|
grid[GRID - 1][GRID - 1] = oppId;
|
||||||
return JSON.stringify(grid);
|
return JSON.stringify(grid);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prüft ob Zelle an Spieler-Gebiet grenzt (oben/unten/links/rechts)
|
// Diagonal erlaubt: alle 8 Richtungen
|
||||||
function isAdjacent(grid, row, col, playerId) {
|
function isAdjacent(grid, row, col, playerId) {
|
||||||
const dirs = [[-1,0],[1,0],[0,-1],[0,1]];
|
const dirs = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];
|
||||||
for (const [dr, dc] of dirs) {
|
for (const [dr, dc] of dirs) {
|
||||||
const r = row + dr, c = col + dc;
|
const r = row + dr, c = col + dc;
|
||||||
if (r >= 0 && r < GRID_SIZE && c >= 0 && c < GRID_SIZE && grid[r][c] === playerId) return true;
|
if (r >= 0 && r < GRID && c >= 0 && c < GRID && grid[r][c] === playerId) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prüft ob ein Spieler noch Züge machen kann
|
|
||||||
function canMove(grid, playerId) {
|
function canMove(grid, playerId) {
|
||||||
for (let r = 0; r < GRID_SIZE; r++) {
|
for (let r = 0; r < GRID; r++)
|
||||||
for (let c = 0; c < GRID_SIZE; c++) {
|
for (let c = 0; c < GRID; c++)
|
||||||
if (grid[r][c] === 0 && isAdjacent(grid, r, c, playerId)) return true;
|
if (grid[r][c] === 0 && isAdjacent(grid, r, c, playerId)) return true;
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Felder zählen
|
|
||||||
function countCells(grid, playerId) {
|
function countCells(grid, playerId) {
|
||||||
let count = 0;
|
let n = 0;
|
||||||
for (let r = 0; r < GRID_SIZE; r++)
|
for (let r = 0; r < GRID; r++)
|
||||||
for (let c = 0; c < GRID_SIZE; c++)
|
for (let c = 0; c < GRID; c++)
|
||||||
if (grid[r][c] === playerId) count++;
|
if (grid[r][c] === playerId) n++;
|
||||||
return count;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pushover helper
|
|
||||||
function sendPush(userId, title, message) {
|
function sendPush(userId, title, message) {
|
||||||
const cfg = db.prepare('SELECT user_key, app_token FROM pushover_settings WHERE user_id=?').get(userId);
|
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;
|
if (!cfg?.app_token || !cfg?.user_key) return;
|
||||||
@@ -76,24 +72,52 @@ function sendPush(userId, title, message) {
|
|||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Spiel mit JOIN laden (inkl. owner_name / opp_name)
|
||||||
|
function getGame(id) {
|
||||||
|
return 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(id);
|
||||||
|
}
|
||||||
|
|
||||||
const uid = req => req.user.id;
|
const uid = req => req.user.id;
|
||||||
|
|
||||||
// ── Alle Spiele des Users ─────────────────────────────────────────────────────
|
// ── Alle Spiele des Users ─────────────────────────────────────────────────────
|
||||||
router.get('/', authenticate, (req, res) => {
|
router.get('/', authenticate, (req, res) => {
|
||||||
const me = uid(req);
|
const me = uid(req);
|
||||||
const games = db.prepare(`
|
const games = db.prepare(`
|
||||||
SELECT g.*,
|
SELECT g.*, u1.username as owner_name, u2.username as opp_name
|
||||||
u1.username as owner_name,
|
|
||||||
u2.username as opp_name
|
|
||||||
FROM geo_games g
|
FROM geo_games g
|
||||||
JOIN users u1 ON u1.id = g.owner_id
|
JOIN users u1 ON u1.id = g.owner_id
|
||||||
JOIN users u2 ON u2.id = g.opponent_id
|
JOIN users u2 ON u2.id = g.opponent_id
|
||||||
WHERE g.owner_id=? OR g.opponent_id=?
|
WHERE (g.owner_id=? OR g.opponent_id=?)
|
||||||
|
AND NOT (g.status='finished' AND g.move_count < 2)
|
||||||
ORDER BY g.updated_at DESC
|
ORDER BY g.updated_at DESC
|
||||||
`).all(me, me);
|
`).all(me, me);
|
||||||
res.json(games);
|
res.json(games);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Topliste ──────────────────────────────────────────────────────────────────
|
||||||
|
router.get('/leaderboard', authenticate, (req, res) => {
|
||||||
|
// Nur Spiele die wirklich gespielt wurden (mind. 1 Zug pro Spieler = move_count >= 2)
|
||||||
|
// und nicht durch Aufgeben ohne Züge beendet wurden
|
||||||
|
const rows = db.prepare(`
|
||||||
|
SELECT u.username, COUNT(*) as wins
|
||||||
|
FROM geo_games g
|
||||||
|
JOIN users u ON u.id = g.winner_id
|
||||||
|
WHERE g.status = 'finished'
|
||||||
|
AND g.winner_id IS NOT NULL
|
||||||
|
AND g.move_count >= 2
|
||||||
|
GROUP BY g.winner_id
|
||||||
|
ORDER BY wins DESC
|
||||||
|
LIMIT 20
|
||||||
|
`).all();
|
||||||
|
res.json(rows);
|
||||||
|
});
|
||||||
|
|
||||||
// ── Alle User (für Einladen) ──────────────────────────────────────────────────
|
// ── Alle User (für Einladen) ──────────────────────────────────────────────────
|
||||||
router.get('/users', authenticate, (req, res) => {
|
router.get('/users', authenticate, (req, res) => {
|
||||||
const me = uid(req);
|
const me = uid(req);
|
||||||
@@ -107,15 +131,7 @@ router.get('/users', authenticate, (req, res) => {
|
|||||||
// ── Einzelnes Spiel ───────────────────────────────────────────────────────────
|
// ── Einzelnes Spiel ───────────────────────────────────────────────────────────
|
||||||
router.get('/:id', authenticate, (req, res) => {
|
router.get('/:id', authenticate, (req, res) => {
|
||||||
const me = uid(req);
|
const me = uid(req);
|
||||||
const game = db.prepare(`
|
const game = getGame(req.params.id);
|
||||||
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) return res.status(404).json({ error: 'Nicht gefunden' });
|
||||||
if (game.owner_id !== me && game.opponent_id !== me)
|
if (game.owner_id !== me && game.opponent_id !== me)
|
||||||
return res.status(403).json({ error: 'Kein Zugriff' });
|
return res.status(403).json({ error: 'Kein Zugriff' });
|
||||||
@@ -134,12 +150,12 @@ router.post('/', authenticate, (req, res) => {
|
|||||||
|
|
||||||
const grid = createGrid(me, opponent_id);
|
const grid = createGrid(me, opponent_id);
|
||||||
const result = db.prepare(`
|
const result = db.prepare(`
|
||||||
INSERT INTO geo_games (owner_id, opponent_id, grid, current_turn)
|
INSERT INTO geo_games (owner_id, opponent_id, grid, current_turn, move_count)
|
||||||
VALUES (?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, 0)
|
||||||
`).run(me, opponent_id, grid, me);
|
`).run(me, opponent_id, grid, me);
|
||||||
|
|
||||||
const myName = db.prepare('SELECT username FROM users WHERE id=?').get(me)?.username || 'Jemand';
|
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.`);
|
sendPush(opponent_id, '⬡ Hex Wars', `${myName} hat dich zu einem Spiel eingeladen! Du bist zuerst dran.`);
|
||||||
|
|
||||||
res.json({ id: result.lastInsertRowid });
|
res.json({ id: result.lastInsertRowid });
|
||||||
});
|
});
|
||||||
@@ -158,69 +174,61 @@ router.post('/:id/move', authenticate, (req, res) => {
|
|||||||
if (game.current_turn !== me) return res.status(400).json({ error: 'Nicht dein Zug' });
|
if (game.current_turn !== me) return res.status(400).json({ error: 'Nicht dein Zug' });
|
||||||
|
|
||||||
const grid = JSON.parse(game.grid);
|
const grid = JSON.parse(game.grid);
|
||||||
|
if (row < 0 || row >= GRID || col < 0 || col >= GRID)
|
||||||
if (row < 0 || row >= GRID_SIZE || col < 0 || col >= GRID_SIZE)
|
|
||||||
return res.status(400).json({ error: 'Ungültige Position' });
|
return res.status(400).json({ error: 'Ungültige Position' });
|
||||||
if (grid[row][col] !== 0)
|
if (grid[row][col] !== 0)
|
||||||
return res.status(400).json({ error: 'Zelle bereits belegt' });
|
return res.status(400).json({ error: 'Zelle bereits belegt' });
|
||||||
if (!isAdjacent(grid, row, col, me))
|
if (!isAdjacent(grid, row, col, me))
|
||||||
return res.status(400).json({ error: 'Zelle grenzt nicht an dein Gebiet' });
|
return res.status(400).json({ error: 'Zelle grenzt nicht an dein Gebiet' });
|
||||||
|
|
||||||
// Zug ausführen
|
|
||||||
grid[row][col] = me;
|
grid[row][col] = me;
|
||||||
|
|
||||||
const opponent = game.owner_id === me ? game.opponent_id : game.owner_id;
|
const opponent = game.owner_id === me ? game.opponent_id : game.owner_id;
|
||||||
|
const newMoves = (game.move_count || 0) + 1;
|
||||||
let nextTurn = opponent;
|
let nextTurn = opponent;
|
||||||
let status = 'active';
|
let status = 'active';
|
||||||
let winnerId = null;
|
let winnerId = null;
|
||||||
|
|
||||||
// Prüfen ob Gegner noch ziehen kann
|
|
||||||
if (!canMove(grid, opponent)) {
|
if (!canMove(grid, opponent)) {
|
||||||
// Gegner kann nicht — prüfen ob ich auch nicht mehr kann
|
|
||||||
if (!canMove(grid, me)) {
|
if (!canMove(grid, me)) {
|
||||||
// Spiel vorbei
|
|
||||||
status = 'finished';
|
status = 'finished';
|
||||||
const myCount = countCells(grid, me);
|
const mc = countCells(grid, me);
|
||||||
const oppCount = countCells(grid, opponent);
|
const oc = countCells(grid, opponent);
|
||||||
winnerId = myCount > oppCount ? me : (oppCount > myCount ? opponent : null); // null = Unentschieden
|
winnerId = mc > oc ? me : (oc > mc ? opponent : null);
|
||||||
} else {
|
} else {
|
||||||
// Gegner überspringen, ich mache weiter
|
nextTurn = me; // Gegner überspringen
|
||||||
nextTurn = me;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const newGrid = JSON.stringify(grid);
|
|
||||||
db.prepare(`
|
db.prepare(`
|
||||||
UPDATE geo_games SET grid=?, current_turn=?, status=?, winner_id=?,
|
UPDATE geo_games SET grid=?, current_turn=?, status=?, winner_id=?, move_count=?,
|
||||||
updated_at=datetime('now','localtime') WHERE id=?
|
updated_at=datetime('now','localtime') WHERE id=?
|
||||||
`).run(newGrid, nextTurn, status, winnerId, game.id);
|
`).run(JSON.stringify(grid), nextTurn, status, winnerId, newMoves, game.id);
|
||||||
|
|
||||||
// Pushover
|
// Pushover
|
||||||
const myName = db.prepare('SELECT username FROM users WHERE id=?').get(me)?.username || 'Jemand';
|
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';
|
const oppName = db.prepare('SELECT username FROM users WHERE id=?').get(opponent)?.username || 'Jemand';
|
||||||
|
|
||||||
if (status === 'finished') {
|
if (status === 'finished') {
|
||||||
const myCount = countCells(grid, me);
|
const mc = countCells(grid, me);
|
||||||
const oppCount = countCells(grid, opponent);
|
const oc = countCells(grid, opponent);
|
||||||
if (winnerId === me) {
|
if (winnerId === me) {
|
||||||
sendPush(opponent, '🗺️ Spiel beendet', `${myName} hat gewonnen! ${myCount} vs ${oppCount} Felder.`);
|
sendPush(opponent, '⬡ Hex Wars beendet', `${myName} hat gewonnen! ${mc} vs ${oc} Felder.`);
|
||||||
sendPush(me, '🗺️ Spiel beendet', `Du hast gewonnen! ${myCount} vs ${oppCount} Felder. 🎉`);
|
sendPush(me, '⬡ Hex Wars gewonnen!', `Du hast gewonnen! ${mc} vs ${oc} Felder. 🎉`);
|
||||||
} else if (winnerId === opponent) {
|
} else if (winnerId === opponent) {
|
||||||
sendPush(me, '🗺️ Spiel beendet', `${oppName} hat gewonnen. ${myCount} vs ${oppCount} Felder.`);
|
sendPush(me, '⬡ Hex Wars beendet', `${oppName} hat gewonnen. ${mc} vs ${oc} Felder.`);
|
||||||
sendPush(opponent, '🗺️ Spiel beendet', `Du hast gewonnen! ${oppCount} vs ${myCount} Felder. 🎉`);
|
sendPush(opponent, '⬡ Hex Wars gewonnen!', `Du hast gewonnen! ${oc} vs ${mc} Felder. 🎉`);
|
||||||
} else {
|
} else {
|
||||||
sendPush(me, '🗺️ Unentschieden!', `Gleichstand — ${myCount} vs ${oppCount} Felder.`);
|
sendPush(me, '⬡ Hex Wars — Unentschieden!', `${mc} vs ${oc} Felder.`);
|
||||||
sendPush(opponent, '🗺️ Unentschieden!', `Gleichstand — ${oppCount} vs ${myCount} Felder.`);
|
sendPush(opponent, '⬡ Hex Wars — Unentschieden!', `${oc} vs ${mc} Felder.`);
|
||||||
}
|
}
|
||||||
} else if (nextTurn === opponent) {
|
} else if (nextTurn === opponent) {
|
||||||
sendPush(opponent, '🗺️ Du bist dran!', `${myName} hat gezogen — jetzt bist du dran!`);
|
sendPush(opponent, '⬡ Hex Wars — Du bist dran!', `${myName} hat gezogen!`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const updated = db.prepare('SELECT * FROM geo_games WHERE id=?').get(game.id);
|
res.json(getGame(game.id));
|
||||||
res.json(updated);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Spiel aufgeben ────────────────────────────────────────────────────────────
|
// ── Aufgeben ──────────────────────────────────────────────────────────────────
|
||||||
router.post('/:id/resign', authenticate, (req, res) => {
|
router.post('/:id/resign', authenticate, (req, res) => {
|
||||||
const me = uid(req);
|
const me = uid(req);
|
||||||
const game = db.prepare('SELECT * FROM geo_games WHERE id=?').get(req.params.id);
|
const game = db.prepare('SELECT * FROM geo_games WHERE id=?').get(req.params.id);
|
||||||
@@ -230,10 +238,14 @@ router.post('/:id/resign', authenticate, (req, res) => {
|
|||||||
if (game.status !== 'active') return res.status(400).json({ error: 'Spiel bereits beendet' });
|
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;
|
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);
|
// move_count bleibt wie es ist — wird für Leaderboard/Liste genutzt
|
||||||
|
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';
|
const myName = db.prepare('SELECT username FROM users WHERE id=?').get(me)?.username || 'Jemand';
|
||||||
sendPush(winner, '🗺️ Spiel gewonnen!', `${myName} hat aufgegeben. Du gewinnst! 🎉`);
|
sendPush(winner, '⬡ Hex Wars gewonnen!', `${myName} hat aufgegeben. Du gewinnst! 🎉`);
|
||||||
|
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ const GRID = 20;
|
|||||||
const MY_COLOR = '#4ecdc4';
|
const MY_COLOR = '#4ecdc4';
|
||||||
const OPP_COLOR = '#ff6b9d';
|
const OPP_COLOR = '#ff6b9d';
|
||||||
|
|
||||||
// User-ID aus JWT lesen (kein API-Call nötig)
|
|
||||||
function getMyId() {
|
function getMyId() {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('sk_token');
|
const token = localStorage.getItem('sk_token');
|
||||||
@@ -17,43 +16,26 @@ function getMyId() {
|
|||||||
// ── Spielerklärung ────────────────────────────────────────────────────────────
|
// ── Spielerklärung ────────────────────────────────────────────────────────────
|
||||||
function HelpModal({ onClose }) {
|
function HelpModal({ onClose }) {
|
||||||
return (
|
return (
|
||||||
<div style={{
|
<div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.75)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:1000, padding:20 }}>
|
||||||
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%' }}>
|
<div style={{ ...S.card, maxWidth:440, width:'100%' }}>
|
||||||
<div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
|
<div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
|
||||||
<span style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:15, fontWeight:700 }}>
|
<span style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:15, fontWeight:700 }}>⬡ Wie funktioniert's?</span>
|
||||||
⬡ 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>
|
||||||
<div style={{ color:'rgba(255,255,255,0.75)', fontSize:13, lineHeight:1.8, fontFamily:'monospace' }}>
|
<div style={{ color:'rgba(255,255,255,0.75)', fontSize:13, lineHeight:1.8, fontFamily:'monospace' }}>
|
||||||
<p style={{ marginTop:0 }}>
|
<p style={{ marginTop:0 }}><strong style={{ color:MY_COLOR }}>Dein Ziel:</strong> Am Ende mehr Felder als dein Gegner besitzen.</p>
|
||||||
<strong style={{ color:MY_COLOR }}>Dein Ziel:</strong> Am Ende mehr Felder als dein Gegner besitzen.
|
<p><strong style={{ color:'#fff' }}>So geht's:</strong><br/>
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<strong style={{ color:'#fff' }}>So geht's:</strong><br/>
|
|
||||||
Jeder Spieler startet in einer Ecke des 20×20 Rasters. Abwechselnd wählst du eine
|
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>,
|
<strong style={{ color:'rgba(255,255,255,0.9)' }}> neutrale (graue) Zelle</strong>,
|
||||||
die direkt an dein Gebiet grenzt — oben, unten, links oder rechts.
|
die an dein Gebiet grenzt — auch diagonal.</p>
|
||||||
</p>
|
<p><strong style={{ color:'#fff' }}>Taktik:</strong><br/>
|
||||||
<p>
|
|
||||||
<strong style={{ color:'#fff' }}>Taktik:</strong><br/>
|
|
||||||
Breite dich aus — aber mauere deinen Gegner
|
Breite dich aus — aber mauere deinen Gegner
|
||||||
<strong style={{ color:OPP_COLOR }}> ein</strong>, bevor er dich einsperrt!
|
<strong style={{ color:OPP_COLOR }}> ein</strong>, bevor er dich einsperrt!</p>
|
||||||
Blockieren ist genauso wichtig wie Expandieren.
|
<p><strong style={{ color:'#fff' }}>Ende:</strong><br/>
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<strong style={{ color:'#fff' }}>Ende:</strong><br/>
|
|
||||||
Wenn niemand mehr expandieren kann, gewinnt wer mehr Felder hat.
|
Wenn niemand mehr expandieren kann, gewinnt wer mehr Felder hat.
|
||||||
Du kriegst eine <strong>Pushover-Benachrichtigung</strong> wenn du dran bist.
|
Du kriegst eine <strong>Pushover-Benachrichtigung</strong> wenn du dran bist.</p>
|
||||||
</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)' }}>
|
||||||
<div style={{
|
💡 <em>Leuchtende Felder sind anklickbar — alle 8 Richtungen (inkl. Diagonal).</em>
|
||||||
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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -67,9 +49,7 @@ function NewGameModal({ onClose, onCreated, toast }) {
|
|||||||
const [oppId, setOppId] = useState('');
|
const [oppId, setOppId] = useState('');
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => { api('/tools/gebietseroberung/users').then(setUsers).catch(() => {}); }, []);
|
||||||
api('/tools/gebietseroberung/users').then(setUsers).catch(() => {});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const create = async () => {
|
const create = async () => {
|
||||||
if (!oppId) return;
|
if (!oppId) return;
|
||||||
@@ -84,15 +64,10 @@ function NewGameModal({ onClose, onCreated, toast }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{
|
<div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.75)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:1000, padding:20 }}>
|
||||||
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={{ ...S.card, maxWidth:360, width:'100%' }}>
|
||||||
<div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
|
<div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
|
||||||
<span style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:14, fontWeight:700 }}>
|
<span style={{ color:'#fff', fontFamily:'Space Mono,monospace', fontSize:14, fontWeight:700 }}>Neues Spiel</span>
|
||||||
Neues Spiel
|
|
||||||
</span>
|
|
||||||
<button onClick={onClose} style={S.btn('#666666', true)}>✕</button>
|
<button onClick={onClose} style={S.btn('#666666', true)}>✕</button>
|
||||||
</div>
|
</div>
|
||||||
<label style={{ ...S.head, display:'block', marginBottom:6 }}>GEGNER WÄHLEN</label>
|
<label style={{ ...S.head, display:'block', marginBottom:6 }}>GEGNER WÄHLEN</label>
|
||||||
@@ -111,8 +86,44 @@ function NewGameModal({ onClose, onCreated, toast }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Topliste ──────────────────────────────────────────────────────────────────
|
||||||
|
function Leaderboard() {
|
||||||
|
const [rows, setRows] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
api('/tools/gebietseroberung/leaderboard').then(setRows).catch(() => setRows([]));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (rows === null) return <div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', fontSize:12, padding:'20px 0', textAlign:'center' }}>Lade…</div>;
|
||||||
|
|
||||||
|
const medals = ['🥇','🥈','🥉'];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ marginTop:24 }}>
|
||||||
|
<div style={{ ...S.head, marginBottom:10 }}>TOPLISTE — SIEGE</div>
|
||||||
|
{rows.length === 0
|
||||||
|
? <div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', fontSize:12, textAlign:'center', padding:'12px 0' }}>Noch keine abgeschlossenen Spiele.</div>
|
||||||
|
: rows.map((r, i) => (
|
||||||
|
<div key={r.username} style={{
|
||||||
|
display:'flex', alignItems:'center', gap:10,
|
||||||
|
padding:'8px 12px', marginBottom:6,
|
||||||
|
background:'rgba(255,255,255,0.03)',
|
||||||
|
border:'1px solid rgba(255,255,255,0.07)',
|
||||||
|
borderRadius:8,
|
||||||
|
}}>
|
||||||
|
<span style={{ fontSize:16, width:24, textAlign:'center' }}>{medals[i] || `${i+1}.`}</span>
|
||||||
|
<span style={{ flex:1, color:'#fff', fontFamily:'monospace', fontSize:13 }}>{r.username}</span>
|
||||||
|
<span style={{ color:MY_COLOR, fontFamily:'Space Mono,monospace', fontSize:15, fontWeight:700 }}>{r.wins}</span>
|
||||||
|
<span style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', fontSize:10 }}>Siege</span>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Spielfeld ─────────────────────────────────────────────────────────────────
|
// ── Spielfeld ─────────────────────────────────────────────────────────────────
|
||||||
function GameBoard({ game, myId, onMove, toast }) {
|
function GameBoard({ game, myId, onMove }) {
|
||||||
const [hover, setHover] = useState(null);
|
const [hover, setHover] = useState(null);
|
||||||
const [moving, setMoving] = useState(false);
|
const [moving, setMoving] = useState(false);
|
||||||
|
|
||||||
@@ -123,13 +134,13 @@ function GameBoard({ game, myId, onMove, toast }) {
|
|||||||
const oppColor = game.owner_id === myId ? OPP_COLOR : MY_COLOR;
|
const oppColor = game.owner_id === myId ? OPP_COLOR : MY_COLOR;
|
||||||
const oppName = game.owner_id === myId ? game.opp_name : game.owner_name;
|
const oppName = game.owner_id === myId ? game.opp_name : game.owner_name;
|
||||||
|
|
||||||
const isAdj = (r, c) => [[-1,0],[1,0],[0,-1],[0,1]].some(([dr,dc]) => {
|
// Diagonal erlaubt: alle 8 Richtungen
|
||||||
|
const isAdj = (r, c) => [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]].some(([dr,dc]) => {
|
||||||
const nr = r+dr, nc = c+dc;
|
const nr = r+dr, nc = c+dc;
|
||||||
return nr>=0 && nr<GRID && nc>=0 && nc<GRID && grid[nr][nc] === myId;
|
return nr>=0 && nr<GRID && nc>=0 && nc<GRID && grid[nr][nc] === myId;
|
||||||
});
|
});
|
||||||
|
|
||||||
const canClick = (r, c) =>
|
const canClick = (r, c) => isMyTurn && game.status === 'active' && grid[r][c] === 0 && isAdj(r, c);
|
||||||
isMyTurn && game.status === 'active' && grid[r][c] === 0 && isAdj(r, c);
|
|
||||||
|
|
||||||
const handleClick = async (r, c) => {
|
const handleClick = async (r, c) => {
|
||||||
if (!canClick(r, c) || moving) return;
|
if (!canClick(r, c) || moving) return;
|
||||||
@@ -144,17 +155,15 @@ function GameBoard({ game, myId, onMove, toast }) {
|
|||||||
let banner = null;
|
let banner = null;
|
||||||
if (game.status === 'finished') {
|
if (game.status === 'finished') {
|
||||||
if (!game.winner_id) banner = { text:'Unentschieden! 🤝', color:'#ffe66d' };
|
if (!game.winner_id) banner = { text:'Unentschieden! 🤝', color:'#ffe66d' };
|
||||||
else if (game.winner_id===myId) banner = { text:'Du hast gewonnen! 🎉', color:MY_COLOR };
|
else if (game.winner_id === myId) banner = { text:'Du hast gewonnen! 🎉', color:MY_COLOR };
|
||||||
else banner = { text:'Du hast verloren.', color:OPP_COLOR };
|
else banner = { text:'Du hast verloren.', color:OPP_COLOR };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Zellgröße: passt sich ans Viewport an, nie horizontales Scrollen
|
const vw = Math.min(window.innerWidth, 520);
|
||||||
const vw = Math.min(window.innerWidth, 600);
|
const cellSize = Math.floor((vw - 40) / GRID);
|
||||||
const cellSize = Math.floor((vw - 48) / GRID); // 48px = padding + gap
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{/* Scoreboard */}
|
|
||||||
<div style={{ display:'flex', gap:8, alignItems:'center', marginBottom:10 }}>
|
<div style={{ display:'flex', gap:8, alignItems:'center', marginBottom:10 }}>
|
||||||
<div style={{ ...S.card, padding:'8px 12px', flex:1 }}>
|
<div style={{ ...S.card, padding:'8px 12px', flex:1 }}>
|
||||||
<div style={{ color:myColor, fontFamily:'monospace', fontSize:10, marginBottom:2 }}>DU</div>
|
<div style={{ color:myColor, fontFamily:'monospace', fontSize:10, marginBottom:2 }}>DU</div>
|
||||||
@@ -169,7 +178,6 @@ function GameBoard({ game, myId, onMove, toast }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Banner */}
|
|
||||||
{banner && (
|
{banner && (
|
||||||
<div style={{
|
<div style={{
|
||||||
background:`${banner.color}22`, border:`1px solid ${banner.color}55`,
|
background:`${banner.color}22`, border:`1px solid ${banner.color}55`,
|
||||||
@@ -179,19 +187,12 @@ function GameBoard({ game, myId, onMove, toast }) {
|
|||||||
}}>{banner.text}</div>
|
}}>{banner.text}</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Zug-Hinweis */}
|
|
||||||
{game.status === 'active' && (
|
{game.status === 'active' && (
|
||||||
<div style={{
|
<div style={{ color: isMyTurn ? myColor : 'rgba(255,255,255,0.35)', fontFamily:'monospace', fontSize:11, marginBottom:8, textAlign:'center' }}>
|
||||||
color: isMyTurn ? myColor : 'rgba(255,255,255,0.35)',
|
{isMyTurn ? (moving ? 'Zug wird gespeichert…' : '▶ Dein Zug') : `⏳ ${oppName} ist dran…`}
|
||||||
fontFamily:'monospace', fontSize:11, marginBottom:8, textAlign:'center',
|
|
||||||
}}>
|
|
||||||
{isMyTurn
|
|
||||||
? (moving ? 'Zug wird gespeichert…' : '▶ Dein Zug')
|
|
||||||
: `⏳ ${oppName} ist dran…`}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Grid — immer passend ohne Scrollen */}
|
|
||||||
<div style={{
|
<div style={{
|
||||||
display:'grid',
|
display:'grid',
|
||||||
gridTemplateColumns:`repeat(${GRID}, ${cellSize}px)`,
|
gridTemplateColumns:`repeat(${GRID}, ${cellSize}px)`,
|
||||||
@@ -234,7 +235,8 @@ function GameBoard({ game, myId, onMove, toast }) {
|
|||||||
// ── Spielliste ────────────────────────────────────────────────────────────────
|
// ── Spielliste ────────────────────────────────────────────────────────────────
|
||||||
function GameList({ games, myId, onSelect, onNew }) {
|
function GameList({ games, myId, onSelect, onNew }) {
|
||||||
const active = games.filter(g => g.status === 'active');
|
const active = games.filter(g => g.status === 'active');
|
||||||
const finished = games.filter(g => g.status === 'finished');
|
// Beendet: nur Spiele mit mind. 2 Zügen (mind. 1 pro Spieler)
|
||||||
|
const finished = games.filter(g => g.status === 'finished' && (g.move_count || 0) >= 2);
|
||||||
|
|
||||||
const GameRow = ({ g }) => {
|
const GameRow = ({ g }) => {
|
||||||
const isMyTurn = g.status === 'active' && g.current_turn === myId;
|
const isMyTurn = g.status === 'active' && g.current_turn === myId;
|
||||||
@@ -287,10 +289,11 @@ function GameList({ games, myId, onSelect, onNew }) {
|
|||||||
{finished.map(g => <GameRow key={g.id} g={g} />)}
|
{finished.map(g => <GameRow key={g.id} g={g} />)}
|
||||||
</>}
|
</>}
|
||||||
{games.length === 0 && (
|
{games.length === 0 && (
|
||||||
<div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', fontSize:13, textAlign:'center', paddingTop:40 }}>
|
<div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', fontSize:13, textAlign:'center', paddingTop:30 }}>
|
||||||
Noch keine Spiele — starte eines!
|
Noch keine Spiele — starte eines!
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<Leaderboard />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -304,7 +307,6 @@ export default function HexWars({ toast }) {
|
|||||||
const [showHelp, setShowHelp] = useState(false);
|
const [showHelp, setShowHelp] = useState(false);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
// User-ID direkt aus JWT — kein API-Call
|
|
||||||
const myId = getMyId();
|
const myId = getMyId();
|
||||||
|
|
||||||
const loadGames = useCallback(async () => {
|
const loadGames = useCallback(async () => {
|
||||||
@@ -317,7 +319,6 @@ export default function HexWars({ toast }) {
|
|||||||
|
|
||||||
useEffect(() => { loadGames(); }, [loadGames]);
|
useEffect(() => { loadGames(); }, [loadGames]);
|
||||||
|
|
||||||
// Aktives Spiel laden
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!activeId) { setGame(null); return; }
|
if (!activeId) { setGame(null); return; }
|
||||||
api(`/tools/gebietseroberung/${activeId}`).then(setGame).catch(() => {});
|
api(`/tools/gebietseroberung/${activeId}`).then(setGame).catch(() => {});
|
||||||
@@ -352,19 +353,14 @@ export default function HexWars({ toast }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (loading) return (
|
if (loading) return (
|
||||||
<div style={{ color:'rgba(255,255,255,0.4)', fontFamily:'monospace', padding:40, textAlign:'center' }}>
|
<div style={{ color:'rgba(255,255,255,0.4)', fontFamily:'monospace', padding:40, textAlign:'center' }}>Lade…</div>
|
||||||
Lade…
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ maxWidth:520, margin:'0 auto', padding:'0 4px' }}>
|
<div style={{ maxWidth:520, margin:'0 auto', padding:'0 4px' }}>
|
||||||
{/* Header */}
|
|
||||||
<div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:16 }}>
|
<div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:16 }}>
|
||||||
{activeId && (
|
{activeId && (
|
||||||
<button onClick={() => { setActiveId(null); setGame(null); }} style={S.btn('#666666', true)}>
|
<button onClick={() => { setActiveId(null); setGame(null); }} style={S.btn('#666666', true)}>← Zurück</button>
|
||||||
← Zurück
|
|
||||||
</button>
|
|
||||||
)}
|
)}
|
||||||
<span style={{ ...S.head, margin:0, flex:1, fontSize:12 }}>⬡ HEX WARS</span>
|
<span style={{ ...S.head, margin:0, flex:1, fontSize:12 }}>⬡ HEX WARS</span>
|
||||||
<button onClick={() => setShowHelp(true)} style={S.btn('#ffe66d', true)}>? Regeln</button>
|
<button onClick={() => setShowHelp(true)} style={S.btn('#ffe66d', true)}>? Regeln</button>
|
||||||
@@ -376,7 +372,7 @@ export default function HexWars({ toast }) {
|
|||||||
{!activeId
|
{!activeId
|
||||||
? <GameList games={games} myId={myId} onSelect={setActiveId} onNew={() => setShowNew(true)} />
|
? <GameList games={games} myId={myId} onSelect={setActiveId} onNew={() => setShowNew(true)} />
|
||||||
: game && myId
|
: game && myId
|
||||||
? <GameBoard game={game} myId={myId} onMove={handleMove} toast={toast} />
|
? <GameBoard game={game} myId={myId} onMove={handleMove} />
|
||||||
: <div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', textAlign:'center', paddingTop:40 }}>Lade Spiel…</div>
|
: <div style={{ color:'rgba(255,255,255,0.3)', fontFamily:'monospace', textAlign:'center', paddingTop:40 }}>Lade Spiel…</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user