feat: vytržení miniher do samostatného projektu
CI / Server unit tests (push) Successful in 26s
CI / Generate TypeScript types (push) Successful in 10s
CI / Build server (push) Successful in 28s
CI / Build client (push) Successful in 41s
CI / Playwright E2E tests (push) Successful in 2m24s
CI / Build and push Docker image (push) Successful in 44s
CI / Notify (push) Successful in 2s

This commit is contained in:
mates committed 2026-10-22 12:42:49 +02:00
1 parent 8a7bbef729
commit 35cf2ca9d7
42 files changed
+136 -8224

No files matched your search

+18 -3
View File
@@ -1,6 +1,21 @@
// Pozvánka Kreslení nad pozvánkami ostatních her, aby se nepřekrývaly
.duel-invite.draw-invite {
bottom: 224px;
.duel-invite {
position: fixed;
left: 16px;
bottom: 16px;
z-index: 1040;
padding: 10px 16px;
border: none;
border-radius: 999px;
background: var(--luncher-primary, #198754);
color: #fff;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
cursor: pointer;
animation: duel-pulse 1.6s ease-in-out infinite;
}
@keyframes duel-pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.04); }
}
.drawing-game-modal {
+31
View File
@@ -0,0 +1,31 @@
// Bez zoomu dvojitým ťuknutím, jinak by iOS sérii ťuknutí na logo spolkl
.navbar-brand {
touch-action: manipulation;
}
// Skryté pole pro kód minihry — musí jít zaměřit (kvůli softwarové klávesnici), proto ne display: none.
// Písmo aspoň 16px, jinak iOS při zaměření přiblíží stránku.
.minigame-secret-input {
position: fixed;
top: 0;
left: 0;
width: 1px;
height: 1px;
padding: 0;
border: 0;
font-size: 16px;
opacity: 0;
pointer-events: none;
}
// Nenápadné potvrzení, že logo přijalo sérii kliknutí a čeká na tajné slovo
.navbar-brand.duel-armed {
display: inline-block;
animation: duel-wiggle 0.35s ease-in-out 2;
}
@keyframes duel-wiggle {
0%, 100% { transform: rotate(0); }
25% { transform: rotate(-4deg); }
75% { transform: rotate(4deg); }
}
+1 -10
View File
@@ -2,12 +2,8 @@ import { useEffect, useState } from "react";
import { Navbar, Nav, NavDropdown, Modal, Button } from "react-bootstrap";
import { useAuth } from "../context/auth";
import SettingsModal from "./modals/SettingsModal";
import ReactionDuel from "./ReactionDuel";
import SnakeGame from "./SnakeGame";
import TetrisGame from "./TetrisGame";
import PongGame from "./PongGame";
import DrawingGame from "./DrawingGame";
import TankGame from "./TankGame";
import "./Header.scss";
import { useMinigameSecret } from "../hooks/useMinigameSecret";
import { useSettings, ThemePreference } from "../context/settings";
import HuePicker from "./HuePicker";
@@ -205,12 +201,7 @@ export default function Header({ choices, dayIndex }: Props) {
</NavDropdown>
</Nav>
</Navbar.Collapse>
<ReactionDuel />
<SnakeGame />
<TetrisGame />
<PongGame />
<DrawingGame />
<TankGame />
<SettingsModal isOpen={settingsModalOpen} onClose={closeSettingsModal} onSave={saveSettings} />
<RefreshMenuModal isOpen={refreshMenuModalOpen} onClose={closeRefreshMenuModal} />
<PizzaCalculatorModal isOpen={pizzaModalOpen} onClose={closePizzaModal} />
-35
View File
@@ -1,35 +0,0 @@
.lobby-chat {
margin-top: 12px;
.lobby-chat-messages {
height: 140px;
overflow-y: auto;
border: 1px solid rgba(127, 127, 127, 0.35);
border-radius: 6px;
padding: 6px 8px;
margin-bottom: 6px;
font-size: 0.9rem;
word-break: break-word;
}
.lobby-chat-emojis {
display: flex;
flex-wrap: wrap;
gap: 2px;
margin-bottom: 4px;
button {
border: none;
background: none;
padding: 0 3px;
font-size: 1.2rem;
line-height: 1.4;
border-radius: 4px;
cursor: pointer;
&:hover {
background: rgba(127, 127, 127, 0.2);
}
}
}
}
-64
View File
@@ -1,64 +0,0 @@
import { FormEvent, useEffect, useRef, useState } from "react";
import { Form } from "react-bootstrap";
import { socket } from "../context/socket";
import { getToken } from "../Utils";
import "./LobbyChat.scss";
const EMOJIS = ['😀', '😂', '😎', '😢', '😡', '👍', '👎', '👋', '🎉', '🔥', '❤️', '🍕', '🍔', '🍺', '⏳'];
type LobbyChatMessage = { game: string, login: string, text: string };
/** Jednoduchý chat v lobby minihry — zprávy se drží jen po dobu zobrazení lobby. */
export default function LobbyChat({ game }: { game: string }) {
const [messages, setMessages] = useState<LobbyChatMessage[]>([]);
const [text, setText] = useState('');
const listRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const onMessage = (m: LobbyChatMessage) => {
if (m.game === game) setMessages(prev => [...prev.slice(-99), m]);
};
socket.on('lobbychat:message', onMessage);
return () => { socket.off('lobbychat:message', onMessage); };
}, [game]);
useEffect(() => {
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
}, [messages]);
const submit = (e: FormEvent) => {
e.preventDefault();
if (!text.trim()) return;
socket.emit('lobbychat:send', { token: getToken(), game, text });
setText('');
};
const addEmoji = (emoji: string) => {
setText(prev => (prev + emoji).slice(0, 200));
inputRef.current?.focus();
};
return (
<div className="lobby-chat">
<div className="lobby-chat-messages" ref={listRef}>
{messages.length === 0 && <div className="text-muted">Zatím žádné zprávy…</div>}
{messages.map((m, i) => <div key={i}><strong>{m.login}: </strong>{m.text}</div>)}
</div>
<div className="lobby-chat-emojis">
{EMOJIS.map(e => <button key={e} type="button" onClick={() => addEmoji(e)}>{e}</button>)}
</div>
<Form onSubmit={submit}>
<Form.Control
ref={inputRef}
size="sm"
value={text}
onChange={e => setText(e.target.value)}
placeholder="Napište zprávu…"
maxLength={200}
onKeyDown={e => e.stopPropagation()}
/>
</Form>
</div>
);
}
-71
View File
@@ -1,71 +0,0 @@
// Pozvánka Pongu nad pozvánkami ostatních her, aby se nepřekrývaly
.duel-invite.pong-invite {
bottom: 172px;
}
.pong-game-modal {
.pong-scoreboard {
display: flex;
justify-content: center;
align-items: baseline;
gap: 24px;
font-size: 1.1rem;
margin-bottom: 8px;
strong {
font-size: 2rem;
}
}
.pong-board-wrap {
position: relative;
max-width: 800px;
margin: 0 auto;
// Tah prstem po hřišti hýbe pálkou, ne stránkou
touch-action: none;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
}
.pong-board {
display: block;
width: 100%;
height: auto;
border-radius: 8px;
}
.pong-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 5rem;
font-weight: 700;
color: #fff;
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.6);
pointer-events: none;
&.small {
font-size: 2.5rem;
}
}
.pong-bot-picker {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
.form-select {
width: auto;
}
}
.pong-status {
text-align: center;
opacity: 0.7;
margin-top: 8px;
}
}
-317
View File
@@ -1,317 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button, Form, Modal } from "react-bootstrap";
import { socket } from "../context/socket";
import { useAuth } from "../context/auth";
import { getToken } from "../Utils";
import { useGameIcon } from "../games/themeIcons";
import { useTouchDevice } from "../hooks/useTouchDevice";
import LobbyChat from "./LobbyChat";
import "./PongGame.scss";
// Typy musí odpovídat server/src/pongGame.ts (stav chodí přes websocket, ne přes OpenAPI)
type PongPhase = 'idle' | 'lobby' | 'countdown' | 'playing' | 'finished';
type BotLevel = 'easy' | 'medium' | 'hard' | 'impossible';
type PongPlayer = { login: string, side: 0 | 1, y: number, score: number, bot?: BotLevel };
type PongState = {
phase: PongPhase,
host?: string,
players: PongPlayer[],
ball: { x: number, y: number },
countdown?: number,
winner?: string,
width: number,
height: number,
};
const OPEN_EVENT = 'luncher:open-pong';
/** Otevře okno Pongu. */
export const openPongGame = () => window.dispatchEvent(new Event(OPEN_EVENT));
// Rozměry musí odpovídat serveru
const PADDLE_HEIGHT = 90;
const PADDLE_WIDTH = 12;
const PADDLE_MARGIN = 20;
const BALL_SIZE = 12;
const SIDE_COLORS = ['#60a5fa', '#f472b6'];
/** Jak často se posílá poloha myši (ms). */
const AIM_SEND_MS = 30;
const BOT_LEVELS: { value: BotLevel, label: string }[] = [
{ value: 'easy', label: 'Lehký' },
{ value: 'medium', label: 'Střední' },
{ value: 'hard', label: 'Těžký' },
{ value: 'impossible', label: 'Nemožný' },
];
const UP_KEYS = new Set(['ArrowUp', 'KeyW']);
const DOWN_KEYS = new Set(['ArrowDown', 'KeyS']);
function draw(canvas: HTMLCanvasElement, state: PongState, me?: string) {
const ctx = canvas.getContext('2d');
if (!ctx) return;
const scale = canvas.width / state.width;
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.fillStyle = '#111827';
ctx.fillRect(0, 0, state.width, state.height);
// Středová čára
ctx.fillStyle = '#374151';
for (let y = 0; y < state.height; y += 30) ctx.fillRect(state.width / 2 - 2, y + 5, 4, 18);
for (const p of state.players) {
const x = p.side === 0 ? PADDLE_MARGIN : state.width - PADDLE_MARGIN - PADDLE_WIDTH;
ctx.fillStyle = SIDE_COLORS[p.side];
ctx.fillRect(x, p.y - PADDLE_HEIGHT / 2, PADDLE_WIDTH, PADDLE_HEIGHT);
if (p.login === me) {
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.strokeRect(x - 1, p.y - PADDLE_HEIGHT / 2 - 1, PADDLE_WIDTH + 2, PADDLE_HEIGHT + 2);
}
}
if (state.phase === 'playing') {
ctx.fillStyle = '#f9fafb';
ctx.beginPath();
ctx.arc(state.ball.x, state.ball.y, BALL_SIZE / 2, 0, Math.PI * 2);
ctx.fill();
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
/** Pong 1v1 — fyziku drží server, klient posílá jen směr pálky. */
export default function PongGame() {
const auth = useAuth();
const login = auth?.login;
const [state, setState] = useState<PongState | null>(null);
const [open, setOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const prevPhase = useRef<PongPhase>('idle');
const icon = useGameIcon('pong');
const touch = useTouchDevice();
const [botLevel, setBotLevel] = useState<BotLevel>('medium');
/** Výška hřiště pro přepočet myši — přes ref, ať se efekt nerestartuje každým snímkem. */
const fieldHeight = useRef(500);
fieldHeight.current = state?.height ?? fieldHeight.current;
const send = useCallback((event: string, extra?: object) => {
setError(null);
socket.emit(event, { token: getToken(), ...extra });
}, []);
useEffect(() => {
const onState = (s: PongState) => setState(s);
const onError = (msg: string) => setError(msg);
const onOpen = () => setOpen(true);
const sync = () => socket.emit('pong:sync');
socket.on('pong:state', onState);
socket.on('pong:error', onError);
socket.on('connect', sync);
window.addEventListener(OPEN_EVENT, onOpen);
sync();
return () => {
socket.off('pong:state', onState);
socket.off('pong:error', onError);
socket.off('connect', sync);
window.removeEventListener(OPEN_EVENT, onOpen);
};
}, []);
// Snímky hry dostávají jen klienti s otevřeným oknem
useEffect(() => {
if (!open) return;
const watch = () => socket.emit('pong:watch');
watch();
socket.on('connect', watch);
return () => {
socket.off('connect', watch);
socket.emit('pong:unwatch');
};
}, [open]);
const isPlayer = !!login && !!state?.players.some(p => p.login === login);
const phase = state?.phase ?? 'idle';
const inGame = phase === 'countdown' || phase === 'playing';
useEffect(() => {
if (prevPhase.current === 'lobby' && phase === 'countdown' && isPlayer) {
setOpen(true);
}
prevPhase.current = phase;
}, [phase, isPlayer]);
// Ovládání: drží se klávesa → pálka jede, puštění → stojí
useEffect(() => {
if (!open || !inGame || !isPlayer) return;
const pressed = new Set<string>();
const update = () => {
const up = [...pressed].some(k => UP_KEYS.has(k));
const down = [...pressed].some(k => DOWN_KEYS.has(k));
send('pong:input', { input: up === down ? 'stop' : up ? 'up' : 'down' });
};
const onDown = (e: KeyboardEvent) => {
if (!UP_KEYS.has(e.code) && !DOWN_KEYS.has(e.code)) return;
e.preventDefault();
if (e.repeat || pressed.has(e.code)) return;
pressed.add(e.code);
update();
};
const onUp = (e: KeyboardEvent) => {
if (!pressed.delete(e.code)) return;
update();
};
const onBlur = () => {
pressed.clear();
update();
};
window.addEventListener('keydown', onDown);
window.addEventListener('keyup', onUp);
window.addEventListener('blur', onBlur);
return () => {
window.removeEventListener('keydown', onDown);
window.removeEventListener('keyup', onUp);
window.removeEventListener('blur', onBlur);
};
}, [open, inGame, isPlayer, send]);
// Ovládání myší či prstem: pálka sleduje výšku kurzoru nad hřištěm (kdekoli v okně, mimo hřiště se ořízne)
useEffect(() => {
if (!open || !inGame || !isPlayer) return;
let latest: number | undefined;
let sent: number | undefined;
const onMove = (e: PointerEvent) => {
const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
const height = fieldHeight.current;
const y = ((e.clientY - rect.top) / rect.height) * height;
latest = Math.round(Math.min(height, Math.max(0, y)));
};
const id = window.setInterval(() => {
if (latest === undefined || latest === sent) return;
sent = latest;
send('pong:aim', { y: latest });
}, AIM_SEND_MS);
// Prst nemá "hover" — pálka skočí už na dotyk, ne až na první pohyb
window.addEventListener('pointerdown', onMove);
window.addEventListener('pointermove', onMove);
return () => {
window.clearInterval(id);
window.removeEventListener('pointerdown', onMove);
window.removeEventListener('pointermove', onMove);
};
}, [open, inGame, isPlayer, send]);
useEffect(() => {
if (canvasRef.current && state && phase !== 'idle' && phase !== 'lobby') {
draw(canvasRef.current, state, login);
}
}, [state, phase, login]);
if (!login) return null;
const left = state?.players.find(p => p.side === 0);
const right = state?.players.find(p => p.side === 1);
const showInvite = !open && phase === 'lobby' && !isPlayer && (state?.players.length ?? 0) < 2;
const showReturn = !open && isPlayer && inGame;
const renderBoard = () => state && (
<>
<div className="pong-scoreboard">
<span style={{ color: SIDE_COLORS[0] }}>{left?.login}</span>
<strong>{left?.score ?? 0} : {right?.score ?? 0}</strong>
<span style={{ color: SIDE_COLORS[1] }}>{right?.login}</span>
</div>
<div className="pong-board-wrap">
<canvas ref={canvasRef} className="pong-board" width={state.width} height={state.height} />
{phase === 'countdown' && <div className="pong-overlay">{state.countdown}</div>}
{phase === 'finished' && <div className="pong-overlay small">🏆 {state.winner}</div>}
</div>
<div className="pong-status">{isPlayer ? (touch ? 'Táhněte prstem po hřišti' : 'Myš, nebo ↑↓ / W S') : 'Sledujete zápas'}</div>
</>
);
const renderBody = () => {
switch (phase) {
case 'idle':
return (
<p>
Klasický Pong pro dva. Ovládání myší (pálka sleduje kurzor), prstem po hřišti nebo šipkami / W S, hraje se
do 5 bodů. Když není s kým hrát, přidejte si v lobby bota. Ostatní se mohou dívat.
</p>
);
case 'lobby':
return (
<>
<p>Lobby založil(a) <strong>{state?.host}</strong>.</p>
<ul>{state?.players.map(p => <li key={p.login}>{p.login}{p.login === state.host && ' 👑'}</li>)}</ul>
{(state?.players.length ?? 0) < 2 && <p className="text-muted">Čeká se na soupeře…</p>}
{login === state?.host && (state?.players.length ?? 0) < 2 && (
<div className="pong-bot-picker">
<span>Nebo hrát proti botovi:</span>
<Form.Select size="sm" value={botLevel} onChange={e => setBotLevel(e.target.value as BotLevel)}>
{BOT_LEVELS.map(l => <option key={l.value} value={l.value}>{l.label}</option>)}
</Form.Select>
<Button size="sm" variant="outline-primary" onClick={() => send('pong:addBot', { level: botLevel })}>
Přidat bota
</Button>
</div>
)}
{login === state?.host && state?.players.some(p => p.bot) && (
<Button size="sm" variant="outline-secondary" onClick={() => send('pong:removeBot')}>Odebrat bota</Button>
)}
{isPlayer && <LobbyChat game="pong" />}
</>
);
default:
return renderBoard();
}
};
const renderFooter = () => {
const buttons = [];
if (phase === 'idle' || phase === 'finished') {
buttons.push(<Button key="new" onClick={() => send('pong:join')}>{phase === 'idle' ? 'Založit lobby' : 'Nová hra'}</Button>);
}
if (phase === 'lobby') {
if (!isPlayer) {
if ((state?.players.length ?? 0) < 2) {
buttons.push(<Button key="join" onClick={() => send('pong:join')}>Připojit se</Button>);
}
} else {
buttons.push(<Button key="leave" variant="outline-secondary" onClick={() => send('pong:leave')}>
{login === state?.host ? 'Zrušit lobby' : 'Odejít'}
</Button>);
if (login === state?.host) {
buttons.push(<Button key="start" onClick={() => send('pong:start')}
disabled={(state?.players.length ?? 0) < 2}>Spustit hru</Button>);
}
}
}
buttons.push(<Button key="close" variant="secondary" onClick={() => setOpen(false)}>Zavřít</Button>);
return buttons;
};
return (
<>
{showInvite && (
<button className="duel-invite pong-invite" onClick={() => setOpen(true)}>
{icon} <strong>{state?.host}</strong> hledá soupeře na Pong — připojit se
</button>
)}
{showReturn && (
<button className="duel-invite pong-invite" onClick={() => setOpen(true)}>
{icon} Pong běží — zpět do hry
</button>
)}
<Modal show={open} onHide={() => setOpen(false)} size="xl" fullscreen="sm-down" className="pong-game-modal">
<Modal.Header closeButton>
<Modal.Title><h2>{icon} Pong</h2></Modal.Title>
</Modal.Header>
<Modal.Body>
{renderBody()}
{error && <div className="text-danger mt-2">{error}</div>}
</Modal.Body>
<Modal.Footer>{renderFooter()}</Modal.Footer>
</Modal>
</>
);
}
-134
View File
@@ -1,134 +0,0 @@
.duel-invite {
position: fixed;
left: 16px;
bottom: 16px;
z-index: 1040;
padding: 10px 16px;
border: none;
border-radius: 999px;
background: var(--luncher-primary, #198754);
color: #fff;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
cursor: pointer;
animation: duel-pulse 1.6s ease-in-out infinite;
}
@keyframes duel-pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.04); }
}
.reaction-duel-modal {
.duel-arena {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 280px;
border-radius: 12px;
color: #fff;
user-select: none;
cursor: pointer;
touch-action: manipulation;
transition: background-color 0.05s;
&.waiting { background: #b02a37; }
&.go { background: #198754; }
&.done { background: #495057; }
&.early { background: #fd7e14; }
}
.duel-round {
opacity: 0.85;
}
.duel-signal {
font-size: 3rem;
font-weight: 700;
margin: 8px 0;
}
.duel-hint {
opacity: 0.85;
font-size: 0.9rem;
}
.duel-players {
columns: 2;
}
.duel-podium {
display: flex;
justify-content: center;
align-items: flex-end;
gap: 12px;
margin-bottom: 16px;
}
.duel-place {
flex: 0 1 160px;
padding: 12px 8px;
border-radius: 10px;
text-align: center;
background: var(--bs-tertiary-bg);
// Vítěz uprostřed a nejvýš, jako na stupních vítězů
&.place-1 { order: 2; padding-top: 28px; }
&.place-2 { order: 1; }
&.place-3 { order: 3; }
}
.duel-medal {
font-size: 2.2rem;
}
.duel-place-name {
font-weight: 700;
overflow-wrap: anywhere;
}
.duel-place-time {
opacity: 0.75;
font-size: 0.9rem;
}
.duel-last {
text-align: center;
}
.duel-results .duel-loser td {
background: rgba(220, 53, 69, 0.15);
}
}
// Bez zoomu dvojitým ťuknutím, jinak by iOS sérii ťuknutí na logo spolkl
.navbar-brand {
touch-action: manipulation;
}
// Skryté pole pro kód minihry — musí jít zaměřit (kvůli softwarové klávesnici), proto ne display: none.
// Písmo aspoň 16px, jinak iOS při zaměření přiblíží stránku.
.minigame-secret-input {
position: fixed;
top: 0;
left: 0;
width: 1px;
height: 1px;
padding: 0;
border: 0;
font-size: 16px;
opacity: 0;
pointer-events: none;
}
// Nenápadné potvrzení, že logo přijalo sérii kliknutí a čeká na tajné slovo
.navbar-brand.duel-armed {
display: inline-block;
animation: duel-wiggle 0.35s ease-in-out 2;
}
@keyframes duel-wiggle {
0%, 100% { transform: rotate(0); }
25% { transform: rotate(-4deg); }
75% { transform: rotate(4deg); }
}
-266
View File
@@ -1,266 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button, Modal, Table } from "react-bootstrap";
import { socket } from "../context/socket";
import { useAuth } from "../context/auth";
import { getToken } from "../Utils";
import { useGameIcon } from "../games/themeIcons";
import { useTouchDevice } from "../hooks/useTouchDevice";
import LobbyChat from "./LobbyChat";
import "./ReactionDuel.scss";
// Typy musí odpovídat server/src/reactionDuel.ts (stav chodí přes websocket, ne přes OpenAPI)
type DuelPhase = 'idle' | 'lobby' | 'waiting' | 'go' | 'roundResult' | 'finished';
type RoundResult = { ms: number | null, falseStart?: boolean };
type DuelPlayer = { login: string, rounds: RoundResult[], total: number };
type DuelState = {
phase: DuelPhase,
host?: string,
round: number,
totalRounds: number,
players: DuelPlayer[],
loser?: string,
winner?: string,
minPlayers: number,
};
const OPEN_EVENT = 'luncher:open-duel';
/** Otevře okno reakční hry. */
export const openReactionDuel = () => window.dispatchEvent(new Event(OPEN_EVENT));
const MEDALS = ['🥇', '🥈', '🥉'];
const formatResult = (r?: RoundResult) => {
if (!r) return '—';
if (r.falseStart) return 'předčasně';
if (r.ms == null) return 'nekliknuto';
return `${r.ms} ms`;
};
/** Reakční hra — lobby, kola a výsledky; časování drží server. */
export default function ReactionDuel() {
const auth = useAuth();
const login = auth?.login;
const [state, setState] = useState<DuelState | null>(null);
const [open, setOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
/** Kolo, ve kterém už tento klient kliknul (a zda předčasně). */
const [myClick, setMyClick] = useState<{ round: number, early: boolean } | null>(null);
const prevPhase = useRef<DuelPhase>('idle');
const icon = useGameIcon('reaction');
const touch = useTouchDevice();
const send = useCallback((event: string) => {
setError(null);
socket.emit(event, { token: getToken() });
}, []);
useEffect(() => {
const onState = (s: DuelState) => setState(s);
const onError = (msg: string) => setError(msg);
const onOpen = () => setOpen(true);
const sync = () => socket.emit('duel:sync');
socket.on('duel:state', onState);
socket.on('duel:error', onError);
socket.on('connect', sync);
window.addEventListener(OPEN_EVENT, onOpen);
sync();
return () => {
socket.off('duel:state', onState);
socket.off('duel:error', onError);
socket.off('connect', sync);
window.removeEventListener(OPEN_EVENT, onOpen);
};
}, []);
const isPlayer = !!login && !!state?.players.some(p => p.login === login);
const phase = state?.phase ?? 'idle';
const inRound = phase === 'waiting' || phase === 'go';
// Hráčům se okno otevře samo, jakmile hra začne
useEffect(() => {
if (prevPhase.current === 'lobby' && phase === 'waiting' && isPlayer) {
setOpen(true);
}
prevPhase.current = phase;
}, [phase, isPlayer]);
const click = useCallback(() => {
if (!state || !isPlayer || !inRound || myClick?.round === state.round) return;
setMyClick({ round: state.round, early: state.phase === 'waiting' });
send('duel:click');
}, [state, isPlayer, inRound, myClick, send]);
// Mezerník funguje stejně jako kliknutí
useEffect(() => {
if (!open || !inRound) return;
const onKey = (e: KeyboardEvent) => {
if (e.code === 'Space') {
e.preventDefault();
click();
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [open, inRound, click]);
if (!login) return null;
const showInvite = !open && phase === 'lobby' && !isPlayer;
const showReturn = !open && isPlayer && phase !== 'finished';
const clickedThisRound = myClick?.round === state?.round;
const ranked = [...(state?.players ?? [])].sort((a, b) => a.total - b.total);
const renderArena = () => {
if (!state) return null;
let cls = 'waiting';
let text = 'Počkej…';
if (phase === 'go') {
cls = 'go';
text = 'TEĎ!';
}
if (isPlayer && clickedThisRound) {
cls = myClick?.early ? 'early' : 'done';
text = myClick?.early ? 'Předčasný start! 😬' : 'Kliknuto ✔';
}
return (
<div
className={`duel-arena ${cls}`}
onPointerDown={click}
role="button"
tabIndex={0}
>
<div className="duel-round">Kolo {state.round}/{state.totalRounds}</div>
<div className="duel-signal">{text}</div>
{isPlayer
? <div className="duel-hint">{touch ? 'Ťukněte, až zezelená.' : 'Klikněte nebo zmáčkněte mezerník, až zezelená.'}</div>
: <div className="duel-hint">Sledujete hru.</div>}
</div>
);
};
const renderResults = (final: boolean) => (
<Table size="sm" className="duel-results">
<thead>
<tr>
<th>#</th>
<th>Hráč</th>
{Array.from({ length: state?.totalRounds ?? 0 }, (_, i) => <th key={i}>{i + 1}. kolo</th>)}
<th>Celkem</th>
</tr>
</thead>
<tbody>
{ranked.map((p, i) => (
<tr key={p.login} className={final && p.login === state?.loser ? 'duel-loser' : undefined}>
<td>{final && i < 3 ? MEDALS[i] : i + 1}</td>
<td>{p.login}{p.login === login && ' (vy)'}</td>
{Array.from({ length: state?.totalRounds ?? 0 }, (_, r) => <td key={r}>{formatResult(p.rounds[r])}</td>)}
<td><strong>{p.rounds.length ? `${p.total} ms` : '—'}</strong></td>
</tr>
))}
</tbody>
</Table>
);
const renderBody = () => {
switch (phase) {
case 'idle':
return (
<>
<p>
Hra má {state?.totalRounds ?? 3} kola — po náhodné chvíli se plocha rozsvítí zeleně
a počítá se, jak rychle kliknete. Předčasný start nebo nekliknutí znamená trestné 2 s.
Vyhrává nejnižší součet časů.
</p>
<p className="text-muted">Po založení lobby dostanou ostatní online pozvánku.</p>
</>
);
case 'lobby':
return (
<>
<p>Lobby založil(a) <strong>{state?.host}</strong>. Hráči ({state?.players.length}):</p>
<ul className="duel-players">
{state?.players.map(p => <li key={p.login}>{p.login}{p.login === state.host && ' 👑'}</li>)}
</ul>
{state && state.players.length < state.minPlayers &&
<p className="text-muted">Čeká se na další hráče…</p>}
{isPlayer && <LobbyChat game="duel" />}
</>
);
case 'waiting':
case 'go':
return renderArena();
case 'roundResult':
return (
<>
<p>Kolo {state?.round}/{state?.totalRounds} skončilo, další za chvíli…</p>
{renderResults(false)}
</>
);
case 'finished':
return (
<>
<div className="duel-podium">
{ranked.slice(0, 3).map((p, i) => (
<div key={p.login} className={`duel-place place-${i + 1}`}>
<div className="duel-medal">{MEDALS[i]}</div>
<div className="duel-place-name">{p.login}</div>
<div className="duel-place-time">{p.total} ms</div>
</div>
))}
</div>
{state?.loser && ranked.length > 3 &&
<p className="duel-last">🐢 Poslední: <strong>{state.loser}</strong></p>}
{renderResults(true)}
</>
);
}
};
const renderFooter = () => {
const buttons = [];
if (phase === 'idle' || phase === 'finished') {
buttons.push(<Button key="new" onClick={() => send('duel:join')}>{phase === 'idle' ? 'Založit lobby' : 'Nová hra'}</Button>);
}
if (phase === 'lobby') {
if (!isPlayer) {
buttons.push(<Button key="join" onClick={() => send('duel:join')}>Připojit se</Button>);
} else {
buttons.push(<Button key="leave" variant="outline-secondary" onClick={() => send('duel:leave')}>
{login === state?.host ? 'Zrušit lobby' : 'Odejít'}
</Button>);
if (login === state?.host) {
buttons.push(<Button key="start" onClick={() => send('duel:start')}
disabled={(state?.players.length ?? 0) < (state?.minPlayers ?? 2)}>Spustit hru</Button>);
}
}
}
buttons.push(<Button key="close" variant="secondary" onClick={() => setOpen(false)}>Zavřít</Button>);
return buttons;
};
return (
<>
{showInvite && (
<button className="duel-invite" onClick={() => setOpen(true)}>
{icon} <strong>{state?.host}</strong> zve na reakční hru — připojit se
</button>
)}
{showReturn && (
<button className="duel-invite" onClick={() => setOpen(true)}>
{icon} Reakční hra běží — zpět do hry
</button>
)}
<Modal show={open} onHide={() => setOpen(false)} size="lg" fullscreen="sm-down" className="reaction-duel-modal">
<Modal.Header closeButton>
<Modal.Title><h2>{icon} Reakční hra</h2></Modal.Title>
</Modal.Header>
<Modal.Body>
{renderBody()}
{error && <div className="text-danger mt-2">{error}</div>}
</Modal.Body>
<Modal.Footer>{renderFooter()}</Modal.Footer>
</Modal>
</>
);
}
-82
View File
@@ -1,82 +0,0 @@
// Pozvánka hada nad pozvánkou reakční hry, aby se nepřekrývaly
.duel-invite.snake-invite {
bottom: 68px;
}
.snake-game-modal {
.snake-board-wrap {
position: relative;
margin: 0 auto;
max-width: 768px;
}
.snake-board {
display: block;
width: 100%;
height: auto;
border-radius: 8px;
image-rendering: pixelated;
touch-action: none;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
}
// Kříž šipek pro dotykové ovládání
.snake-touch-pad {
display: grid;
grid-template-areas: ". up ." "left . right" ". down .";
grid-template-columns: repeat(3, calc(var(--touch-btn-size) + 8px));
grid-template-rows: repeat(3, var(--touch-btn-size));
gap: 4px;
justify-content: center;
margin: 8px 0 16px;
.up { grid-area: up; }
.left { grid-area: left; }
.right { grid-area: right; }
.down { grid-area: down; }
}
.snake-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 5rem;
font-weight: 700;
color: #fff;
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.6);
pointer-events: none;
}
.snake-status {
text-align: center;
opacity: 0.75;
margin: 8px 0;
}
.snake-scores {
max-width: 768px;
margin: 0 auto;
}
.snake-dead td {
opacity: 0.5;
}
.snake-dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 6px;
}
.snake-players {
columns: 2;
list-style: none;
padding-left: 0;
}
}
-361
View File
@@ -1,361 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button, Modal, Table } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCaretDown, faCaretLeft, faCaretRight, faCaretUp } from "@fortawesome/free-solid-svg-icons";
import { socket } from "../context/socket";
import { useAuth } from "../context/auth";
import { getToken } from "../Utils";
import { useGameIcon } from "../games/themeIcons";
import { useTouchDevice } from "../hooks/useTouchDevice";
import TouchButton from "./TouchButton";
import LobbyChat from "./LobbyChat";
import "./SnakeGame.scss";
// Typy musí odpovídat server/src/snakeGame.ts (stav chodí přes websocket, ne přes OpenAPI)
type Cell = [number, number];
type Direction = 'up' | 'down' | 'left' | 'right';
type SnakePhase = 'idle' | 'lobby' | 'countdown' | 'playing' | 'finished';
type SnakePlayer = { login: string, color: number, body: Cell[], alive: boolean, score: number, place?: number };
type SnakeState = {
phase: SnakePhase,
host?: string,
players: SnakePlayer[],
food: Cell[],
tick: number,
maxTicks: number,
countdown?: number,
width: number,
height: number,
minPlayers: number,
};
const OPEN_EVENT = 'luncher:open-snake';
/** Otevře okno hada. */
export const openSnakeGame = () => window.dispatchEvent(new Event(OPEN_EVENT));
const COLORS = ['#4ade80', '#60a5fa', '#f472b6', '#facc15', '#a78bfa', '#fb923c', '#2dd4bf', '#f87171'];
const MEDALS = ['🥇', '🥈', '🥉'];
const TICK_MS = 120;
const KEY_DIRECTIONS: Record<string, Direction> = {
ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right',
KeyW: 'up', KeyS: 'down', KeyA: 'left', KeyD: 'right',
};
/** Délka tahu prstem po ploše (px), od které se bere jako zatočení. */
const SWIPE_PX = 24;
/** Vykreslí hrací plochu do canvasu. */
function draw(canvas: HTMLCanvasElement, state: SnakeState, me?: string) {
const ctx = canvas.getContext('2d');
if (!ctx) return;
const cell = canvas.width / state.width;
ctx.fillStyle = '#111827';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#1f2937';
for (let x = 0; x < state.width; x++) {
for (let y = 0; y < state.height; y++) {
if ((x + y) % 2 === 0) ctx.fillRect(x * cell, y * cell, cell, cell);
}
}
for (const [x, y] of state.food) {
ctx.fillStyle = '#ef4444';
ctx.beginPath();
ctx.arc((x + 0.5) * cell, (y + 0.5) * cell, cell * 0.35, 0, Math.PI * 2);
ctx.fill();
}
for (const p of state.players) {
const color = COLORS[p.color % COLORS.length];
// Tělo tlumeně, hlava se kreslí zvlášť až nakonec
ctx.fillStyle = color;
ctx.globalAlpha = 0.65;
p.body.slice(1).forEach(([x, y]) => ctx.fillRect(x * cell + 2, y * cell + 2, cell - 4, cell - 4));
ctx.globalAlpha = 1;
if (p.body[0]) drawHead(ctx, p.body, cell, color, p.login === me);
}
}
/** Hlava: plná barva, zaoblená, přes okraj políčka a s očima ve směru pohybu. */
function drawHead(ctx: CanvasRenderingContext2D, body: Cell[], cell: number, color: string, mine: boolean) {
const [x, y] = body[0];
const neck = body[1];
const dx = neck ? Math.sign(x - neck[0]) : 1;
const dy = neck ? Math.sign(y - neck[1]) : 0;
const cx = (x + 0.5) * cell;
const cy = (y + 0.5) * cell;
const size = cell * 1.1;
ctx.fillStyle = color;
ctx.beginPath();
ctx.roundRect(cx - size / 2, cy - size / 2, size, size, cell * 0.35);
ctx.fill();
// Vlastní had má bílý obrys hlavy, ostatní tmavý — hlava se tak odliší od těla i pozadí
ctx.strokeStyle = mine ? '#fff' : '#0b0f19';
ctx.lineWidth = 2;
ctx.stroke();
// Oči: posunuté ve směru pohybu, rozložené kolmo na něj
const forward = cell * 0.18;
const side = cell * 0.22;
for (const s of [-1, 1]) {
const ex = cx + dx * forward + -dy * side * s;
const ey = cy + dy * forward + dx * side * s;
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc(ex, ey, cell * 0.14, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(ex + dx * cell * 0.05, ey + dy * cell * 0.05, cell * 0.07, 0, Math.PI * 2);
ctx.fill();
}
}
/** Multiplayerový had — lobby, hrací plocha a výsledky; simulaci drží server. */
export default function SnakeGame() {
const auth = useAuth();
const login = auth?.login;
const [state, setState] = useState<SnakeState | null>(null);
const [open, setOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const prevPhase = useRef<SnakePhase>('idle');
const icon = useGameIcon('snake');
const touch = useTouchDevice();
/** Rozpracovaný tah prstem — bod, od kterého se měří další zatočení, a poslední směr v tomto tahu. */
const swipe = useRef<{ pointerId: number, x: number, y: number, last?: Direction } | null>(null);
const send = useCallback((event: string, extra?: object) => {
setError(null);
socket.emit(event, { token: getToken(), ...extra });
}, []);
useEffect(() => {
const onState = (s: SnakeState) => setState(s);
const onError = (msg: string) => setError(msg);
const onOpen = () => setOpen(true);
const sync = () => socket.emit('snake:sync');
socket.on('snake:state', onState);
socket.on('snake:error', onError);
socket.on('connect', sync);
window.addEventListener(OPEN_EVENT, onOpen);
sync();
return () => {
socket.off('snake:state', onState);
socket.off('snake:error', onError);
socket.off('connect', sync);
window.removeEventListener(OPEN_EVENT, onOpen);
};
}, []);
// Průběžné snímky hry dostávají jen klienti s otevřeným oknem
useEffect(() => {
if (!open) return;
const watch = () => socket.emit('snake:watch');
watch();
socket.on('connect', watch);
return () => {
socket.off('connect', watch);
socket.emit('snake:unwatch');
};
}, [open]);
const isPlayer = !!login && !!state?.players.some(p => p.login === login);
const phase = state?.phase ?? 'idle';
const inGame = phase === 'countdown' || phase === 'playing';
const controllable = open && inGame && isPlayer;
const turn = useCallback((dir: Direction) => {
if (controllable) send('snake:turn', { dir });
}, [controllable, send]);
// Hráčům se okno otevře samo, jakmile hra začne
useEffect(() => {
if (prevPhase.current === 'lobby' && phase === 'countdown' && isPlayer) {
setOpen(true);
}
prevPhase.current = phase;
}, [phase, isPlayer]);
// Ovládání šipkami a WSAD
useEffect(() => {
if (!controllable) return;
const onKey = (e: KeyboardEvent) => {
const dir = KEY_DIRECTIONS[e.code];
if (!dir) return;
e.preventDefault();
if (!e.repeat) turn(dir);
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [controllable, turn]);
// Ovládání tahem prstu po ploše; v jednom tahu jde zatočit i víckrát (cik-cak)
const onBoardPointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (e.pointerType === 'mouse' || !controllable) return;
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
swipe.current = { pointerId: e.pointerId, x: e.clientX, y: e.clientY };
};
const onBoardPointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
const s = swipe.current;
if (!s || s.pointerId !== e.pointerId) return;
const dx = e.clientX - s.x;
const dy = e.clientY - s.y;
if (Math.max(Math.abs(dx), Math.abs(dy)) < SWIPE_PX) return;
const dir: Direction = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? 'right' : 'left') : (dy > 0 ? 'down' : 'up');
if (dir !== s.last) turn(dir);
swipe.current = { ...s, x: e.clientX, y: e.clientY, last: dir };
};
const onBoardPointerEnd = () => {
swipe.current = null;
};
useEffect(() => {
if (canvasRef.current && state && (inGame || phase === 'finished')) {
draw(canvasRef.current, state, login);
}
}, [state, inGame, phase, login]);
if (!login) return null;
const showInvite = !open && phase === 'lobby' && !isPlayer;
const showReturn = !open && isPlayer && inGame;
const ranked = [...(state?.players ?? [])].sort((a, b) => (a.place ?? 99) - (b.place ?? 99) || b.score - a.score);
const secondsLeft = state ? Math.max(0, Math.ceil((state.maxTicks - state.tick) * TICK_MS / 1000)) : 0;
const renderBoard = () => state && (
<div className="snake-board-wrap">
<canvas ref={canvasRef} className="snake-board" width={state.width * 24} height={state.height * 24}
onPointerDown={onBoardPointerDown} onPointerMove={onBoardPointerMove}
onPointerUp={onBoardPointerEnd} onPointerCancel={onBoardPointerEnd} />
{phase === 'countdown' && <div className="snake-overlay">{state.countdown}</div>}
</div>
);
const renderScores = () => (
<Table size="sm" className="snake-scores">
<thead>
<tr><th>#</th><th>Hráč</th><th>Jídla</th><th>Délka</th></tr>
</thead>
<tbody>
{ranked.map((p, i) => (
<tr key={p.login} className={p.alive || phase !== 'playing' ? undefined : 'snake-dead'}>
<td>{phase === 'finished' && i < 3 ? MEDALS[i] : (phase === 'finished' ? i + 1 : '')}</td>
<td>
<span className="snake-dot" style={{ background: COLORS[p.color % COLORS.length] }} />
{p.login}{p.login === login && ' (vy)'}{!p.alive && inGame && ' 💀'}
</td>
<td>{p.score}</td>
<td>{p.body.length || '—'}</td>
</tr>
))}
</tbody>
</Table>
);
const renderBody = () => {
switch (phase) {
case 'idle':
return (
<p>
Klasický had pro více hráčů. Ovládání šipkami nebo WSAD, na dotykovém displeji tahem prstu
po ploše nebo tlačítky. Jezte jídlo a vyhněte se zdem,
sobě i ostatním — čelní srážka zabije oba. Vyhrává ten, kdo přežije nejdéle;
hra trvá nejvýš 3 minuty. Hrát se dá i sólo.
</p>
);
case 'lobby':
return (
<>
<p>Lobby založil(a) <strong>{state?.host}</strong>. Hráči ({state?.players.length}):</p>
<ul className="snake-players">
{state?.players.map(p => (
<li key={p.login}>
<span className="snake-dot" style={{ background: COLORS[p.color % COLORS.length] }} />
{p.login}{p.login === state.host && ' 👑'}
</li>
))}
</ul>
{isPlayer && <LobbyChat game="snake" />}
</>
);
case 'countdown':
case 'playing':
return (
<>
{renderBoard()}
<div className="snake-status">
{isPlayer ? (touch ? 'Táhněte prstem po ploše' : 'Šipky / WSAD') : 'Sledujete hru'} · zbývá {secondsLeft} s
</div>
{touch && isPlayer && (
<div className="snake-touch-pad">
<TouchButton label="Nahoru" className="up" onPress={() => turn('up')}><FontAwesomeIcon icon={faCaretUp} /></TouchButton>
<TouchButton label="Doleva" className="left" onPress={() => turn('left')}><FontAwesomeIcon icon={faCaretLeft} /></TouchButton>
<TouchButton label="Doprava" className="right" onPress={() => turn('right')}><FontAwesomeIcon icon={faCaretRight} /></TouchButton>
<TouchButton label="Dolů" className="down" onPress={() => turn('down')}><FontAwesomeIcon icon={faCaretDown} /></TouchButton>
</div>
)}
{renderScores()}
</>
);
case 'finished':
return (
<>
{renderBoard()}
{renderScores()}
</>
);
}
};
const renderFooter = () => {
const buttons = [];
if (phase === 'idle' || phase === 'finished') {
buttons.push(<Button key="new" onClick={() => send('snake:join')}>{phase === 'idle' ? 'Založit lobby' : 'Nová hra'}</Button>);
}
if (phase === 'lobby') {
if (!isPlayer) {
buttons.push(<Button key="join" onClick={() => send('snake:join')}>Připojit se</Button>);
} else {
buttons.push(<Button key="leave" variant="outline-secondary" onClick={() => send('snake:leave')}>
{login === state?.host ? 'Zrušit lobby' : 'Odejít'}
</Button>);
if (login === state?.host) {
buttons.push(<Button key="start" onClick={() => send('snake:start')}
disabled={(state?.players.length ?? 0) < (state?.minPlayers ?? 1)}>Spustit hru</Button>);
}
}
}
buttons.push(<Button key="close" variant="secondary" onClick={() => setOpen(false)}>Zavřít</Button>);
return buttons;
};
return (
<>
{showInvite && (
<button className="duel-invite snake-invite" onClick={() => setOpen(true)}>
{icon} <strong>{state?.host}</strong> zve na hada — připojit se
</button>
)}
{showReturn && (
<button className="duel-invite snake-invite" onClick={() => setOpen(true)}>
{icon} Had běží — zpět do hry
</button>
)}
<Modal show={open} onHide={() => setOpen(false)} size="xl" fullscreen="sm-down" className="snake-game-modal">
<Modal.Header closeButton>
<Modal.Title><h2>{icon} Had</h2></Modal.Title>
</Modal.Header>
<Modal.Body>
{renderBody()}
{error && <div className="text-danger mt-2">{error}</div>}
</Modal.Body>
<Modal.Footer>{renderFooter()}</Modal.Footer>
</Modal>
</>
);
}
-182
View File
@@ -1,182 +0,0 @@
// Pozvánka tanků nad pozvánkami ostatních her, aby se nepřekrývaly
.duel-invite.tanks-invite {
bottom: 276px;
}
// Hřiště je široké 1120 px — okno je o kus širší než běžné xl, ať se plocha nezmenšuje
@media (min-width: 1200px) {
.tanks-game-modal .modal-dialog {
--bs-modal-width: min(1200px, calc(100vw - 32px));
}
}
.tanks-game-modal {
.tanks-board-wrap {
position: relative;
max-width: 1120px;
margin: 0 auto;
}
.tanks-board {
display: block;
width: 100%;
height: auto;
border-radius: 8px;
cursor: crosshair;
}
.tanks-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 5rem;
font-weight: 700;
color: #fff;
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.6);
pointer-events: none;
&.small {
font-size: 2rem;
}
}
.tanks-status {
text-align: center;
opacity: 0.75;
margin: 8px 0;
}
.tanks-scores {
max-width: 960px;
margin: 0 auto;
}
.tanks-out td {
opacity: 0.5;
}
.tanks-dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 6px;
}
.tanks-players {
list-style: none;
padding-left: 0;
&.two-columns {
columns: 2;
}
}
.tanks-switch {
padding: 0 6px;
line-height: 1;
text-decoration: none;
}
.tanks-teams {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
.tanks-teamscore {
display: flex;
justify-content: center;
align-items: baseline;
gap: 24px;
font-size: 1.1rem;
margin-bottom: 8px;
strong {
font-size: 1.8rem;
}
}
.tanks-legend {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 2px 18px;
list-style: none;
padding: 0;
margin: 8px 0 0;
font-size: 0.8rem;
opacity: 0.8;
}
.tanks-controls {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 4px 16px;
margin-top: 8px;
}
.tanks-equipment {
text-align: center;
font-size: 1.1rem;
margin-top: 8px;
}
.tanks-items {
white-space: nowrap;
}
.tanks-pickups {
columns: 2;
list-style: none;
padding-left: 0;
}
.tanks-config {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 8px;
.form-label {
margin-bottom: 2px;
font-size: 0.85rem;
}
.form-select {
min-width: 190px;
}
}
// Volby hry pod sebou: popisek vlevo, ovládání vpravo
.tanks-options {
display: grid;
grid-template-columns: max-content 1fr;
align-items: center;
gap: 8px 16px;
margin-bottom: 12px;
.form-check {
margin-bottom: 0;
}
}
.tanks-option-label {
font-size: 0.85rem;
opacity: 0.8;
}
.tanks-bot-picker {
display: flex;
gap: 6px;
.form-select {
width: auto;
min-width: 130px;
}
}
}
-565
View File
@@ -1,565 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button, Form, Modal, Table } from "react-bootstrap";
import { socket } from "../context/socket";
import { useAuth } from "../context/auth";
import { getToken } from "../Utils";
import { useGameIcon } from "../games/themeIcons";
import {
BIOMES, BotLevel, drawTanks, FLASH_MS, MuzzleFlash, PICKUPS, PickupType, tankColor, TankMode, TankPhase,
TankPlayer, TankState, TEAM_COLORS, TEAM_NAMES,
} from "../games/tankRender";
import LobbyChat from "./LobbyChat";
import "./TankGame.scss";
const OPEN_EVENT = 'luncher:open-tanks';
/** Otevře okno tanků. */
export const openTankGame = () => window.dispatchEvent(new Event(OPEN_EVENT));
/** Jak často se posílá poloha myši (ms). */
const AIM_SEND_MS = 30;
const MAX_TEAM_SIZE = 3;
const MEDALS = ['🥇', '🥈', '🥉'];
const MODES: { value: TankMode, label: string, description: string }[] = [
{ value: 'lastman', label: 'Poslední přeživší', description: 'Každý má 3 životy, vyhrává ten, komu nějaký zbyde.' },
{ value: 'deathmatch', label: 'Na čas', description: '3 minuty, po zničení se tank vrací do hry. Vyhrává nejvíc bodů.' },
];
const BOT_LEVELS: { value: BotLevel, label: string }[] = [
{ value: 'easy', label: 'Lehký' },
{ value: 'medium', label: 'Střední' },
{ value: 'hard', label: 'Těžký' },
];
/** Směrové: klávesa = směr jízdy na mapě; tankové: nahoru/dolů jízda vpřed/vzad, doleva/doprava otáčení. */
type Controls = 'directional' | 'tank';
const CONTROLS_KEY = 'tanks_controls';
const CONTROLS: { value: Controls, label: string, hint: string }[] = [
{ value: 'directional', label: 'Směrové', hint: 'šipky / WSAD jízda daným směrem' },
{ value: 'tank', label: 'Tankové', hint: '↑↓ / W S jízda, ←→ / A D otáčení' },
];
function getInitialControls(): Controls {
try {
return localStorage.getItem(CONTROLS_KEY) === 'tank' ? 'tank' : 'directional';
} catch {
// localStorage nedostupný
}
return 'directional';
}
const UP_KEYS = new Set(['ArrowUp', 'KeyW']);
const DOWN_KEYS = new Set(['ArrowDown', 'KeyS']);
const LEFT_KEYS = new Set(['ArrowLeft', 'KeyA']);
const RIGHT_KEYS = new Set(['ArrowRight', 'KeyD']);
const FIRE_KEYS = new Set(['Space']);
const MINE_KEYS = new Set(['KeyE']);
const GAME_KEYS = new Set([...UP_KEYS, ...DOWN_KEYS, ...LEFT_KEYS, ...RIGHT_KEYS, ...FIRE_KEYS, ...MINE_KEYS]);
const formatTime = (ms: number) => {
const s = Math.ceil(ms / 1000);
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
};
/** Aktivní efekty a munice hráče jako ikony (pro výpis výbavy a tabulku). */
function equipment(p: TankPlayer) {
const items: string[] = [];
const effect = (on: boolean, type: PickupType) => { if (on) items.push(PICKUPS[type].icon); };
effect(p.shield, 'shield');
effect(p.triple, 'triple');
effect(p.turbo, 'turbo');
effect(p.ghost, 'ghost');
effect(p.homing, 'homing');
if (p.rockets) items.push(`${PICKUPS.rocket.icon}${p.rockets}`);
if (p.mines) items.push(`${PICKUPS.mine.icon}${p.mines}`);
return items;
}
/** Tanky pro více hráčů — lobby, hrací plocha a výsledky; simulaci drží server. */
export default function TankGame() {
const auth = useAuth();
const login = auth?.login;
const [state, setState] = useState<TankState | null>(null);
const [open, setOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const [botLevel, setBotLevel] = useState<BotLevel>('medium');
const [controls, setControls] = useState<Controls>(getInitialControls);
const canvasRef = useRef<HTMLCanvasElement>(null);
const prevPhase = useRef<TankPhase>('idle');
const flashes = useRef<MuzzleFlash[]>([]);
const prevShots = useRef(new Map<string, number>());
const icon = useGameIcon('tanks');
const send = useCallback((event: string, extra?: object) => {
setError(null);
socket.emit(event, { token: getToken(), ...extra });
}, []);
useEffect(() => {
const onState = (s: TankState) => setState(s);
const onError = (msg: string) => setError(msg);
const onOpen = () => setOpen(true);
const sync = () => socket.emit('tanks:sync');
socket.on('tanks:state', onState);
socket.on('tanks:error', onError);
socket.on('connect', sync);
window.addEventListener(OPEN_EVENT, onOpen);
sync();
return () => {
socket.off('tanks:state', onState);
socket.off('tanks:error', onError);
socket.off('connect', sync);
window.removeEventListener(OPEN_EVENT, onOpen);
};
}, []);
// Průběžné snímky hry dostávají jen klienti s otevřeným oknem
useEffect(() => {
if (!open) return;
const watch = () => socket.emit('tanks:watch');
watch();
socket.on('connect', watch);
return () => {
socket.off('connect', watch);
socket.emit('tanks:unwatch');
};
}, [open]);
const isPlayer = !!login && !!state?.players.some(p => p.login === login);
const isHost = !!login && login === state?.host;
const phase = state?.phase ?? 'idle';
const inGame = phase === 'countdown' || phase === 'playing';
const me = state?.players.find(p => p.login === login);
// Hráčům se okno otevře samo, jakmile hra začne
useEffect(() => {
if (prevPhase.current === 'lobby' && phase === 'countdown' && isPlayer) {
setOpen(true);
}
prevPhase.current = phase;
}, [phase, isPlayer]);
// Ovládání: držené klávesy a tlačítko myši → stav ovládání, posílá se jen při změně
useEffect(() => {
if (!open || !inGame || !isPlayer) return;
const pressed = new Set<string>();
let mouseFire = false;
let sent = '';
const any = (keys: Set<string>) => [...pressed].some(k => keys.has(k));
const update = () => {
const x = (any(RIGHT_KEYS) ? 1 : 0) - (any(LEFT_KEYS) ? 1 : 0);
const y = (any(DOWN_KEYS) ? 1 : 0) - (any(UP_KEYS) ? 1 : 0);
const fire = any(FIRE_KEYS) || mouseFire;
const input = controls === 'tank' ? { drive: -y, turn: x, fire } : { dx: x, dy: y, fire };
const key = JSON.stringify(input);
if (key === sent) return;
sent = key;
send('tanks:input', input);
};
const onDown = (e: KeyboardEvent) => {
if (!GAME_KEYS.has(e.code)) return;
// Mezerník by jinak "klikl" na tlačítko s fokusem
e.preventDefault();
if (pressed.has(e.code)) return;
pressed.add(e.code);
if (MINE_KEYS.has(e.code)) send('tanks:mine');
update();
};
const onUp = (e: KeyboardEvent) => {
if (GAME_KEYS.has(e.code)) e.preventDefault();
if (!pressed.delete(e.code)) return;
update();
};
// Levé tlačítko nad hrací plochou střílí, dokud se nepustí (puštění kdekoli); pravé položí minu
const onMouseDown = (e: MouseEvent) => {
if (e.target !== canvasRef.current) return;
if (e.button === 2) {
e.preventDefault();
send('tanks:mine');
return;
}
if (e.button !== 0) return;
e.preventDefault();
mouseFire = true;
update();
};
const onMouseUp = (e: MouseEvent) => {
if (e.button !== 0 || !mouseFire) return;
mouseFire = false;
update();
};
const onContextMenu = (e: MouseEvent) => {
if (e.target === canvasRef.current) e.preventDefault();
};
const onBlur = () => {
pressed.clear();
mouseFire = false;
update();
};
(document.activeElement as HTMLElement | null)?.blur?.();
window.addEventListener('keydown', onDown);
window.addEventListener('keyup', onUp);
window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mouseup', onMouseUp);
window.addEventListener('contextmenu', onContextMenu);
window.addEventListener('blur', onBlur);
window.addEventListener('pagehide', onBlur);
return () => {
// Server si pamatuje poslední stav — bez puštění by tank jel dál (zavřené okno, pád stránky)
onBlur();
window.removeEventListener('pagehide', onBlur);
window.removeEventListener('keydown', onDown);
window.removeEventListener('keyup', onUp);
window.removeEventListener('mousedown', onMouseDown);
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('contextmenu', onContextMenu);
window.removeEventListener('blur', onBlur);
};
}, [open, inGame, isPlayer, send, controls]);
const changeControls = (value: Controls) => {
setControls(value);
try {
localStorage.setItem(CONTROLS_KEY, value);
} catch {
// localStorage nedostupný
}
};
// Míření myší: kurzor nad hrací plochou natáčí věž, mimo ni se věž vrátí do směru jízdy
useEffect(() => {
if (!open || !inGame || !isPlayer) return;
let latest: [number, number] | null = null;
let sent = '';
const onMove = (e: PointerEvent) => {
const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
const inside = e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom;
latest = inside
? [Math.round((e.clientX - rect.left) / rect.width * canvas.width), Math.round((e.clientY - rect.top) / rect.height * canvas.height)]
: null;
};
const id = window.setInterval(() => {
const key = JSON.stringify(latest);
if (key === sent) return;
sent = key;
send('tanks:aim', latest ? { x: latest[0], y: latest[1] } : { x: null });
}, AIM_SEND_MS);
window.addEventListener('pointermove', onMove);
return () => {
window.clearInterval(id);
window.removeEventListener('pointermove', onMove);
};
}, [open, inGame, isPlayer, send]);
// Záblesky výstřelů: podle změny počítadla výstřelů u hráče
useEffect(() => {
if (!state) return;
const now = performance.now();
for (const p of state.players) {
const before = prevShots.current.get(p.login);
if (before !== undefined && p.shots > before && state.phase === 'playing') {
flashes.current.push({ login: p.login, start: now });
}
prevShots.current.set(p.login, p.shots);
}
flashes.current = flashes.current.filter(f => now - f.start < FLASH_MS);
}, [state]);
useEffect(() => {
if (!state || !(inGame || phase === 'finished')) return;
const draw = () => canvasRef.current && drawTanks(canvasRef.current, state, flashes.current, login);
draw();
// Při odpočtu chodí stav jen jednou za sekundu — značka vlastního tanku se animuje překreslováním
if (phase !== 'countdown') return;
let frame = requestAnimationFrame(function loop() {
draw();
frame = requestAnimationFrame(loop);
});
return () => cancelAnimationFrame(frame);
}, [state, inGame, phase, login]);
if (!login) return null;
const mode = MODES.find(m => m.value === state?.mode) ?? MODES[0];
const mapOf = (id?: string) => state?.maps.find(m => m.id === id);
const mapLabel = (m?: { name: string, biome: keyof typeof BIOMES }) => m ? `${BIOMES[m.biome].icon} ${m.name}` : '🎲 Náhodná';
const mapName = mapLabel(state?.mapId === 'random' ? undefined : mapOf(state?.mapId));
const showInvite = !open && phase === 'lobby' && !isPlayer && (state?.players.length ?? 0) < (state?.maxPlayers ?? 0);
const showReturn = !open && isPlayer && inGame;
const ranked = [...(state?.players ?? [])].sort((a, b) => phase === 'finished'
? (a.place ?? 99) - (b.place ?? 99)
: state?.mode === 'lastman'
? (b.lives ?? 0) - (a.lives ?? 0) || b.kills - a.kills
: b.score - a.score || a.deaths - b.deaths);
const teamDot = (team: 0 | 1) => <span className="tanks-dot" style={{ background: TEAM_COLORS[team][0] }} />;
const winnerText = () => {
if (!state?.teams) return `🏆 ${ranked[0]?.login}`;
if (state.winnerTeam === undefined || state.winnerTeam < 0) return '🤝 Remíza';
return `🏆 Vyhrává tým ${TEAM_NAMES[state.winnerTeam]}`;
};
const renderBoard = () => state && (
<div className="tanks-layout">
{state.teams && state.teamScores && (
<div className="tanks-teamscore">
<span style={{ color: TEAM_COLORS[0][0] }}>{TEAM_NAMES[0]}</span>
<strong>{state.teamScores[0]} : {state.teamScores[1]}</strong>
<span style={{ color: TEAM_COLORS[1][0] }}>{TEAM_NAMES[1]}</span>
</div>
)}
<div className="tanks-board-wrap">
<canvas ref={canvasRef} className="tanks-board" width={state.width} height={state.height} />
{phase === 'countdown' && <div className="tanks-overlay">{state.countdown}</div>}
{phase === 'playing' && me && !me.alive && me.respawnIn !== undefined && (
<div className="tanks-overlay small">Zničen — návrat za {Math.ceil(me.respawnIn / 1000)} s</div>
)}
{phase === 'playing' && me && !me.alive && me.respawnIn === undefined && (
<div className="tanks-overlay small">Vypadli jste — sledujete hru</div>
)}
{phase === 'finished' && <div className="tanks-overlay small">{winnerText()}</div>}
</div>
{inGame && me?.alive && (
<div className="tanks-equipment">
Výbava: {equipment(me).length ? equipment(me).join(' ') : <span className="text-muted">nic — sbírejte bonusy</span>}
</div>
)}
<div className="tanks-status">
{mode.label}{state.teams && ' v týmech'}{state.bounce && ' · odrazy'}{state.hardcore && ' · 🌑 hardcore'} · {mapName}{inGame && ` · zbývá ${formatTime(state.timeLeftMs)}`}
{inGame && (isPlayer
? ` · ${CONTROLS.find(c => c.value === controls)!.hint}, myš míření, klik / mezerník střelba, E / pravé tlačítko mina`
: ' · sledujete hru')}
</div>
{inGame && isPlayer && renderControls()}
{inGame && (
<ul className="tanks-legend">
{(Object.entries(PICKUPS) as [PickupType, typeof PICKUPS[PickupType]][])
.filter(([type]) => type !== 'heart' || state.mode === 'lastman')
.map(([type, p]) => <li key={type}>{p.icon} {p.label}</li>)}
</ul>
)}
{renderScores()}
</div>
);
/** Volba ovládání — osobní nastavení hráče, pamatuje si ho prohlížeč. */
const renderControls = () => (
<div className="tanks-controls">
<span className="tanks-option-label">Ovládání</span>
{CONTROLS.map(c => (
<Form.Check key={c.value} inline type="radio" id={`tanks-controls-${c.value}`} name="tanks-controls"
label={c.label} title={c.hint} checked={controls === c.value} onChange={() => changeControls(c.value)} />
))}
</div>
);
const renderScores = () => (
<Table size="sm" className="tanks-scores">
<thead>
<tr>
<th>#</th>
<th>Hráč</th>
{state?.mode === 'lastman' ? <th>Životy</th> : <th>Body</th>}
<th>Zničil(a)</th>
<th>Zničen(a)</th>
</tr>
</thead>
<tbody>
{ranked.map((p, i) => (
<tr key={p.login} className={state?.mode === 'lastman' && p.lives === 0 && inGame ? 'tanks-out' : undefined}>
<td>{phase === 'finished' ? (i < 3 ? MEDALS[i] : i + 1) : ''}</td>
<td>
<span className="tanks-dot" style={{ background: tankColor(p) }} />
{p.login}{p.login === login && ' (vy)'}
{state?.teams && p.team !== undefined && <span className="text-muted"> · {TEAM_NAMES[p.team]}</span>}
{p.alive && inGame && equipment(p).length > 0 && <span className="tanks-items"> {equipment(p).join(' ')}</span>}
</td>
<td>{state?.mode === 'lastman' ? '❤️'.repeat(p.lives ?? 0) || '💀' : p.score}</td>
<td>{p.kills}</td>
<td>{p.deaths}</td>
</tr>
))}
</tbody>
</Table>
);
const renderPlayer = (p: TankPlayer) => (
<li key={p.login}>
<span className="tanks-dot" style={{ background: tankColor(p) }} />
{p.login}{p.login === state?.host && ' 👑'}
{state?.teams && (isHost || p.login === login) && (
<Button size="sm" variant="link" className="tanks-switch" title="Přesunout do druhého týmu"
onClick={() => send('tanks:team', { target: p.login })}>⇄</Button>
)}
</li>
);
const renderLobby = () => state && (
<>
<p>Lobby založil(a) <strong>{state.host}</strong>. Hráči ({state.players.length}/{state.maxPlayers}):</p>
{state.teams ? (
<div className="tanks-teams">
{([0, 1] as const).map(team => {
const members = state.players.filter(p => p.team === team);
return (
<div key={team}>
<strong>{teamDot(team)}{TEAM_NAMES[team]}</strong> ({members.length}/{MAX_TEAM_SIZE})
<ul className="tanks-players">{members.map(renderPlayer)}</ul>
</div>
);
})}
</div>
) : (
<ul className="tanks-players two-columns">{state.players.map(renderPlayer)}</ul>
)}
{isHost ? (
<>
<div className="tanks-config">
<Form.Group>
<Form.Label>Režim</Form.Label>
<Form.Select size="sm" value={state.mode} onChange={e => send('tanks:configure', { mode: e.target.value })}>
{MODES.map(m => <option key={m.value} value={m.value}>{m.label}</option>)}
</Form.Select>
</Form.Group>
<Form.Group>
<Form.Label>Mapa</Form.Label>
<Form.Select size="sm" value={state.mapId} onChange={e => send('tanks:configure', { mapId: e.target.value })}>
<option value="random">{mapLabel()}</option>
{state.maps.map(m => <option key={m.id} value={m.id}>{mapLabel(m)}</option>)}
</Form.Select>
</Form.Group>
</div>
<div className="tanks-options">
<span className="tanks-option-label">Hráči</span>
<div>
<Form.Check inline type="radio" id="tanks-solo" name="tanks-teams" label="Každý sám za sebe"
checked={!state.teams} onChange={() => send('tanks:configure', { teams: false })} />
<Form.Check inline type="radio" id="tanks-teams" name="tanks-teams" label="Dva týmy"
checked={state.teams} onChange={() => send('tanks:configure', { teams: true })} />
</div>
<span className="tanks-option-label">Střely</span>
<Form.Check type="switch" id="tanks-bounce" label="Odráží se od zdí" checked={state.bounce}
onChange={e => send('tanks:configure', { bounce: e.target.checked })} />
<span className="tanks-option-label">Hardcore</span>
<Form.Check type="switch" id="tanks-hardcore" label="🌑 Tma — vidět je jen okolí tanku" checked={state.hardcore}
onChange={e => send('tanks:configure', { hardcore: e.target.checked })} />
{(state.players.length < state.maxPlayers || state.players.some(p => p.bot)) && (
<>
<span className="tanks-option-label">Boti</span>
<div className="tanks-bot-picker">
{state.players.length < state.maxPlayers && (
<>
<Form.Select size="sm" value={botLevel} onChange={e => setBotLevel(e.target.value as BotLevel)}>
{BOT_LEVELS.map(l => <option key={l.value} value={l.value}>{l.label}</option>)}
</Form.Select>
<Button size="sm" variant="outline-primary" onClick={() => send('tanks:addBot', { level: botLevel })}>
Přidat bota
</Button>
</>
)}
{state.players.some(p => p.bot) && (
<Button size="sm" variant="outline-secondary" onClick={() => send('tanks:removeBots')}>Odebrat boty</Button>
)}
</div>
</>
)}
</div>
</>
) : (
<p>
Režim: <strong>{mode.label}{state.teams && ' v týmech'}{state.bounce && ', odrazy'}{state.hardcore && ', 🌑 hardcore'}</strong>
{' · '}mapa: <strong>{mapName}</strong>
</p>
)}
<p className="text-muted small mb-0">
{mode.description}{state.teams && ' Spoluhráči se navzájem nezraní, týmy začínají každý na své půlce mapy.'}
{state.bounce && ' Střely se odráží od zdí — pozor na vlastní!'}
{state.hardcore && ' V aréně je tma: vidíte jen okolí tanku a kužel reflektoru ve směru věže, světlo zastaví zdi a bedny.'
+ (state.teams ? ' Co osvítí spoluhráč, vidíte také.' : '') + ' Výbuchy a výstřely prosvítí i tmou.'}
</p>
{isPlayer && renderControls()}
{isPlayer && <LobbyChat game="tanks" />}
</>
);
const renderBody = () => {
switch (phase) {
case 'idle':
return (
<>
<p>
Tanková bitva pro více hráčů. Jezdí se šipkami nebo WSAD (směrově, nebo po tankovém —
vpřed/vzad a otáčení), věž míří za myší a střílí se kliknutím nebo mezerníkem. Bedny se dají rozstřílet, přes vodu se nedá projet (ale dá se
přes ni střílet) a bláto, sníh, písek nebo porost zpomalují. Hraje se na poslední přeživší
nebo na čas, sólo i v týmech, volitelně s odrážením střel od zdí nebo potmě (hardcore);
když není s kým hrát, přidejte si do lobby boty.
</p>
<p className="mb-1">Bonusy:</p>
<ul className="tanks-pickups">
{Object.values(PICKUPS).map(p => <li key={p.icon}>{p.icon} {p.label}</li>)}
</ul>
{renderControls()}
</>
);
case 'lobby':
return renderLobby();
default:
return renderBoard();
}
};
const startBlocked = () => {
if (!state) return true;
if (state.players.length < state.minPlayers) return true;
return state.teams && state.minPlayers > 1 && [0, 1].some(t => !state.players.some(p => p.team === t));
};
const renderFooter = () => {
const buttons = [];
if (phase === 'idle' || phase === 'finished') {
buttons.push(<Button key="new" onClick={() => send('tanks:join')}>{phase === 'idle' ? 'Založit lobby' : 'Nová hra'}</Button>);
}
if (phase === 'lobby') {
if (!isPlayer) {
buttons.push(<Button key="join" onClick={() => send('tanks:join')}
disabled={(state?.players.length ?? 0) >= (state?.maxPlayers ?? 0)}>Připojit se</Button>);
} else {
buttons.push(<Button key="leave" variant="outline-secondary" onClick={() => send('tanks:leave')}>
{isHost ? 'Zrušit lobby' : 'Odejít'}
</Button>);
if (isHost) {
buttons.push(<Button key="start" onClick={() => send('tanks:start')} disabled={startBlocked()}>Spustit hru</Button>);
}
}
}
buttons.push(<Button key="close" variant="secondary" onClick={() => setOpen(false)}>Zavřít</Button>);
return buttons;
};
return (
<>
{showInvite && (
<button className="duel-invite tanks-invite" onClick={() => setOpen(true)}>
{icon} <strong>{state?.host}</strong> zve na tanky — připojit se
</button>
)}
{showReturn && (
<button className="duel-invite tanks-invite" onClick={() => setOpen(true)}>
{icon} Tanky běží — zpět do hry
</button>
)}
<Modal show={open} onHide={() => setOpen(false)} size="xl" className="tanks-game-modal">
<Modal.Header closeButton>
<Modal.Title><h2>{icon} Tanky</h2></Modal.Title>
</Modal.Header>
<Modal.Body>
{renderBody()}
{error && <div className="text-danger mt-2">{error}</div>}
</Modal.Body>
<Modal.Footer>{renderFooter()}</Modal.Footer>
</Modal>
</>
);
}
-193
View File
@@ -1,193 +0,0 @@
// Pozvánka Tetrisu nad pozvánkami ostatních her, aby se nepřekrývaly
.duel-invite.tetris-invite {
bottom: 120px;
}
.tetris-game-modal {
.tetris-layout {
display: flex;
flex-wrap: wrap;
gap: 24px;
justify-content: center;
align-items: flex-start;
}
.tetris-own-col {
display: flex;
flex-direction: column;
gap: 12px;
}
.tetris-own {
display: flex;
gap: 16px;
// Ovládání pod deskou může být na tabletu širší než deska s postranním panelem
align-self: center;
}
.tetris-board-wrap {
position: relative;
}
.tetris-board {
display: block;
border-radius: 6px;
// Gesta prstem nesmí posouvat ani přibližovat stránku
touch-action: none;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
}
.tetris-touch-pad {
display: flex;
justify-content: space-between;
gap: 12px;
}
.tetris-touch-group {
display: flex;
gap: calc(var(--touch-btn-size) * 0.12);
}
.tetris-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 5rem;
font-weight: 700;
color: #fff;
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.6);
background: rgba(0, 0, 0, 0.25);
pointer-events: none;
&.small {
font-size: 2.2rem;
}
}
.tetris-flash {
position: absolute;
top: 8px;
left: 0;
right: 0;
text-align: center;
font-weight: 700;
color: #fca5a5;
text-shadow: 0 1px 6px rgba(0, 0, 0, 0.8);
pointer-events: none;
}
.tetris-side {
min-width: 110px;
}
.tetris-label {
font-size: 0.8rem;
text-transform: uppercase;
opacity: 0.6;
margin-top: 10px;
}
.tetris-value {
font-size: 1.4rem;
font-weight: 700;
}
.tetris-help {
margin-top: 16px;
font-size: 0.8rem;
opacity: 0.7;
line-height: 1.5;
}
.tetris-opponents {
display: flex;
flex-wrap: wrap;
gap: 12px;
max-width: 440px;
}
.tetris-mini {
text-align: center;
canvas {
display: block;
border-radius: 4px;
}
&.dead canvas {
opacity: 0.35;
}
}
.tetris-mini-name {
font-size: 0.8rem;
font-weight: 600;
max-width: 90px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tetris-mini-score {
font-size: 0.75rem;
opacity: 0.7;
}
.tetris-players {
columns: 2;
}
// Na dotykovém displeji se deska zmenší, aby se i s ovládáním vešla na výšku telefonu
@media (any-pointer: coarse) {
.tetris-own {
gap: 12px;
}
.tetris-board {
width: auto;
// Výška okna bez hlavičky, patičky, odstupů a řady tlačítek
height: clamp(280px, calc(100dvh - 278px - var(--touch-btn-size)), #{20 * 26px});
}
.tetris-side {
min-width: 90px;
}
}
@media (max-width: 575.98px) {
.modal-body {
padding: 12px;
}
.tetris-layout {
gap: 12px;
}
}
}
// Bootstrap dává oknu mezi 576 a 992 px (tablet na výšku) jen 500 px a větší dotyková tlačítka by se nevešla
@media (min-width: 576px) and (max-width: 991.98px) {
.tetris-game-modal .modal-dialog {
--bs-modal-width: 640px;
}
}
.tetris-game-modal .tetris-settings {
display: flex;
flex-wrap: wrap;
gap: 16px;
max-width: 640px;
> div {
flex: 1 1 180px;
}
.form-label {
margin-bottom: 2px;
font-weight: 600;
}
}
-663
View File
@@ -1,663 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button, Form, Modal, Table } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faAnglesDown, faCaretDown, faCaretLeft, faCaretRight, faRotateLeft, faRotateRight } from "@fortawesome/free-solid-svg-icons";
import { socket } from "../context/socket";
import { useAuth } from "../context/auth";
import { getToken } from "../Utils";
import { TetrisSession, WIDTH, HEIGHT, pieceCells, Piece } from "../games/tetrisEngine";
import { useGameIcon } from "../games/themeIcons";
import { useTouchDevice } from "../hooks/useTouchDevice";
import TouchButton from "./TouchButton";
import LobbyChat from "./LobbyChat";
import "./TetrisGame.scss";
// Typy musí odpovídat server/src/tetrisGame.ts (stav chodí přes websocket, ne přes OpenAPI)
type TetrisPhase = 'idle' | 'lobby' | 'countdown' | 'playing' | 'finished';
type TetrisPlayer = { login: string, board: string, score: number, lines: number, alive: boolean, place?: number };
type TetrisTargeting = 'random' | 'even' | 'payback';
type TetrisWinMode = 'survival' | 'score';
type TetrisSettings = { targeting: TetrisTargeting, winMode: TetrisWinMode, timeLimit: number };
type TetrisState = {
phase: TetrisPhase,
host?: string,
players: TetrisPlayer[],
seed?: number,
countdown?: number,
minPlayers: number,
settings: TetrisSettings,
remainingMs?: number,
};
type GarbageEvent = { target: string, from: string, lines: number };
const OPEN_EVENT = 'luncher:open-tetris';
const TARGETING_LABELS: Record<TetrisTargeting, { label: string, help: string }> = {
random: { label: 'Náhodně (Random)', help: 'útok jde náhodnému soupeři' },
even: { label: 'Rovnoměrně (Even)', help: 'útok jde soupeři, který zatím dostal nejméně odpadu' },
payback: { label: 'Oplácení (Payback)', help: 'útok jde tomu, kdo vás naposledy napadl, jinak rovnoměrně' },
};
const WIN_MODE_LABELS: Record<TetrisWinMode, string> = {
survival: 'Poslední ve hře (Last man standing)',
score: 'Nejvyšší skóre',
};
/** Musí odpovídat TIME_LIMITS na serveru (s). */
const TIME_LIMITS = [120, 180, 300];
const formatTime = (ms: number) => {
const total = Math.ceil(ms / 1000);
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
};
/** Otevře okno Tetrisu. */
export const openTetrisGame = () => window.dispatchEvent(new Event(OPEN_EVENT));
/** Barvy kostek I, O, T, S, Z, J, L a odpadu (index = hodnota buňky). */
const COLORS = ['', '#22d3ee', '#facc15', '#a855f7', '#22c55e', '#ef4444', '#3b82f6', '#f97316', '#6b7280'];
const MEDALS = ['🥇', '🥈', '🥉'];
const CELL = 26;
const MINI_CELL = 9;
/** Jak často se soupeřům posílá deska s padající kostkou (ms). */
const SNAPSHOT_MS = 250;
/**
* Deska se posílá i časovačem — běží i v neaktivním tabu (na rozdíl od requestAnimationFrame),
* takže server pozná, že hráč pořád hraje. Musí být výrazně kratší než PLAYER_TIMEOUT_MS na serveru.
*/
const HEARTBEAT_MS = 2000;
type Action = 'left' | 'right' | 'down' | 'rotate' | 'rotateBack' | 'drop';
const KEYS: Record<string, Action> = {
ArrowLeft: 'left', KeyA: 'left',
ArrowRight: 'right', KeyD: 'right',
ArrowDown: 'down', KeyS: 'down',
ArrowUp: 'rotate', KeyW: 'rotate', KeyX: 'rotate',
KeyZ: 'rotateBack', KeyY: 'rotateBack',
Space: 'drop',
};
/** Akce, které se opakují při podržení klávesy. */
const REPEATABLE = new Set<Action>(['left', 'right', 'down']);
// Dotyková gesta na desce: ťuknutí otočí, tažení posouvá o políčka, švihnutí dolů shodí
/** Posun prstu (px), do kterého se dotyk ještě bere jako ťuknutí. */
const TAP_SLOP_PX = 10;
/** Delší dotyk bez pohybu už není ťuknutí. */
const TAP_MAX_MS = 300;
/** Nejmenší krok tažení o jedno políčko (px) — na malé desce by jinak byl příliš citlivý. */
const MIN_STEP_PX = 14;
/** Švihnutí = pohyb dolů aspoň touto rychlostí (px/ms) za posledních FLICK_WINDOW_MS. */
const FLICK_SPEED = 0.7;
const FLICK_MIN_PX = 30;
const FLICK_WINDOW_MS = 100;
/** Rozpracované dotykové gesto na desce. */
type Gesture = {
pointerId: number,
/** Kostka, se kterou gesto začalo — když mezitím dopadne, zbytek gesta se ignoruje. */
pieceNo: number,
startX: number,
startY: number,
startTime: number,
/** Bod, od kterého se měří další krok o políčko. */
anchorX: number,
anchorY: number,
moved: boolean,
/** Poslední polohy prstu pro rychlost švihnutí. */
trail: { y: number, t: number }[],
};
function drawCell(ctx: CanvasRenderingContext2D, x: number, y: number, size: number, value: number) {
ctx.fillStyle = COLORS[value];
ctx.fillRect(x * size + 1, y * size + 1, size - 2, size - 2);
}
/** Vykreslí desku zadanou řetězcem (soupeři) nebo polem (vlastní hra). */
function drawBoard(canvas: HTMLCanvasElement, cells: ArrayLike<number | string>, size: number, piece?: Piece | null, ghost?: Piece | null) {
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.fillStyle = '#111827';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < WIDTH * HEIGHT; i++) {
const v = Number(cells[i]);
if (v) drawCell(ctx, i % WIDTH, Math.floor(i / WIDTH), size, v);
}
if (ghost) {
ctx.globalAlpha = 0.25;
pieceCells(ghost).forEach(([x, y]) => y >= 0 && drawCell(ctx, x, y, size, ghost.type + 1));
ctx.globalAlpha = 1;
}
if (piece) {
pieceCells(piece).forEach(([x, y]) => y >= 0 && drawCell(ctx, x, y, size, piece.type + 1));
}
}
/** Náhled příští kostky. */
function drawNext(canvas: HTMLCanvasElement, type: number) {
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const cells = pieceCells({ type, rot: 0, x: 0, y: 0 });
const minX = Math.min(...cells.map(c => c[0]));
const minY = Math.min(...cells.map(c => c[1]));
cells.forEach(([x, y]) => drawCell(ctx, x - minX + 0.5, y - minY + 0.5, 20, type + 1));
}
/** Malá deska soupeře. */
function MiniBoard({ player }: { player: TetrisPlayer }) {
const ref = useRef<HTMLCanvasElement>(null);
useEffect(() => {
if (ref.current) drawBoard(ref.current, player.board, MINI_CELL);
}, [player.board]);
return (
<div className={`tetris-mini ${player.alive ? '' : 'dead'}`}>
<canvas ref={ref} width={WIDTH * MINI_CELL} height={HEIGHT * MINI_CELL} />
<div className="tetris-mini-name">{player.login}{!player.alive && ' 💀'}</div>
<div className="tetris-mini-score">{player.score}</div>
</div>
);
}
/** Multiplayerový Tetris (battle) — vlastní deska běží v prohlížeči, server koordinuje hru. */
export default function TetrisGame() {
const auth = useAuth();
const login = auth?.login;
const [state, setState] = useState<TetrisState | null>(null);
const [open, setOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const [flash, setFlash] = useState<string | null>(null);
/** Překreslení postranních údajů (skóre, řádky) po změně v session. */
const [, setVersion] = useState(0);
/** Trénink: hra jen v prohlížeči, bez serveru a soupeřů. */
const [practice, setPractice] = useState(false);
const sessionRef = useRef<TetrisSession | null>(null);
const sessionSeed = useRef<number | undefined>(undefined);
const boardRef = useRef<HTMLCanvasElement>(null);
const nextRef = useRef<HTMLCanvasElement>(null);
const prevPhase = useRef<TetrisPhase>('idle');
/** Konec hry na skóre v čase prohlížeče (ze zbývajícího času, ať nevadí rozdíl hodin se serverem). */
const deadline = useRef<number | undefined>(undefined);
const [now, setNow] = useState(() => Date.now());
const icon = useGameIcon('tetris');
const touch = useTouchDevice();
const gesture = useRef<Gesture | null>(null);
const send = useCallback((event: string, extra?: object) => {
setError(null);
socket.emit(event, { token: getToken(), ...extra });
}, []);
const sendSnapshot = useCallback(() => {
const s = sessionRef.current;
if (s) send('tetris:update', { board: s.snapshot(), score: s.score, lines: s.lines });
}, [send]);
useEffect(() => {
const onState = (s: TetrisState) => {
deadline.current = s.remainingMs !== undefined ? Date.now() + s.remainingMs : undefined;
setState(s);
};
const onError = (msg: string) => setError(msg);
const onOpen = () => setOpen(true);
const sync = () => socket.emit('tetris:sync');
socket.on('tetris:state', onState);
socket.on('tetris:error', onError);
socket.on('connect', sync);
window.addEventListener(OPEN_EVENT, onOpen);
sync();
return () => {
socket.off('tetris:state', onState);
socket.off('tetris:error', onError);
socket.off('connect', sync);
window.removeEventListener(OPEN_EVENT, onOpen);
};
}, []);
// Průběžné desky soupeřů a útoky dostávají jen klienti s otevřeným oknem
useEffect(() => {
if (!open) return;
const watch = () => socket.emit('tetris:watch');
watch();
socket.on('connect', watch);
return () => {
socket.off('connect', watch);
socket.emit('tetris:unwatch');
};
}, [open]);
useEffect(() => {
const onGarbage = (e: GarbageEvent) => {
if (e.target !== login || !sessionRef.current?.alive) return;
sessionRef.current.receiveGarbage(e.lines);
setFlash(`⚠️ +${e.lines} od ${e.from}`);
window.setTimeout(() => setFlash(null), 1500);
};
socket.on('tetris:garbage', onGarbage);
return () => { socket.off('tetris:garbage', onGarbage); };
}, [login]);
const isPlayer = !!login && !!state?.players.some(p => p.login === login);
const phase = state?.phase ?? 'idle';
const inGame = phase === 'countdown' || phase === 'playing';
const controllable = open && (practice || (phase === 'playing' && isPlayer));
// Hráčům se okno otevře samo, jakmile hra začne
useEffect(() => {
if (prevPhase.current === 'lobby' && phase === 'countdown' && isPlayer) {
setPractice(false);
setOpen(true);
}
prevPhase.current = phase;
}, [phase, isPlayer]);
// Start vlastní hry se seedem od serveru
useEffect(() => {
if (practice || phase !== 'playing' || !isPlayer || state?.seed === undefined || sessionSeed.current === state.seed) return;
sessionSeed.current = state.seed;
sessionRef.current = new TetrisSession(state.seed, {
onLock: (cleared, attack) => {
if (attack > 0) send('tetris:cleared', { count: cleared, sent: attack });
sendSnapshot();
setVersion(v => v + 1);
},
onDeath: () => {
sendSnapshot();
send('tetris:died');
setVersion(v => v + 1);
},
});
setVersion(v => v + 1);
}, [practice, phase, isPlayer, state?.seed, send, sendSnapshot]);
// Herní smyčka: gravitace, vykreslení a průběžné posílání desky (trénink se při zavřeném okně pozastaví)
useEffect(() => {
if (practice ? !open : phase !== 'playing') return;
if (!sessionRef.current) return;
let raf = 0;
let lastFall = performance.now();
let lastSnapshot = 0;
const loop = (now: number) => {
const s = sessionRef.current;
if (!s) return;
if (s.alive && now - lastFall >= s.gravityMs) {
s.tick();
lastFall = now;
}
if (!practice && s.alive && now - lastSnapshot >= SNAPSHOT_MS) {
sendSnapshot();
lastSnapshot = now;
}
if (boardRef.current) drawBoard(boardRef.current, s.board, CELL, s.active, s.ghost);
if (nextRef.current) drawNext(nextRef.current, s.nextType);
raf = requestAnimationFrame(loop);
};
raf = requestAnimationFrame(loop);
return () => cancelAnimationFrame(raf);
}, [practice, phase, open, sendSnapshot, state?.seed]);
// Odpočet zbývajícího času hry na skóre
useEffect(() => {
if (phase !== 'playing' || state?.settings.winMode !== 'score') return;
const id = window.setInterval(() => setNow(Date.now()), 500);
return () => window.clearInterval(id);
}, [phase, state?.settings.winMode]);
// Heartbeat pro server (viz HEARTBEAT_MS)
useEffect(() => {
if (practice || phase !== 'playing' || !isPlayer) return;
const id = window.setInterval(() => {
if (sessionRef.current?.alive) sendSnapshot();
}, HEARTBEAT_MS);
return () => window.clearInterval(id);
}, [practice, phase, isPlayer, sendSnapshot]);
/** Herní akce z klávesnice i dotykového ovládání. */
const control = useCallback((action: Action) => {
const s = sessionRef.current;
if (!controllable || !s?.alive) return;
switch (action) {
case 'left': s.move(-1); break;
case 'right': s.move(1); break;
case 'down': s.softDrop(); break;
case 'rotate': s.rotate(1); break;
case 'rotateBack': s.rotate(-1); break;
case 'drop': s.hardDrop(); break;
}
}, [controllable]);
// Deska mohla zmizet s prstem na ní (konec hry, zavření okna) — rozpracované gesto se zahodí
useEffect(() => {
if (!controllable) gesture.current = null;
}, [controllable]);
// Ovládání klávesnicí
useEffect(() => {
if (!controllable) return;
const onKey = (e: KeyboardEvent) => {
const action = KEYS[e.code];
if (!action || !sessionRef.current) return;
e.preventDefault();
if (e.repeat && !REPEATABLE.has(action)) return;
control(action);
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [controllable, control]);
// Po skončení hry se session zahodí, ať se příště začíná načisto
useEffect(() => {
if (!practice && (phase === 'lobby' || phase === 'idle')) {
sessionRef.current = null;
sessionSeed.current = undefined;
}
}, [practice, phase]);
const startPractice = useCallback(() => {
sessionSeed.current = undefined;
sessionRef.current = new TetrisSession(Math.floor(Math.random() * 2 ** 31), {
onLock: () => setVersion(v => v + 1),
onDeath: () => setVersion(v => v + 1),
});
setPractice(true);
setVersion(v => v + 1);
}, []);
const stopPractice = useCallback(() => {
sessionRef.current = null;
setPractice(false);
}, []);
// Dotyková gesta na desce (myš se ignoruje, aby kliknutí do desky na počítači neotáčelo kostkou)
const onBoardPointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
const s = sessionRef.current;
if (e.pointerType === 'mouse' || !controllable || !s?.alive) return;
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
gesture.current = {
pointerId: e.pointerId, pieceNo: s.pieceNo,
startX: e.clientX, startY: e.clientY, startTime: e.timeStamp,
anchorX: e.clientX, anchorY: e.clientY, moved: false,
trail: [{ y: e.clientY, t: e.timeStamp }],
};
};
const onBoardPointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
const g = gesture.current;
const s = sessionRef.current;
if (!g || g.pointerId !== e.pointerId || !s || s.pieceNo !== g.pieceNo) return;
if (Math.abs(e.clientX - g.startX) > TAP_SLOP_PX || Math.abs(e.clientY - g.startY) > TAP_SLOP_PX) g.moved = true;
const step = Math.max(MIN_STEP_PX, e.currentTarget.getBoundingClientRect().width / WIDTH);
for (; e.clientX - g.anchorX >= step; g.anchorX += step) control('right');
for (; g.anchorX - e.clientX >= step; g.anchorX -= step) control('left');
// Tažení dolů kostku nezamkne (to udělá gravitace nebo švihnutí), aby tah nepokračoval na další kostce
for (; e.clientY - g.anchorY >= step; g.anchorY += step) {
if (!s.grounded) control('down');
}
g.anchorY = Math.min(g.anchorY, e.clientY);
g.trail.push({ y: e.clientY, t: e.timeStamp });
while (e.timeStamp - g.trail[0].t > FLICK_WINDOW_MS) g.trail.shift();
};
const onBoardPointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {
const g = gesture.current;
if (!g || g.pointerId !== e.pointerId) return;
gesture.current = null;
if (sessionRef.current?.pieceNo !== g.pieceNo) return;
if (!g.moved) {
if (e.timeStamp - g.startTime <= TAP_MAX_MS) control('rotate');
return;
}
const from = g.trail.find(p => e.timeStamp - p.t <= FLICK_WINDOW_MS);
if (!from || e.timeStamp <= from.t) return;
const dy = e.clientY - from.y;
if (dy >= FLICK_MIN_PX && dy / (e.timeStamp - from.t) >= FLICK_SPEED) control('drop');
};
const onBoardPointerCancel = () => {
gesture.current = null;
};
if (!login) return null;
const session = sessionRef.current;
// Připojit se jde i během odpočtu před startem
const joinable = phase === 'lobby' || phase === 'countdown';
const showInvite = !open && joinable && !isPlayer;
const showReturn = !open && isPlayer && inGame;
const others = practice ? [] : (state?.players ?? []).filter(p => !(isPlayer && p.login === login));
const ranked = [...(state?.players ?? [])].sort((a, b) => (a.place ?? 99) - (b.place ?? 99));
const settings = state?.settings;
const isHost = login === state?.host;
const remaining = !practice && phase === 'playing' && deadline.current !== undefined
? Math.max(0, deadline.current - now) : undefined;
const configure = (change: Partial<TetrisSettings>) => send('tetris:configure', change);
const renderSettings = () => settings && (
<div className="tetris-settings">
<Form.Group>
<Form.Label>Míření odpadu</Form.Label>
{isHost ? (
<Form.Select size="sm" value={settings.targeting}
onChange={e => configure({ targeting: e.target.value as TetrisTargeting })}>
{Object.entries(TARGETING_LABELS).map(([value, { label }]) => <option key={value} value={value}>{label}</option>)}
</Form.Select>
) : <div><strong>{TARGETING_LABELS[settings.targeting].label}</strong></div>}
<Form.Text>{TARGETING_LABELS[settings.targeting].help}</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Vítěz</Form.Label>
{isHost ? (
<Form.Select size="sm" value={settings.winMode}
onChange={e => configure({ winMode: e.target.value as TetrisWinMode })}>
{Object.entries(WIN_MODE_LABELS).map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</Form.Select>
) : <div><strong>{WIN_MODE_LABELS[settings.winMode]}</strong></div>}
</Form.Group>
{settings.winMode === 'score' && (
<Form.Group>
<Form.Label>Délka hry</Form.Label>
{isHost ? (
<Form.Select size="sm" value={settings.timeLimit}
onChange={e => configure({ timeLimit: Number(e.target.value) })}>
{TIME_LIMITS.map(t => <option key={t} value={t}>{t / 60} min</option>)}
</Form.Select>
) : <div><strong>{settings.timeLimit / 60} min</strong></div>}
</Form.Group>
)}
</div>
);
const renderPlaying = () => (
<div className="tetris-layout">
{(isPlayer || practice) && (
<div className="tetris-own-col">
<div className="tetris-own">
<div className="tetris-board-wrap">
<canvas ref={boardRef} className="tetris-board" width={WIDTH * CELL} height={HEIGHT * CELL}
onPointerDown={onBoardPointerDown} onPointerMove={onBoardPointerMove}
onPointerUp={onBoardPointerUp} onPointerCancel={onBoardPointerCancel} />
{!practice && phase === 'countdown' && <div className="tetris-overlay">{state?.countdown}</div>}
{session && !session.alive && <div className="tetris-overlay small">Konec 💀</div>}
{flash && <div className="tetris-flash">{flash}</div>}
</div>
<div className="tetris-side">
{remaining !== undefined && (
<>
<div className="tetris-label">Zbývá</div>
<div className="tetris-value">{formatTime(remaining)}</div>
</>
)}
<div className="tetris-label">Další</div>
<canvas ref={nextRef} width={100} height={60} />
<div className="tetris-label">Skóre</div>
<div className="tetris-value">{session?.score ?? 0}</div>
<div className="tetris-label">Řádky</div>
<div className="tetris-value">{session?.lines ?? 0}</div>
<div className="tetris-label">Úroveň</div>
<div className="tetris-value">{session?.level ?? 0}</div>
<div className="tetris-help">
{touch
? <>ťuknutí otočí<br />tažení posouvá<br />švihnutí dolů shodí</>
: <>←→ / AD posun<br />↑ / W otočit<br />↓ / S dolů<br />mezerník shodit</>}
</div>
</div>
</div>
{touch && (
<div className="tetris-touch-pad">
<div className="tetris-touch-group">
<TouchButton label="Doleva" repeat onPress={() => control('left')}><FontAwesomeIcon icon={faCaretLeft} /></TouchButton>
<TouchButton label="Dolů" repeat onPress={() => control('down')}><FontAwesomeIcon icon={faCaretDown} /></TouchButton>
<TouchButton label="Doprava" repeat onPress={() => control('right')}><FontAwesomeIcon icon={faCaretRight} /></TouchButton>
</div>
<div className="tetris-touch-group">
<TouchButton label="Otočit po směru hodinových ručiček" onPress={() => control('rotateBack')}><FontAwesomeIcon icon={faRotateRight} /></TouchButton>
<TouchButton label="Otočit proti směru hodinových ručiček" onPress={() => control('rotate')}><FontAwesomeIcon icon={faRotateLeft} /></TouchButton>
<TouchButton label="Shodit" onPress={() => control('drop')}><FontAwesomeIcon icon={faAnglesDown} /></TouchButton>
</div>
</div>
)}
</div>
)}
{others.length > 0 && (
<div className="tetris-opponents">
{others.map(p => <MiniBoard key={p.login} player={p} />)}
</div>
)}
</div>
);
const renderBody = () => {
if (practice) {
return (
<>
<p className="text-muted text-center">🎯 Trénink — hra jen pro vás, nikdo ji nevidí.</p>
{renderPlaying()}
</>
);
}
switch (phase) {
case 'idle':
return (
<p>
Tetris pro více hráčů. Všichni dostávají stejné kostky; kdo smaže 2, 3 nebo 4 řádky naráz,
pošle soupeři 1, 2 nebo 4 odpadní řádky. Smazáním řádků lze zároveň odrazit odpad,
který na vás čeká. Zakladatel lobby volí, komu útoky půjdou a zda vyhrává poslední
hráč ve hře, nebo nejvyšší skóre po časovém limitu.
Hrát se dá i sólo, nebo si kdykoli zatrénovat jen pro sebe.
</p>
);
case 'lobby':
return (
<>
<p>Lobby založil(a) <strong>{state?.host}</strong>. Hráči ({state?.players.length}):</p>
<ul className="tetris-players">
{state?.players.map(p => <li key={p.login}>{p.login}{p.login === state.host && ' 👑'}</li>)}
</ul>
{state && state.players.length < state.minPlayers &&
<p className="text-muted">Čeká se na další hráče… Pro hru o samotě použijte Trénink.</p>}
{renderSettings()}
{isPlayer && <LobbyChat game="tetris" />}
</>
);
case 'countdown':
return (
<>
{!isPlayer && (
<p className="text-center">
Hra začne za <strong>{state?.countdown} s</strong> — ještě se můžete připojit.
</p>
)}
{renderPlaying()}
</>
);
case 'playing':
return renderPlaying();
case 'finished':
return (
<>
{settings && (
<p className="text-muted">
Hodnocení: {WIN_MODE_LABELS[settings.winMode]}
{settings.winMode === 'score' && ` (${settings.timeLimit / 60} min)`}
{' · '}míření: {TARGETING_LABELS[settings.targeting].label}
</p>
)}
<Table size="sm" className="tetris-results">
<thead>
<tr><th>#</th><th>Hráč</th><th>Skóre</th><th>Řádky</th></tr>
</thead>
<tbody>
{ranked.map((p, i) => (
<tr key={p.login}>
<td>{i < 3 ? MEDALS[i] : i + 1}</td>
<td>{p.login}{p.login === login && ' (vy)'}</td>
<td>{p.score}</td>
<td>{p.lines}</td>
</tr>
))}
</tbody>
</Table>
</>
);
}
};
const renderFooter = () => {
const buttons = [];
if (practice) {
if (session && !session.alive) {
buttons.push(<Button key="again" onClick={startPractice}>Znovu</Button>);
}
buttons.push(<Button key="stop" variant="outline-secondary" onClick={stopPractice}>Ukončit trénink</Button>);
buttons.push(<Button key="close" variant="secondary" onClick={() => setOpen(false)}>Zavřít</Button>);
return buttons;
}
// Trénink jde spustit, kdykoli zrovna nehrajete online hru
if (!(isPlayer && (phase === 'lobby' || inGame))) {
buttons.push(<Button key="practice" variant="outline-primary" onClick={startPractice}>Trénink</Button>);
}
if (phase === 'idle' || phase === 'finished') {
buttons.push(<Button key="new" onClick={() => send('tetris:join')}>{phase === 'idle' ? 'Založit lobby' : 'Nová hra'}</Button>);
}
if (joinable && !isPlayer) {
buttons.push(<Button key="join" onClick={() => send('tetris:join')}>Připojit se</Button>);
}
if (phase === 'lobby' && isPlayer) {
buttons.push(<Button key="leave" variant="outline-secondary" onClick={() => send('tetris:leave')}>
{login === state?.host ? 'Zrušit lobby' : 'Odejít'}
</Button>);
if (login === state?.host) {
buttons.push(<Button key="start" onClick={() => send('tetris:start')}
disabled={(state?.players.length ?? 0) < (state?.minPlayers ?? 2)}>Spustit hru</Button>);
}
}
buttons.push(<Button key="close" variant="secondary" onClick={() => setOpen(false)}>Zavřít</Button>);
return buttons;
};
return (
<>
{showInvite && (
<button className="duel-invite tetris-invite" onClick={() => setOpen(true)}>
{icon} {phase === 'countdown'
? <>Tetris začíná za <strong>{state?.countdown} s</strong> — připojit se</>
: <><strong>{state?.host}</strong> zve na Tetris — připojit se</>}
</button>
)}
{showReturn && (
<button className="duel-invite tetris-invite" onClick={() => setOpen(true)}>
{icon} Tetris běží — zpět do hry
</button>
)}
<Modal show={open} onHide={() => setOpen(false)} size="xl" fullscreen="sm-down" className="tetris-game-modal">
<Modal.Header closeButton>
<Modal.Title><h2>{icon} Tetris</h2></Modal.Title>
</Modal.Header>
<Modal.Body>
{renderBody()}
{error && <div className="text-danger mt-2">{error}</div>}
</Modal.Body>
<Modal.Footer>{renderFooter()}</Modal.Footer>
</Modal>
</>
);
}
-37
View File
@@ -1,37 +0,0 @@
// Velikost dotykových tlačítek — podle ní se řídí i rozložení ovládání v jednotlivých hrách
:root {
--touch-btn-size: 52px;
}
// Tablet (na rozdíl od telefonu na šířku je vysoký i široký) — na velkém displeji jsou malá tlačítka špatně trefitelná
@media (any-pointer: coarse) and (min-width: 700px) and (min-height: 600px) {
:root {
--touch-btn-size: 76px;
}
}
// Dotyková tlačítka miniher — bez zoomu dvojitým ťuknutím, výběru textu a kontextové nabídky při podržení
.touch-btn {
display: flex;
align-items: center;
justify-content: center;
min-width: var(--touch-btn-size);
height: var(--touch-btn-size);
padding: 0 10px;
border: 1px solid var(--luncher-border, rgba(127, 127, 127, 0.4));
border-radius: calc(var(--touch-btn-size) * 0.23);
background: var(--bs-tertiary-bg);
color: var(--luncher-text, inherit);
font-size: calc(var(--touch-btn-size) * 0.45);
line-height: 1;
touch-action: none;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
-webkit-tap-highlight-color: transparent;
&:active {
background: var(--luncher-primary, #198754);
color: #fff;
}
}
-52
View File
@@ -1,52 +0,0 @@
import { ReactNode, useEffect, useRef } from "react";
import "./TouchButton.scss";
/** Prodleva před opakováním a interval opakování při podržení tlačítka (ms), podobně jako u klávesnice. */
const REPEAT_DELAY_MS = 170;
const REPEAT_MS = 50;
type Props = {
label: string,
onPress: () => void,
/** Při podržení se akce opakuje (posun, pád). */
repeat?: boolean,
className?: string,
children: ReactNode,
};
/**
* Tlačítko dotykového ovládání miniher. Reaguje hned na dotyk (ne až na click) a je mimo pořadí
* fokusu, aby mezerník nebo šipky z klávesnice nespouštěly tlačítko místo hry.
*/
export default function TouchButton({ label, onPress, repeat, className, children }: Props) {
const timer = useRef<number | undefined>(undefined);
const onPressRef = useRef(onPress);
onPressRef.current = onPress;
const stop = () => {
window.clearTimeout(timer.current);
timer.current = undefined;
};
useEffect(() => stop, []);
const onPointerDown = (e: React.PointerEvent<HTMLButtonElement>) => {
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
stop();
onPressRef.current();
if (!repeat) return;
const tick = () => {
onPressRef.current();
timer.current = window.setTimeout(tick, REPEAT_MS);
};
timer.current = window.setTimeout(tick, REPEAT_DELAY_MS);
};
return (
<button type="button" tabIndex={-1} aria-label={label} className={`touch-btn ${className ?? ''}`}
onPointerDown={onPointerDown} onPointerUp={stop} onPointerCancel={stop} onLostPointerCapture={stop}
onContextMenu={e => e.preventDefault()}>
{children}
</button>
);
}
-948
View File
@@ -1,948 +0,0 @@
/**
* Vykreslování tanků do canvasu: mapa podle prostředí (biomu), tanky, střely, miny, bonusy,
* hořící vraky, výbuchy a záblesky výstřelů. Stav chodí ze serveru (server/src/tankGame.ts).
*/
// Typy musí odpovídat server/src/tankGame.ts (stav chodí přes websocket, ne přes OpenAPI)
export type TankPhase = 'idle' | 'lobby' | 'countdown' | 'playing' | 'finished';
export type TankMode = 'deathmatch' | 'lastman';
export type BotLevel = 'easy' | 'medium' | 'hard';
export type PickupType = 'shield' | 'triple' | 'rocket' | 'turbo' | 'ghost' | 'homing' | 'mine' | 'heart';
export type Biome = 'city' | 'forest' | 'desert' | 'winter' | 'swamp';
export type Team = 0 | 1;
export type TankPlayer = {
login: string,
color: number,
team?: Team,
x: number,
y: number,
angle: number,
turret: number,
alive: boolean,
kills: number,
deaths: number,
score: number,
lives?: number,
shield: boolean,
triple: boolean,
turbo: boolean,
ghost: boolean,
homing: boolean,
rockets: number,
mines: number,
protected: boolean,
shots: number,
respawnIn?: number,
bot?: BotLevel,
place?: number,
};
export type TankState = {
phase: TankPhase,
host?: string,
mode: TankMode,
teams: boolean,
hardcore: boolean,
bounce: boolean,
mapId: string,
biome: Biome,
maps: { id: string, name: string, biome: Biome }[],
tiles: string[],
players: TankPlayer[],
bullets: { x: number, y: number, color: number, team?: Team, angle: number, rocket: boolean }[],
pickups: { x: number, y: number, type: PickupType }[],
mines: { x: number, y: number, owner: string, team?: Team, color: number, armed: boolean }[],
wrecks: { x: number, y: number, angle: number, turret: number, color: number, team?: Team, age: number }[],
explosions: { x: number, y: number, r: number, age: number }[],
teamScores?: [number, number],
winnerTeam?: number,
countdown?: number,
timeLeftMs: number,
width: number,
height: number,
tile: number,
minPlayers: number,
maxPlayers: number,
};
/** Záblesk výstřelu — klient ho zakládá podle změny počítadla výstřelů. */
export type MuzzleFlash = { login: string, start: number };
// Konstanty musí odpovídat serveru
const TANK_RADIUS = 14;
const BULLET_RADIUS = 4;
const EXPLOSION_MS = 600;
const WRECK_MS = 8000;
const REVEAL_DISTANCE = 70;
const LIGHT_RADIUS = 130;
const SPOTLIGHT_RANGE = 300;
const SPOTLIGHT_HALF_ANGLE = 0.45;
export const FLASH_MS = 110;
export const COLORS = ['#4ade80', '#60a5fa', '#f472b6', '#facc15', '#a78bfa', '#fb923c'];
/** Týmy mají vlastní paletu (teplé × studené barvy). */
export const TEAM_COLORS: [string[], string[]] = [['#f87171', '#fb923c', '#fbbf24'], ['#60a5fa', '#22d3ee', '#a78bfa']];
export const TEAM_NAMES = ['Červení', 'Modří'];
export const PICKUPS: Record<PickupType, { icon: string, label: string }> = {
shield: { icon: '🛡️', label: 'štít — vydrží jeden zásah' },
triple: { icon: '🔱', label: 'trojitá střela — tři střely do vějíře' },
rocket: { icon: '🚀', label: 'rakety — výbuch zasáhne i okolí' },
turbo: { icon: '💨', label: 'turbo — rychlejší jízda' },
ghost: { icon: '👻', label: 'neviditelnost — soupeř vás uvidí jen zblízka' },
homing: { icon: '🧲', label: 'naváděné střely — stáčí se k soupeři' },
mine: { icon: '💣', label: 'miny — položíte E / pravým tlačítkem' },
heart: { icon: '❤️', label: 'život navíc (jen na přežití)' },
};
export const BIOMES: Record<Biome, { icon: string }> = {
city: { icon: '🏙️' },
forest: { icon: '🌲' },
desert: { icon: '🏜️' },
winter: { icon: '❄️' },
swamp: { icon: '🐸' },
};
export const tankColor = (o: { color: number, team?: Team }) =>
o.team !== undefined ? TEAM_COLORS[o.team][o.color % TEAM_COLORS[o.team].length] : COLORS[o.color % COLORS.length];
/** Deterministická „náhoda" podle polohy dlaždice — dekorace se nemění mezi snímky. */
const hash = (col: number, row: number, k: number) => {
const v = Math.sin(col * 12.9898 + row * 78.233 + k * 37.719) * 43758.5453;
return v - Math.floor(v);
};
type BiomeStyle = {
ground: [string, string],
speck: string,
water: string,
mud: string,
};
const STYLES: Record<Biome, BiomeStyle> = {
city: { ground: ['#1f2937', '#243041'], speck: 'rgba(255,255,255,0.03)', water: '#1e3a5f', mud: '#4b4036' },
forest: { ground: ['#2d4a26', '#31502a'], speck: 'rgba(0,0,0,0.12)', water: '#2563eb', mud: '#5b4630' },
desert: { ground: ['#d8b46c', '#d2ad64'], speck: 'rgba(120,80,30,0.18)', water: '#0e7490', mud: '#b8934f' },
winter: { ground: ['#e2e8f0', '#dbe2ec'], speck: 'rgba(100,116,139,0.15)', water: '#1e3a8a', mud: '#f8fafc' },
swamp: { ground: ['#38432a', '#3c482d'], speck: 'rgba(0,0,0,0.15)', water: '#1f3d36', mud: '#4a3b26' },
};
// --- Statická vrstva mapy — překresluje se jen při změně dlaždic ---
let layerCache: { key: string, ground: HTMLCanvasElement } | undefined;
function mapLayer(state: TankState) {
const key = `${state.biome}|${state.tiles.join('')}`;
if (layerCache?.key === key) return layerCache.ground;
const ground = document.createElement('canvas');
ground.width = state.width;
ground.height = state.height;
drawGround(ground.getContext('2d')!, state);
layerCache = { key, ground };
return ground;
}
function drawGround(ctx: CanvasRenderingContext2D, state: TankState) {
const t = state.tile;
const style = STYLES[state.biome];
state.tiles.forEach((row, r) => [...row].forEach((_, col) => {
const x = col * t;
const y = r * t;
ctx.fillStyle = style.ground[(col + r) % 2];
ctx.fillRect(x, y, t, t);
ctx.fillStyle = style.speck;
for (let k = 0; k < 4; k++) {
ctx.fillRect(x + hash(col, r, k) * (t - 4), y + hash(col, r, k + 9) * (t - 4), 3, 3);
}
}));
// Nejdřív plochy (voda, bláto, porost), pak překážky přes ně — stromy a skály přesahují políčko
state.tiles.forEach((row, r) => [...row].forEach((c, col) => {
if (c === '~') drawWater(ctx, state.biome, col, r, t);
else if (c === ':') drawMud(ctx, state.biome, col, r, t);
else if (c === '%') drawGrowth(ctx, state.biome, col, r, t);
}));
state.tiles.forEach((row, r) => [...row].forEach((c, col) => {
if (c === '#') drawWall(ctx, state.biome, col, r, t);
else if (c === '+') drawCrate(ctx, state.biome, col, r, t);
}));
}
function drawWater(ctx: CanvasRenderingContext2D, biome: Biome, col: number, row: number, t: number) {
const x = col * t;
const y = row * t;
ctx.fillStyle = STYLES[biome].water;
ctx.fillRect(x, y, t, t);
if (biome === 'winter') {
// Díra v ledu: světlý okraj
ctx.strokeStyle = 'rgba(255,255,255,0.7)';
ctx.lineWidth = 3;
ctx.strokeRect(x + 1.5, y + 1.5, t - 3, t - 3);
}
// Vlnky
ctx.strokeStyle = 'rgba(255,255,255,0.18)';
ctx.lineWidth = 1.5;
for (let k = 0; k < 2; k++) {
const wx = x + 6 + hash(col, row, k) * (t - 18);
const wy = y + 8 + hash(col, row, k + 4) * (t - 16);
ctx.beginPath();
ctx.moveTo(wx, wy);
ctx.quadraticCurveTo(wx + 3, wy - 3, wx + 6, wy);
ctx.quadraticCurveTo(wx + 9, wy + 3, wx + 12, wy);
ctx.stroke();
}
if (biome === 'swamp' && hash(col, row, 7) > 0.5) {
// Lekníny
ctx.fillStyle = '#4d7c0f';
ctx.beginPath();
ctx.arc(x + 10 + hash(col, row, 8) * 20, y + 10 + hash(col, row, 9) * 20, 5, 0.4, Math.PI * 2);
ctx.lineTo(x + 10 + hash(col, row, 8) * 20, y + 10 + hash(col, row, 9) * 20);
ctx.fill();
}
}
function drawMud(ctx: CanvasRenderingContext2D, biome: Biome, col: number, row: number, t: number) {
const x = col * t;
const y = row * t;
ctx.fillStyle = STYLES[biome].mud;
ctx.fillRect(x, y, t, t);
if (biome === 'winter') {
// Závěje: stínované oblouky
ctx.strokeStyle = 'rgba(148,163,184,0.5)';
ctx.lineWidth = 2;
for (let k = 0; k < 2; k++) {
ctx.beginPath();
ctx.arc(x + 8 + hash(col, row, k) * 24, y + 14 + k * 14, 8, Math.PI * 1.1, Math.PI * 1.9);
ctx.stroke();
}
return;
}
if (biome === 'desert') {
// Pohyblivý písek: víry
ctx.strokeStyle = 'rgba(120,80,30,0.35)';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(x + t / 2, y + t / 2, 10, 0, Math.PI * 1.5);
ctx.stroke();
ctx.beginPath();
ctx.arc(x + t / 2, y + t / 2, 4, Math.PI, Math.PI * 2.5);
ctx.stroke();
return;
}
// Bláto: tmavší louže
ctx.fillStyle = 'rgba(0,0,0,0.2)';
for (let k = 0; k < 3; k++) {
ctx.beginPath();
ctx.ellipse(x + 6 + hash(col, row, k) * 28, y + 6 + hash(col, row, k + 3) * 28, 6, 4, 0, 0, Math.PI * 2);
ctx.fill();
}
}
function drawWall(ctx: CanvasRenderingContext2D, biome: Biome, col: number, row: number, t: number) {
const x = col * t;
const y = row * t;
const cx = x + t / 2;
const cy = y + t / 2;
switch (biome) {
case 'city':
ctx.fillStyle = '#4b5563';
ctx.fillRect(x, y, t, t);
ctx.fillStyle = '#6b7280';
ctx.fillRect(x, y, t, 4);
ctx.strokeStyle = 'rgba(0,0,0,0.25)';
ctx.lineWidth = 1;
ctx.strokeRect(x + 0.5, y + 0.5, t - 1, t - 1);
return;
case 'forest': {
// Strom: stín, koruna ve vrstvách a odlesk
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.beginPath();
ctx.arc(cx + 3, cy + 4, t * 0.5, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#14532d';
ctx.beginPath();
ctx.arc(cx, cy, t * 0.52, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#166534';
for (let k = 0; k < 4; k++) {
const a = hash(col, row, k) * Math.PI * 2;
ctx.beginPath();
ctx.arc(cx + Math.cos(a) * 8, cy + Math.sin(a) * 8, t * 0.26, 0, Math.PI * 2);
ctx.fill();
}
ctx.fillStyle = 'rgba(134,239,172,0.25)';
ctx.beginPath();
ctx.arc(cx - 6, cy - 6, t * 0.18, 0, Math.PI * 2);
ctx.fill();
return;
}
case 'swamp': {
// Pahýl: kořeny, letokruhy a mech
ctx.fillStyle = '#2b2118';
for (let k = 0; k < 5; k++) {
const a = k / 5 * Math.PI * 2 + hash(col, row, k);
ctx.beginPath();
ctx.ellipse(cx + Math.cos(a) * 13, cy + Math.sin(a) * 13, 7, 4, a, 0, Math.PI * 2);
ctx.fill();
}
ctx.fillStyle = '#5b4632';
ctx.beginPath();
ctx.arc(cx, cy, 14, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#3b2d20';
ctx.lineWidth = 1.5;
for (const r of [10, 6, 2.5]) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.stroke();
}
ctx.fillStyle = 'rgba(101,163,13,0.6)';
ctx.beginPath();
ctx.arc(cx - 8, cy + 7, 5, 0, Math.PI * 2);
ctx.fill();
return;
}
default: {
// Skála (poušť pískovec, zima žula se sněhem)
const winter = biome === 'winter';
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.beginPath();
ctx.roundRect(x + 3, y + 5, t - 2, t - 3, 10);
ctx.fill();
ctx.fillStyle = winter ? '#64748b' : '#a87b45';
ctx.beginPath();
ctx.roundRect(x + 1, y + 1, t - 2, t - 2, 10);
ctx.fill();
ctx.fillStyle = winter ? '#475569' : '#7c5a32';
ctx.beginPath();
ctx.roundRect(x + 1, y + t * 0.55, t - 2, t * 0.45 - 1, [0, 0, 10, 10]);
ctx.fill();
if (winter) {
ctx.fillStyle = '#f8fafc';
ctx.beginPath();
ctx.roundRect(x + 2, y + 1, t - 4, t * 0.35, [10, 10, 6, 6]);
ctx.fill();
} else {
ctx.strokeStyle = 'rgba(255,240,200,0.35)';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(x + 8, y + 12);
ctx.lineTo(x + t - 10, y + 10);
ctx.moveTo(x + 6, y + 20);
ctx.lineTo(x + t - 14, y + 19);
ctx.stroke();
}
}
}
}
function drawCrate(ctx: CanvasRenderingContext2D, biome: Biome, col: number, row: number, t: number) {
const x = col * t;
const y = row * t;
if (biome === 'forest' || biome === 'swamp') {
// Hromada klád
for (const [lx, ly] of [[13, 25], [27, 25], [20, 13]]) {
ctx.fillStyle = '#78350f';
ctx.beginPath();
ctx.arc(x + lx, y + ly, 8, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#d6a76b';
ctx.beginPath();
ctx.arc(x + lx, y + ly, 5.5, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#92400e';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(x + lx, y + ly, 2.5, 0, Math.PI * 2);
ctx.stroke();
}
return;
}
ctx.fillStyle = '#a16207';
ctx.fillRect(x + 2, y + 2, t - 4, t - 4);
ctx.strokeStyle = '#713f12';
ctx.lineWidth = 3;
ctx.strokeRect(x + 4, y + 4, t - 8, t - 8);
ctx.beginPath();
ctx.moveTo(x + 4, y + 4);
ctx.lineTo(x + t - 4, y + t - 4);
ctx.moveTo(x + t - 4, y + 4);
ctx.lineTo(x + 4, y + t - 4);
ctx.stroke();
if (biome === 'winter') {
ctx.fillStyle = '#f8fafc';
ctx.beginPath();
ctx.roundRect(x + 2, y + 1, t - 4, 7, 3);
ctx.fill();
}
}
/**
* Porost (zpomaluje): nízká vegetace v úrovni země, přes kterou se jede — kapradí, suchá tráva,
* keříky ve sněhu nebo rákos. Kreslí se pod tanky a je řídký, aby nepřipomínal stromy.
*/
function drawGrowth(ctx: CanvasRenderingContext2D, biome: Biome, col: number, row: number, t: number) {
const x = col * t;
const y = row * t;
const style = GROWTH[biome];
// Lehce odlišený podklad, ať je vidět, kde porost začíná
ctx.fillStyle = style.patch;
ctx.beginPath();
ctx.roundRect(x + 1, y + 1, t - 2, t - 2, 10);
ctx.fill();
for (let k = 0; k < 6; k++) {
const bx = x + 6 + hash(col, row, k) * (t - 12);
const by = y + 10 + hash(col, row, k + 11) * (t - 14);
// Trs stébel / lístků vějířovitě nahoru
ctx.strokeStyle = k % 2 ? style.blade : style.blade2;
ctx.lineWidth = biome === 'winter' ? 1.5 : 1.8;
ctx.lineCap = 'round';
const blades = biome === 'swamp' ? 3 : 5;
for (let b = 0; b < blades; b++) {
const a = -Math.PI / 2 + (b / (blades - 1) - 0.5) * (biome === 'swamp' ? 0.5 : 1.6);
const len = (biome === 'swamp' ? 13 : 8) + hash(col, row, k * 7 + b) * 4;
ctx.beginPath();
ctx.moveTo(bx, by);
ctx.quadraticCurveTo(bx + Math.cos(a) * len * 0.5, by + Math.sin(a) * len * 0.6,
bx + Math.cos(a) * len, by + Math.sin(a) * len);
ctx.stroke();
}
if (biome === 'swamp' && k % 2 === 0) {
// Palice orobince
ctx.fillStyle = '#6b3f1d';
ctx.beginPath();
ctx.ellipse(bx, by - 13, 2, 4, 0, 0, Math.PI * 2);
ctx.fill();
}
if (biome === 'winter') {
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc(bx + 2, by - 7, 1.8, 0, Math.PI * 2);
ctx.fill();
}
}
ctx.lineCap = 'butt';
}
const GROWTH: Record<Biome, { patch: string, blade: string, blade2: string }> = {
city: { patch: 'rgba(74,222,128,0.08)', blade: '#4d7c0f', blade2: '#65a30d' },
forest: { patch: 'rgba(132,204,22,0.12)', blade: '#84cc16', blade2: '#65a30d' },
desert: { patch: 'rgba(161,98,7,0.12)', blade: '#a3842a', blade2: '#8a6d1f' },
winter: { patch: 'rgba(120,113,108,0.1)', blade: '#78716c', blade2: '#57534e' },
swamp: { patch: 'rgba(163,230,53,0.1)', blade: '#7c9a2a', blade2: '#a3b33a' },
};
// --- Snímek ---
/**
* Vykreslí celý snímek. `me` je přihlášený hráč — sebe a spoluhráče s neviditelností vidí
* průsvitně, neviditelné soupeře jen zblízka. V hardcore vidí soupeře, střely a bonusy jen ve světle
* svém a spoluhráčů; výbuchy a záblesky výstřelů prosvítí i tmou. Divák a vyřazený hráč vidí všechno.
*/
export function drawTanks(canvas: HTMLCanvasElement, state: TankState, flashes: MuzzleFlash[], me?: string) {
const ctx = canvas.getContext('2d');
if (!ctx) return;
const scale = canvas.width / state.width;
const now = performance.now();
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.drawImage(mapLayer(state), 0, 0);
const self = state.players.find(p => p.login === me);
const friendly = (o: { login?: string, owner?: string, team?: Team }) =>
!self || (o.login ?? o.owner) === me || (state.teams && o.team === self.team);
const near = (o: { x: number, y: number }) => !!self?.alive && Math.hypot(o.x - self.x, o.y - self.y) < REVEAL_DISTANCE;
const perceivable = (p: TankPlayer) => p.alive && (friendly(p) || !p.ghost || near(p));
// Tma: hráč, který ještě hraje (i čekající na návrat), vidí jen světlo svoje a spoluhráčů
const dark = state.hardcore && !!self && (self.alive || self.respawnIn !== undefined);
const lights = dark
? state.players.filter(p => p.alive && friendly(p)).map(p => castLight(state, p))
: [];
const lit = (o: { x: number, y: number }, margin = 0) => !dark || inLight(lights, o.x, o.y, margin);
for (const w of state.wrecks) if (lit(w, 20)) drawWreck(ctx, w, now);
for (const m of state.mines) if (friendly(m) || lit(m)) drawMine(ctx, m, friendly(m), now);
for (const pk of state.pickups) if (lit(pk, 14)) drawPickup(ctx, pk, now);
const tanks = state.players.filter(p => perceivable(p) && (friendly(p) || lit(p, TANK_RADIUS)));
for (const p of tanks) {
ctx.globalAlpha = p.ghost ? 0.45 : 1;
drawTank(ctx, p, p.login === me, now);
ctx.globalAlpha = 1;
}
for (const b of state.bullets) if (lit(b, BULLET_RADIUS)) drawBullet(ctx, b, now);
if (dark) drawDarkness(ctx, state, lights);
for (const f of flashes) {
const p = state.players.find(x => x.login === f.login);
if (p && perceivable(p)) drawFlash(ctx, p, (now - f.start) / FLASH_MS);
}
for (const e of state.explosions) drawExplosion(ctx, e);
for (const p of tanks) drawLabel(ctx, p, p.login === me);
// Při startu a po návratu do hry ukazuje na vlastní tank šipka s pulzujícím kruhem
if (self?.alive && (state.phase === 'countdown' || self.protected)) drawSelfMarker(ctx, self, now);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
function drawSelfMarker(ctx: CanvasRenderingContext2D, p: TankPlayer, now: number) {
const pulse = (now % 900) / 900;
ctx.strokeStyle = `rgba(250, 204, 21, ${0.9 * (1 - pulse)})`;
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(p.x, p.y, TANK_RADIUS + 10 + pulse * 40, 0, Math.PI * 2);
ctx.stroke();
// Šipka nad jmenovkou; u horního okraje hřiště pod tankem
const below = p.y < 70;
const dir = below ? -1 : 1;
const bob = Math.sin(now / 150) * 3;
const tipY = below ? p.y + TANK_RADIUS + 10 + bob : p.y - TANK_RADIUS - 20 + bob;
ctx.beginPath();
ctx.moveTo(p.x, tipY);
ctx.lineTo(p.x - 9, tipY - dir * 14);
ctx.lineTo(p.x - 4, tipY - dir * 14);
ctx.lineTo(p.x - 4, tipY - dir * 24);
ctx.lineTo(p.x + 4, tipY - dir * 24);
ctx.lineTo(p.x + 4, tipY - dir * 14);
ctx.lineTo(p.x + 9, tipY - dir * 14);
ctx.closePath();
ctx.lineWidth = 3;
ctx.strokeStyle = '#0b0f19';
ctx.stroke();
ctx.fillStyle = '#facc15';
ctx.fill();
ctx.font = 'bold 13px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const textY = tipY - dir * 33;
ctx.lineWidth = 3;
ctx.strokeText('VY', p.x, textY);
ctx.fillText('VY', p.x, textY);
}
// --- Hardcore: světlo a tma ---
/** Paprsek světla ze středu tanku do každého směru; délka končí na zdi či bedně. */
type Light = { x: number, y: number, lengths: Float32Array };
const LIGHT_RAYS = 240;
const LIGHT_STEP = 4;
/** Šířka přechodu mezi kruhem a kuželem reflektoru (rad), ať okraj kužele není ostrý zub. */
const SPOTLIGHT_EDGE = 0.12;
const wrapAngle = (a: number) => {
const d = a % (Math.PI * 2);
return d < 0 ? d + Math.PI * 2 : d;
};
function castLight(state: TankState, src: TankPlayer): Light {
const t = state.tile;
const blocks = (x: number, y: number) => {
if (x < 0 || y < 0 || x >= state.width || y >= state.height) return true;
const c = state.tiles[Math.floor(y / t)]?.[Math.floor(x / t)];
return c === '#' || c === '+';
};
const lengths = new Float32Array(LIGHT_RAYS);
for (let i = 0; i < LIGHT_RAYS; i++) {
const a = i / LIGHT_RAYS * Math.PI * 2;
const off = Math.abs(wrapAngle(a - src.turret + Math.PI) - Math.PI);
const reach = off <= SPOTLIGHT_HALF_ANGLE
? SPOTLIGHT_RANGE
: off <= SPOTLIGHT_HALF_ANGLE + SPOTLIGHT_EDGE
? LIGHT_RADIUS + (SPOTLIGHT_RANGE - LIGHT_RADIUS) * (1 - (off - SPOTLIGHT_HALF_ANGLE) / SPOTLIGHT_EDGE)
: LIGHT_RADIUS;
const dx = Math.cos(a);
const dy = Math.sin(a);
let d = 0;
while (d < reach && !blocks(src.x + dx * (d + LIGHT_STEP), src.y + dy * (d + LIGHT_STEP))) d += LIGHT_STEP;
// Světlo dopadne i na stěnu překážky, ne jen před ni
lengths[i] = d < reach ? d + LIGHT_STEP * 2 : reach;
}
return { x: src.x, y: src.y, lengths };
}
/** Zda je bod (s tolerancí poloměru objektu) v některém světle. */
function inLight(lights: Light[], x: number, y: number, margin: number) {
return lights.some(l => {
const d = Math.hypot(x - l.x, y - l.y);
if (d <= margin) return true;
const i = Math.round(wrapAngle(Math.atan2(y - l.y, x - l.x)) / (Math.PI * 2) * LIGHT_RAYS) % LIGHT_RAYS;
return d - margin <= l.lengths[i];
});
}
let darknessCanvas: HTMLCanvasElement | undefined;
/** Tma přes celou plochu s vyříznutým světlem (rozmazané okraje, slábnoucí do dálky). */
function drawDarkness(ctx: CanvasRenderingContext2D, state: TankState, lights: Light[]) {
if (!darknessCanvas) darknessCanvas = document.createElement('canvas');
const dc = darknessCanvas;
if (dc.width !== state.width || dc.height !== state.height) {
dc.width = state.width;
dc.height = state.height;
}
const d = dc.getContext('2d');
if (!d) return;
d.globalCompositeOperation = 'source-over';
d.clearRect(0, 0, dc.width, dc.height);
// Mapa zůstane matně vidět, aby se dalo orientovat
d.fillStyle = 'rgba(2, 4, 10, 0.84)';
d.fillRect(0, 0, dc.width, dc.height);
d.globalCompositeOperation = 'destination-out';
d.filter = 'blur(8px)';
for (const l of lights) {
const fade = d.createRadialGradient(l.x, l.y, 0, l.x, l.y, SPOTLIGHT_RANGE);
fade.addColorStop(0, 'rgba(0,0,0,1)');
fade.addColorStop(LIGHT_RADIUS / SPOTLIGHT_RANGE * 0.8, 'rgba(0,0,0,1)');
fade.addColorStop(1, 'rgba(0,0,0,0.55)');
d.fillStyle = fade;
d.beginPath();
for (let i = 0; i < LIGHT_RAYS; i++) {
const a = i / LIGHT_RAYS * Math.PI * 2;
d.lineTo(l.x + Math.cos(a) * l.lengths[i], l.y + Math.sin(a) * l.lengths[i]);
}
d.closePath();
d.fill();
}
d.filter = 'none';
d.globalCompositeOperation = 'source-over';
ctx.drawImage(dc, 0, 0);
}
function drawTank(ctx: CanvasRenderingContext2D, p: TankPlayer, mine: boolean, now: number) {
const color = tankColor(p);
const base = ctx.globalAlpha;
// Vlastní tank má pod sebou výrazný otáčející se kruh, ať se v hemžení najde (tmavý lem kvůli světlým mapám)
if (mine) {
ctx.fillStyle = 'rgba(250, 204, 21, 0.18)';
ctx.beginPath();
ctx.arc(p.x, p.y, TANK_RADIUS + 7, 0, Math.PI * 2);
ctx.fill();
ctx.setLineDash([7, 5]);
ctx.lineDashOffset = -now / 40;
ctx.strokeStyle = 'rgba(11, 15, 25, 0.7)';
ctx.lineWidth = 4.5;
ctx.stroke();
ctx.strokeStyle = '#facc15';
ctx.lineWidth = 2.5;
ctx.stroke();
ctx.setLineDash([]);
ctx.lineDashOffset = 0;
}
// Ochrana po zrození — tank bliká
if (p.protected && Math.floor(now / 120) % 2 === 0) ctx.globalAlpha = base * 0.35;
// Turbo: proužky za tankem
if (p.turbo) {
ctx.strokeStyle = 'rgba(255,255,255,0.5)';
ctx.lineWidth = 2;
for (const s of [-8, 0, 8]) {
const len = 10 + Math.sin(now / 60 + s) * 4;
const bx = p.x - Math.cos(p.angle) * 18 + -Math.sin(p.angle) * s;
const by = p.y - Math.sin(p.angle) * 18 + Math.cos(p.angle) * s;
ctx.beginPath();
ctx.moveTo(bx, by);
ctx.lineTo(bx - Math.cos(p.angle) * len, by - Math.sin(p.angle) * len);
ctx.stroke();
}
}
drawHull(ctx, p.x, p.y, p.angle, color, (p.x + p.y) * 0.7);
drawTurret(ctx, p.x, p.y, p.turret, color, p.triple ? 3 : 1, p.homing);
if (p.shield) {
ctx.strokeStyle = '#38bdf8';
ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.arc(p.x, p.y, TANK_RADIUS + 6, 0, Math.PI * 2);
ctx.stroke();
ctx.fillStyle = 'rgba(56,189,248,0.12)';
ctx.fill();
}
ctx.globalAlpha = base;
}
function drawHull(ctx: CanvasRenderingContext2D, x: number, y: number, angle: number, color: string, travel: number) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
// Stín
ctx.fillStyle = 'rgba(0, 0, 0, 0.35)';
ctx.beginPath();
ctx.roundRect(-14, -13, 32, 30, 6);
ctx.fill();
// Pásy s články, které se posouvají s jízdou
const tread = travel % 5;
for (const ty of [-15, 8]) {
ctx.fillStyle = '#111827';
ctx.beginPath();
ctx.roundRect(-16, ty, 32, 7, 3);
ctx.fill();
ctx.strokeStyle = '#4b5563';
ctx.lineWidth = 1.5;
ctx.beginPath();
for (let tx = -15 + tread; tx < 15; tx += 5) {
ctx.moveTo(tx, ty + 1);
ctx.lineTo(tx, ty + 6);
}
ctx.stroke();
}
// Korba se stínováním a čelním pancířem
ctx.fillStyle = color;
ctx.beginPath();
ctx.roundRect(-13, -9, 26, 18, 4);
ctx.fill();
const light = ctx.createLinearGradient(0, -9, 0, 9);
light.addColorStop(0, 'rgba(255, 255, 255, 0.3)');
light.addColorStop(0.5, 'rgba(255, 255, 255, 0)');
light.addColorStop(1, 'rgba(0, 0, 0, 0.3)');
ctx.fillStyle = light;
ctx.fill();
ctx.strokeStyle = 'rgba(0, 0, 0, 0.55)';
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
ctx.fillRect(8, -8, 3, 16);
ctx.restore();
}
function drawTurret(ctx: CanvasRenderingContext2D, x: number, y: number, angle: number, color: string, barrels: number, homing: boolean) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
for (const a of barrels === 3 ? [-0.22, 0, 0.22] : [0]) {
ctx.save();
ctx.rotate(a);
ctx.fillStyle = '#d1d5db';
ctx.strokeStyle = '#1f2937';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.rect(2, -2.5, 17, 5);
ctx.fill();
ctx.stroke();
ctx.fillStyle = homing ? '#e879f9' : '#6b7280';
ctx.beginPath();
ctx.rect(18, -3.5, 4, 7);
ctx.fill();
ctx.stroke();
ctx.restore();
}
ctx.fillStyle = color;
ctx.beginPath();
ctx.roundRect(-8, -7, 14, 14, 5);
ctx.fill();
const glow = ctx.createRadialGradient(-3, -3, 1, -1, 0, 10);
glow.addColorStop(0, 'rgba(255, 255, 255, 0.45)');
glow.addColorStop(1, 'rgba(0, 0, 0, 0.2)');
ctx.fillStyle = glow;
ctx.fill();
ctx.strokeStyle = 'rgba(0, 0, 0, 0.6)';
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.fillStyle = 'rgba(0, 0, 0, 0.35)';
ctx.beginPath();
ctx.arc(-3, 0, 2.5, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
/** Bonus: záře, tmavý podklad se zlatým pulzujícím kruhem a větší ikona, která lehce poskakuje. */
function drawPickup(ctx: CanvasRenderingContext2D, pk: TankState['pickups'][number], now: number) {
const pulse = (Math.sin(now / 180 + pk.x) + 1) / 2;
const bob = Math.sin(now / 260 + pk.y) * 2;
const glow = ctx.createRadialGradient(pk.x, pk.y, 6, pk.x, pk.y, 28 + pulse * 6);
glow.addColorStop(0, 'rgba(253, 224, 71, 0.55)');
glow.addColorStop(1, 'rgba(253, 224, 71, 0)');
ctx.fillStyle = glow;
ctx.beginPath();
ctx.arc(pk.x, pk.y, 34, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'rgba(15, 23, 42, 0.75)';
ctx.beginPath();
ctx.arc(pk.x, pk.y + bob, 16, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = `rgba(250, 204, 21, ${0.7 + pulse * 0.3})`;
ctx.lineWidth = 2.5;
ctx.stroke();
// Otáčející se čárkovaný prstenec, ať bonus upoutá pozornost
ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)';
ctx.lineWidth = 1.5;
ctx.setLineDash([4, 6]);
ctx.lineDashOffset = -now / 40;
ctx.beginPath();
ctx.arc(pk.x, pk.y + bob, 20 + pulse * 2, 0, Math.PI * 2);
ctx.stroke();
ctx.setLineDash([]);
ctx.lineDashOffset = 0;
ctx.font = '20px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(PICKUPS[pk.type].icon, pk.x, pk.y + bob + 1);
}
function drawLabel(ctx: CanvasRenderingContext2D, p: TankPlayer, mine: boolean) {
const y = p.y - TANK_RADIUS - 10;
ctx.font = `${mine ? 'bold ' : ''}11px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineWidth = 3;
ctx.strokeStyle = '#0b0f19';
ctx.strokeText(p.login, p.x, y);
ctx.fillStyle = mine ? '#fff' : tankColor(p);
ctx.fillText(p.login, p.x, y);
}
function drawBullet(ctx: CanvasRenderingContext2D, b: TankState['bullets'][number], now: number) {
const color = tankColor(b);
if (!b.rocket) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(b.x, b.y, BULLET_RADIUS, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc(b.x, b.y, BULLET_RADIUS / 2, 0, Math.PI * 2);
ctx.fill();
return;
}
ctx.save();
ctx.translate(b.x, b.y);
ctx.rotate(b.angle);
// Plamen z trysky
const flame = 8 + Math.sin(now / 30) * 3;
ctx.fillStyle = '#f97316';
ctx.beginPath();
ctx.moveTo(-6, -3);
ctx.lineTo(-6 - flame, 0);
ctx.lineTo(-6, 3);
ctx.fill();
ctx.fillStyle = '#fde047';
ctx.beginPath();
ctx.moveTo(-6, -1.5);
ctx.lineTo(-6 - flame * 0.5, 0);
ctx.lineTo(-6, 1.5);
ctx.fill();
ctx.fillStyle = '#e5e7eb';
ctx.fillRect(-6, -3, 10, 6);
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(4, -3);
ctx.lineTo(9, 0);
ctx.lineTo(4, 3);
ctx.fill();
ctx.fillRect(-7, -4.5, 3, 9);
ctx.restore();
}
function drawMine(ctx: CanvasRenderingContext2D, m: TankState['mines'][number], friendly: boolean, now: number) {
// Cizí miny jsou jen málo vidět
ctx.globalAlpha = friendly ? 1 : 0.3;
ctx.fillStyle = '#1f2937';
ctx.strokeStyle = tankColor(m);
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(m.x, m.y, 7, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.fillStyle = m.armed && Math.floor(now / 300) % 2 === 0 ? '#ef4444' : '#6b7280';
ctx.beginPath();
ctx.arc(m.x, m.y, 2.5, 0, Math.PI * 2);
ctx.fill();
ctx.globalAlpha = 1;
}
/** Vrak: ohořelá korba s věží, plameny slábnou a stoupá kouř. */
function drawWreck(ctx: CanvasRenderingContext2D, w: TankState['wrecks'][number], now: number) {
const fire = Math.max(0, 1 - w.age / WRECK_MS);
ctx.save();
ctx.translate(w.x, w.y);
ctx.rotate(w.angle);
ctx.fillStyle = 'rgba(0,0,0,0.35)';
ctx.beginPath();
ctx.ellipse(1, 2, 20, 17, 0, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#1c1917';
ctx.fillRect(-16, -15, 32, 7);
ctx.fillRect(-16, 8, 32, 7);
ctx.fillStyle = '#292524';
ctx.beginPath();
ctx.roundRect(-13, -9, 26, 18, 4);
ctx.fill();
ctx.globalAlpha = 0.3;
ctx.fillStyle = tankColor(w);
ctx.fill();
ctx.globalAlpha = 1;
ctx.rotate(w.turret - w.angle + 0.5);
ctx.fillStyle = '#44403c';
ctx.fillRect(2, -2.5, 15, 5);
ctx.fillStyle = '#292524';
ctx.beginPath();
ctx.arc(0, 0, 7, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
// Kouř stoupá a mizí, s ohněm postupně řídne
for (let i = 0; i < 6; i++) {
const phase = (now / 1400 + i / 6) % 1;
ctx.fillStyle = `rgba(68,64,60,${(1 - phase) * (0.15 + 0.35 * fire)})`;
ctx.beginPath();
ctx.arc(w.x + Math.sin(phase * 5 + i) * 7 + phase * 6, w.y - phase * 34, 4 + phase * 9, 0, Math.PI * 2);
ctx.fill();
}
if (fire <= 0) return;
for (let i = 0; i < 5; i++) {
const fx = w.x + Math.sin(i * 2.1) * 8 + Math.sin(now / 70 + i) * 2;
const fy = w.y + Math.cos(i * 1.7) * 6 - Math.abs(Math.sin(now / 90 + i * 1.3)) * 4;
const r = (4 + Math.abs(Math.sin(now / 110 + i)) * 4) * (0.4 + 0.6 * fire);
ctx.fillStyle = 'rgba(249,115,22,0.85)';
ctx.beginPath();
ctx.arc(fx, fy, r, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'rgba(253,224,71,0.9)';
ctx.beginPath();
ctx.arc(fx, fy + 1, r * 0.5, 0, Math.PI * 2);
ctx.fill();
}
}
function drawExplosion(ctx: CanvasRenderingContext2D, e: TankState['explosions'][number]) {
const k = e.age / EXPLOSION_MS;
if (k < 0 || k > 1) return;
ctx.globalAlpha = 1 - k;
ctx.fillStyle = '#f97316';
ctx.beginPath();
ctx.arc(e.x, e.y, e.r * (0.3 + 0.7 * k), 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#fde047';
ctx.beginPath();
ctx.arc(e.x, e.y, e.r * (0.15 + 0.4 * k), 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#fff7ed';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(e.x, e.y, e.r * (0.4 + 0.8 * k), 0, Math.PI * 2);
ctx.stroke();
ctx.globalAlpha = 1;
}
/** Záblesk u ústí hlavně: hvězdice, která rychle zhasne. */
function drawFlash(ctx: CanvasRenderingContext2D, p: TankPlayer, k: number) {
if (k < 0 || k > 1) return;
const tip = 24;
const size = 10 * (1 - k * 0.5);
ctx.save();
ctx.translate(p.x + Math.cos(p.turret) * tip, p.y + Math.sin(p.turret) * tip);
ctx.rotate(p.turret);
ctx.globalAlpha = 1 - k;
ctx.fillStyle = '#fde047';
ctx.beginPath();
for (let i = 0; i < 10; i++) {
const a = i / 10 * Math.PI * 2;
const r = i % 2 ? size * 0.4 : size * (i === 0 ? 1.6 : 1);
ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r);
}
ctx.closePath();
ctx.fill();
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.arc(0, 0, size * 0.35, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
ctx.globalAlpha = 1;
}
-270
View File
@@ -1,270 +0,0 @@
/**
* Herní logika Tetrisu bez Reactu — deska, kostky, rotace s odrazem od stěn,
* mazání řádků a odpadní řádky od soupeřů.
*/
export const WIDTH = 10;
export const HEIGHT = 20;
/** Hodnota buňky odpadního řádku (1–7 jsou kostky). */
export const GARBAGE = 8;
type Point = [number, number];
/**
* Kostky I, O, T, S, Z, J, L ve výchozí rotaci, velikost jejich čtverce pro rotaci
* a počet různých poloh (O jedna; I, S, Z jen dvě, aby se při otáčení neposouvaly).
*/
const SHAPES: { cells: Point[], box: number, states: 1 | 2 | 4 }[] = [
{ cells: [[0, 1], [1, 1], [2, 1], [3, 1]], box: 4, states: 2 },
{ cells: [[0, 0], [1, 0], [0, 1], [1, 1]], box: 2, states: 1 },
{ cells: [[1, 0], [0, 1], [1, 1], [2, 1]], box: 3, states: 4 },
{ cells: [[1, 0], [2, 0], [0, 1], [1, 1]], box: 3, states: 2 },
{ cells: [[0, 0], [1, 0], [1, 1], [2, 1]], box: 3, states: 2 },
{ cells: [[0, 0], [0, 1], [1, 1], [2, 1]], box: 3, states: 4 },
{ cells: [[2, 0], [0, 1], [1, 1], [2, 1]], box: 3, states: 4 },
];
/**
* Předpočítané rotace pro každou kostku; rot + 1 = otočení proti směru hodinových ručiček.
* T, J, L se otáčí kolem prostředního políčka. I, S, Z jen přepínají mezi vodorovnou
* a svislou polohou (svislá = vodorovná otočená po směru, stejná osa jako v klasickém Tetrisu).
*/
const ROTATIONS: Point[][][] = SHAPES.map(({ cells, box, states }) => {
const ccw = (pts: Point[]) => pts.map(([x, y]) => [y, box - 1 - x] as Point);
const cw = (pts: Point[]) => pts.map(([x, y]) => [box - 1 - y, x] as Point);
if (states === 1) return [cells, cells, cells, cells];
if (states === 2) return [cells, cw(cells), cells, cw(cells)];
const result = [cells];
for (let r = 1; r < 4; r++) result.push(ccw(result[r - 1]));
return result;
});
/** Posuny zkoušené při rotaci, když kostka narazí (zjednodušený wall kick). */
const KICKS: Point[] = [[0, 0], [-1, 0], [1, 0], [0, -1], [-2, 0], [2, 0]];
/** Body za smazání 0–4 řádků naráz (násobí se úrovní). */
const LINE_SCORES = [0, 100, 300, 500, 800];
/** Odpadní řádky za smazání 0–4 řádků naráz (musí odpovídat GARBAGE_FOR_LINES na serveru). */
const ATTACK_FOR_LINES = [0, 0, 1, 2, 4];
export type Piece = { type: number, rot: number, x: number, y: number };
/** Deterministický generátor (mulberry32) — stejný seed = stejné pořadí kostek u všech. */
function mulberry32(seed: number) {
let a = seed >>> 0;
return () => {
a = (a + 0x6D2B79F5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export const pieceCells = (p: Piece): Point[] => ROTATIONS[p.type][p.rot].map(([x, y]) => [p.x + x, p.y + y]);
export type SessionCallbacks = {
/**
* Kostka dopadla; `cleared` = počet smazaných řádků,
* `attack` = odpadní řádky pro soupeře po odražení vlastního čekajícího odpadu.
*/
onLock: (cleared: number, attack: number) => void,
onDeath: () => void,
};
/** Jedna rozehraná hra jednoho hráče. */
export class TetrisSession {
board: number[] = new Array(WIDTH * HEIGHT).fill(0);
active: Piece | null = null;
nextType = 0;
score = 0;
lines = 0;
alive = true;
/** Pořadové číslo padající kostky — dotykové gesto podle něj pozná, že jeho kostka mezitím dopadla. */
pieceNo = 0;
private random: () => number;
private bag: number[] = [];
private pendingGarbage = 0;
constructor(seed: number, private readonly callbacks: SessionCallbacks) {
this.random = mulberry32(seed);
this.nextType = this.draw();
this.spawn();
}
get level() {
return Math.floor(this.lines / 10);
}
/** Interval gravitace v ms — s úrovní zrychluje. */
get gravityMs() {
return Math.max(80, 800 - this.level * 60);
}
/** Pozice "stínu" — kam by kostka dopadla. */
get ghost(): Piece | null {
if (!this.active) return null;
let p = this.active;
while (this.fits({ ...p, y: p.y + 1 })) p = { ...p, y: p.y + 1 };
return p;
}
tick() {
if (!this.alive || !this.active) return;
if (!this.tryMove(0, 1)) this.lock();
}
move(dx: number) {
if (this.alive) this.tryMove(dx, 0);
}
/** Zda kostka leží na dně či na jiných kostkách (další krok dolů by ji zamkl). */
get grounded() {
return !!this.active && !this.fits({ ...this.active, y: this.active.y + 1 });
}
softDrop() {
if (!this.alive) return;
if (this.tryMove(0, 1)) this.score += 1;
else this.lock();
}
hardDrop() {
if (!this.alive || !this.active) return;
let dropped = 0;
while (this.tryMove(0, 1)) dropped++;
this.score += dropped * 2;
this.lock();
}
rotate(dir: 1 | -1) {
if (!this.alive || !this.active) return;
const rot = (this.active.rot + dir + 4) % 4;
for (const [kx, ky] of KICKS) {
const candidate = { ...this.active, rot, x: this.active.x + kx, y: this.active.y + ky };
if (this.fits(candidate)) {
this.active = candidate;
return;
}
}
}
/** Odpadní řádky čekají a přidají se po dopadu kostky, která nic nesmaže (jako v klasickém battle módu). */
receiveGarbage(lines: number) {
this.pendingGarbage += lines;
}
/** Deska včetně padající kostky (pro soupeře), znaky 0–8. */
snapshot(): string {
const cells = [...this.board];
if (this.active) {
for (const [x, y] of pieceCells(this.active)) {
if (y >= 0) cells[y * WIDTH + x] = this.active.type + 1;
}
}
return cells.join('');
}
private draw(): number {
if (this.bag.length === 0) {
this.bag = [0, 1, 2, 3, 4, 5, 6];
for (let i = this.bag.length - 1; i > 0; i--) {
const j = Math.floor(this.random() * (i + 1));
[this.bag[i], this.bag[j]] = [this.bag[j], this.bag[i]];
}
}
return this.bag.pop()!;
}
private spawn() {
const type = this.nextType;
this.nextType = this.draw();
// Kostka se objeví celá nad deskou, aby ji šlo otočit dřív, než vjede do hrací plochy
const bottom = Math.max(...ROTATIONS[type][0].map(([, y]) => y));
const piece: Piece = { type, rot: 0, x: type === 1 ? 4 : 3, y: -bottom - 1 };
if (!this.fits(piece)) {
this.active = null;
this.die();
return;
}
this.active = piece;
this.pieceNo++;
}
private fits(p: Piece) {
return pieceCells(p).every(([x, y]) =>
x >= 0 && x < WIDTH && y < HEIGHT && (y < 0 || this.board[y * WIDTH + x] === 0));
}
private tryMove(dx: number, dy: number) {
if (!this.active) return false;
const candidate = { ...this.active, x: this.active.x + dx, y: this.active.y + dy };
if (!this.fits(candidate)) return false;
this.active = candidate;
return true;
}
private lock() {
if (!this.active) return;
const cells = pieceCells(this.active);
// Kostka zamčená nad horním okrajem = konec hry
if (cells.some(([, y]) => y < 0)) {
this.die();
return;
}
for (const [x, y] of cells) this.board[y * WIDTH + x] = this.active.type + 1;
this.active = null;
const cleared = this.clearLines();
let attack = 0;
if (cleared > 0) {
this.score += LINE_SCORES[cleared] * (this.level + 1);
this.lines += cleared;
// Útok nejdřív odráží čekající odpad, soupeři jde jen zbytek
attack = ATTACK_FOR_LINES[cleared] ?? 0;
const cancelled = Math.min(attack, this.pendingGarbage);
this.pendingGarbage -= cancelled;
attack -= cancelled;
}
this.callbacks.onLock(cleared, attack);
// Dokud hráč maže řádky, zbylý odpad ještě čeká
if (cleared === 0 && this.pendingGarbage > 0) {
const overflow = this.addGarbage(this.pendingGarbage);
this.pendingGarbage = 0;
if (overflow) {
this.die();
return;
}
}
this.spawn();
}
private clearLines(): number {
const rows: number[][] = [];
for (let y = 0; y < HEIGHT; y++) rows.push(this.board.slice(y * WIDTH, (y + 1) * WIDTH));
const kept = rows.filter(row => row.some(c => c === 0));
const cleared = HEIGHT - kept.length;
if (cleared > 0) {
const empty = Array.from({ length: cleared }, () => new Array(WIDTH).fill(0));
this.board = [...empty, ...kept].flat();
}
return cleared;
}
/** Přidá odpadní řádky zespodu s jednou dírou; vrátí true, pokud deska přetekla. */
private addGarbage(lines: number): boolean {
const overflow = this.board.slice(0, lines * WIDTH).some(c => c !== 0);
const hole = Math.floor(Math.random() * WIDTH);
const garbageRows = Array.from({ length: lines }, () =>
Array.from({ length: WIDTH }, (_, x) => x === hole ? 0 : GARBAGE));
this.board = [...this.board.slice(lines * WIDTH), ...garbageRows.flat()].slice(-WIDTH * HEIGHT);
return overflow;
}
private die() {
if (!this.alive) return;
this.alive = false;
this.callbacks.onDeath();
}
}
+13 -13
View File
@@ -1,20 +1,20 @@
import { StyleTheme, useSettings } from "../context/settings";
export type GameId = 'reaction' | 'snake' | 'tetris' | 'pong' | 'drawing' | 'tanks';
export type GameId = 'drawing';
/** Ikony miniher podle vizuálního stylu aplikace. */
/** Ikony miniher podle vizuálního stylu aplikace (ostatní minihry jsou v samostatné aplikaci Lobby). */
const ICONS: Record<StyleTheme, Record<GameId, string>> = {
simple: { reaction: '⚡', snake: '🐍', tetris: '🧱', pong: '🏓', drawing: '🎨', tanks: '💥' },
// Dostihy: startovní vlajka, kůň místo hada, mrkve jako kostky, žokej, trofej, terč
umamusume: { reaction: '🏁', snake: '🐎', tetris: '🥕', pong: '🏇', drawing: '🏆', tanks: '🎯' },
// Duha, jednorožec, drahokamy, balónky, paleta a blesk Rainbow Dash
mlp: { reaction: '🌈', snake: '🦄', tetris: '💎', pong: '🎈', drawing: '🖌️', tanks: '⚡' },
// Pekelná korespondence: plamen, rudá nit, lampion, slaměná panenka, svitek, svíčka
hellgirl: { reaction: '🔥', snake: '🪢', tetris: '🏮', pong: '🪆', drawing: '📜', tanks: '🕯️' },
// Klub lehké hudby: bicí Ritsu, želva Ton-chan, dortíky k čaji, kytara Gitah, notový zápis a klávesy Mugi
kon: { reaction: '🥁', snake: '🐢', tetris: '🍰', pong: '🎸', drawing: '🎼', tanks: '🎹' },
// Kessoku Band: mikrofon Kity, kabel od kytary, krabice od manga, bicí Nijiky, sešit s texty Bocchi a její kytara
bocchi: { reaction: '🎤', snake: '🔌', tetris: '📦', pong: '🥁', drawing: '📝', tanks: '🎸' },
simple: { drawing: '🎨' },
// Dostihy: trofej
umamusume: { drawing: '🏆' },
// Paleta Rarity
mlp: { drawing: '🖌️' },
// Pekelná korespondence: svitek
hellgirl: { drawing: '📜' },
// Klub lehké hudby: notový zápis
kon: { drawing: '🎼' },
// Kessoku Band: sešit s texty Bocchi
bocchi: { drawing: '📝' },
};
/** Styl z <html data-luncher-theme> — pro místa mimo React kontext nastavení. */
+47 -56
View File
@@ -1,11 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { openReactionDuel } from "../components/ReactionDuel";
import { openSnakeGame } from "../components/SnakeGame";
import { openTetrisGame } from "../components/TetrisGame";
import { openPongGame } from "../components/PongGame";
import { openDrawingGame } from "../components/DrawingGame";
import { openTankGame } from "../components/TankGame";
import { GameId, gameIcon } from "../games/themeIcons";
import { useAppConfig } from "./useGroupLimits";
type Minigame = {
id: GameId,
@@ -16,36 +12,11 @@ type Minigame = {
open: () => void,
};
/** Skryté minihry dostupné přes logo. Novou hru stačí přidat sem. */
/**
* Skryté minihry, které zůstaly v Luncheru (ostatní jsou v samostatné aplikaci Lobby).
* Novou hru stačí přidat sem.
*/
const MINIGAMES: Minigame[] = [
{
id: 'reaction',
code: 'reakce',
name: 'Reakční hra',
description: 'Kdo klikne nejrychleji? Hraje se s kolegy online, 3 kola.',
open: openReactionDuel,
},
{
id: 'snake',
code: 'snake',
name: 'Had',
description: 'Had pro více hráčů, ovládání šipkami nebo WSAD. Vyhrává poslední přeživší.',
open: openSnakeGame,
},
{
id: 'tetris',
code: 'tetris',
name: 'Tetris',
description: 'Tetris pro více hráčů — smazané řádky posílají soupeřům odpad.',
open: openTetrisGame,
},
{
id: 'pong',
code: 'pong',
name: 'Pong',
description: 'Pong pro dva, ovládání šipkami nebo W/S. Hraje se do 5 bodů.',
open: openPongGame,
},
{
id: 'drawing',
code: 'kresleni',
@@ -53,25 +24,23 @@ const MINIGAMES: Minigame[] = [
description: 'Jeden kreslí jídlo z dnešních menu, ostatní hádají.',
open: openDrawingGame,
},
{
id: 'tanks',
code: 'tanky',
name: 'Tanky',
description: 'Tanková bitva pro více hráčů (i s boty), střely se odráží od zdí. Na čas nebo na poslední přeživší.',
open: openTankGame,
},
];
const HELP_CODE = 'help';
const SECRET_CLICKS = 3;
/** Max. pauza mezi kliknutími na logo, aby se počítala do série (ms). */
const SECRET_CLICK_GAP_MS = 400;
/** Jak dlouho po sérii kliknutí lze napsat kód (ms). */
/** Jak dlouho po sérii kliknutí (případně po návratu z Lobby do této záložky) lze napsat kód (ms). */
const SECRET_ARM_MS = 8000;
function printHelp() {
function printHelp(lobbyUrl?: string) {
console.log('%c🎮 Luncher minihry', 'font-size: 16px; font-weight: bold');
console.log('Klikněte 3× na logo a napište kód hry:');
if (lobbyUrl) {
console.log(`Klikněte 3× na logo — otevře se Lobby s dalšími minihrami (${lobbyUrl}).`);
console.log('Po návratu do Luncheru lze napsat kód hry:');
} else {
console.log('Klikněte 3× na logo a napište kód hry:');
}
console.table(MINIGAMES.map(g => ({ kód: g.code, hra: `${gameIcon(g.id)} ${g.name}`, popis: g.description })));
}
@@ -79,12 +48,14 @@ function printHelp() {
const normalizeCode = (text: string) => text.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
/**
* Skrytý vstup do miniher: 3× rychle kliknout na logo a pak napsat kód hry,
* případně "help" pro výpis her do konzole prohlížeče.
* Skrytý vstup do miniher: 3× rychle kliknout na logo. Je-li nastavena adresa Lobby, otevře se v nové záložce.
* Poté lze (po návratu do Luncheru) napsat kód hry, která zůstala v Luncheru, případně "help" pro výpis do konzole prohlížeče.
* Jedno či dvě kliknutí se chovají jako běžný odkaz (jen s malým zpožděním).
* Na dotykových zařízeních se kód píše do skrytého pole (`inputRef`), které otevře softwarovou klávesnici.
* Bez Lobby se na dotykových zařízeních kód píše do skrytého pole (`inputRef`), které otevře softwarovou klávesnici.
* Po otevření Lobby klávesnici po návratu do záložky otevřít nelze (chce gesto uživatele), na mobilu tak kód zadat nepůjde.
*/
export function useMinigameSecret(href: string) {
const { lobbyUrl } = useAppConfig();
const [armed, setArmed] = useState(false);
const clicks = useRef(0);
const timer = useRef<number | undefined>(undefined);
@@ -98,11 +69,16 @@ export function useMinigameSecret(href: string) {
clicks.current++;
if (clicks.current >= SECRET_CLICKS) {
clicks.current = 0;
// Fokus musí proběhnout přímo v obsluze kliknutí, jinak iOS klávesnici neotevře
const input = inputRef.current;
if (input) {
input.value = '';
input.focus({ preventScroll: true });
if (lobbyUrl) {
// Otevření musí proběhnout přímo v obsluze kliknutí, jinak ho prohlížeč zablokuje jako vyskakovací okno
window.open(lobbyUrl, '_blank', 'noopener');
} else {
// Fokus musí proběhnout přímo v obsluze kliknutí, jinak iOS klávesnici neotevře
const input = inputRef.current;
if (input) {
input.value = '';
input.focus({ preventScroll: true });
}
}
setArmed(true);
return;
@@ -111,7 +87,7 @@ export function useMinigameSecret(href: string) {
clicks.current = 0;
window.location.assign(href);
}, SECRET_CLICK_GAP_MS);
}, [href]);
}, [href, lobbyUrl]);
useEffect(() => {
if (!armed) return;
@@ -121,7 +97,7 @@ export function useMinigameSecret(href: string) {
const check = (text: string) => {
if (text.endsWith(HELP_CODE)) {
setArmed(false);
printHelp();
printHelp(lobbyUrl);
return;
}
const game = MINIGAMES.find(g => text.endsWith(g.code));
@@ -138,19 +114,34 @@ export function useMinigameSecret(href: string) {
};
// Softwarová klávesnice (Android) posílá v keydown jen "Unidentified", proto se čte celý text pole
const onInput = () => check(normalizeCode(input?.value ?? ''));
const disarm = window.setTimeout(() => setArmed(false), SECRET_ARM_MS);
// Limit běží, jen když je záložka vidět — po odchodu do Lobby se zastaví a po návratu začne znovu
let disarm: number | undefined;
const startDisarm = () => {
window.clearTimeout(disarm);
disarm = window.setTimeout(() => setArmed(false), SECRET_ARM_MS);
};
const onVisibility = () => {
if (document.visibilityState === 'visible') {
startDisarm();
} else {
window.clearTimeout(disarm);
}
};
startDisarm();
window.addEventListener('keydown', onKey);
input?.addEventListener('input', onInput);
document.addEventListener('visibilitychange', onVisibility);
return () => {
window.clearTimeout(disarm);
window.removeEventListener('keydown', onKey);
input?.removeEventListener('input', onInput);
document.removeEventListener('visibilitychange', onVisibility);
if (input) {
input.value = '';
input.blur();
}
};
}, [armed]);
}, [armed, lobbyUrl]);
useEffect(() => () => window.clearTimeout(timer.current), []);
-16
View File
@@ -1,16 +0,0 @@
import { useEffect, useState } from "react";
/** Libovolné dotykové ovládání — iPad se hlásí jako Mac, takže se nedá spoléhat na user agent. */
const QUERY = '(any-pointer: coarse)';
/** Zda má zařízení dotykový displej (podle toho minihry ukazují dotyková tlačítka a nápovědu). */
export function useTouchDevice() {
const [touch, setTouch] = useState(() => window.matchMedia(QUERY).matches);
useEffect(() => {
const media = window.matchMedia(QUERY);
const onChange = () => setTouch(media.matches);
media.addEventListener('change', onChange);
return () => media.removeEventListener('change', onChange);
}, []);
return touch;
}
+1
View File
@@ -24,6 +24,7 @@ getConfig().then(({ data }) => {
loaded: true,
trustedHeaders: data?.auth?.trustedHeaders,
storeAdmin: data?.features?.storeAdmin,
lobbyUrl: data?.links?.lobbyUrl ?? undefined,
groupLimits: data?.limits?.group,
});
if (data?.sentry.dsn) {
+2
View File
@@ -22,6 +22,8 @@ export type AppRuntimeConfig = {
trustedHeaders?: boolean,
/** Správa obchodů je zapnutá (server má admin heslo); undefined = nevíme */
storeAdmin?: boolean,
/** Adresa aplikace Lobby s minihrami; undefined = není nastavena nebo nevíme */
lobbyUrl?: string,
groupLimits: GroupLimits,
};
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Zda se má stisk klávesy ignorovat pro navigaci šipkami mezi dny/týdny na pozadí stránky.
* Navigace se nemá provádět, pokud uživatel píše do formulářového pole, nebo pokud je otevřený
* modální dialog (typicky minihra jako Tetris či Had, která šipky používá k ovládání) –
* modální dialog (např. minihra, která klávesnici používá k ovládání) –
* jinak by se stránka na pozadí neustále přepínala a zbytečně přenačítala data ze serveru.
*/
export function isArrowNavigationBlocked(e: KeyboardEvent): boolean {