refactor: рабочая база на three.js + меню/правила уровней + доки

Полный рефакторинг проекта в стабильную расширяемую базу рогалика.

Почему: после разнесения single-file на модули потерялся вызов генерации
карты (RoomMap не генерировал комнаты) → игра падала на старте; баг скрывался
тем, что Bun-бандлер не проверяет типы.

Архитектура:
- Логика игры (src/core/) полностью отделена от рендера: без three.js и DOM,
  тестируется без браузера.
- Рендер мира на three.js с ортокамерой (2D-вид); HUD/миникарта — 2D-канвас поверх.
- Фиксированный игровой цикл 60 Гц + интерполяция (раньше скорость зависела
  от частоты кадров).
- Seeded-RNG, ввод через абстрактные «намерения» (InputState).

Возможности:
- Стартовое меню с выбором уровня (Esc → меню).
- Конфигуратор уровней: LevelRules + 5 пресетов (размер карты, плотность/сила
  врагов, HP, фиксированный seed).
- Тема внешнего вида (render/theme.ts) — задел под кастомные ассеты.

Качество:
- 27 юнит-тестов ядра (генерация, симметрия дверей, коллизии, спавн, правила).
- Два круга adversarial-ревью; исправлено 6 реальных багов
  (кнокбэк сквозь стены → софт-лок; незакрываемая сокровищница; фикс-сид после
  рестарта; перенос ввода между забегами; нет source maps; неточности в доках).
- Документация: README, docs/ARCHITECTURE.md, CLAUDE.md, docs/HOWTO.md.
- dist/ исключён из гита; bun.lock зафиксирован.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-18 14:07:06 +03:00
co-authored by Claude Opus 4.8
parent 46dc9f2fad
commit 0684368ac7
60 changed files with 2759 additions and 3364 deletions
+133
View File
@@ -0,0 +1,133 @@
import { CW, CH, OY, RH, MODE_RANGED } from '../config';
import type { Game } from '../core/Game';
import type { Renderer } from './Renderer';
/**
* HUD и миникарта на прозрачном 2D-канвасе ПОВЕРХ WebGL-холста.
* Текст и тонкие линии в Canvas2D остаются чёткими и их просто стилизовать —
* куда удобнее, чем тянуть шрифты в WebGL. Чисто отрисовка, без логики.
*/
export class HudOverlay implements Renderer {
private readonly ctx: CanvasRenderingContext2D;
constructor(canvas: HTMLCanvasElement) {
// Буфер увеличиваем под плотность пикселей (чёткий текст на HiDPI),
// а рисуем по-прежнему в логических координатах CW×CH.
const dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = CW * dpr;
canvas.height = CH * dpr;
this.ctx = canvas.getContext('2d')!;
this.ctx.scale(dpr, dpr);
}
render(game: Game): void {
const ctx = this.ctx;
ctx.clearRect(0, 0, CW, CH);
this.drawHud(game);
this.drawMinimap(game);
if (game.gameOver) this.drawOverlay('#c33', 'GAME OVER');
else if (game.won) this.drawOverlay('#3c3', 'VICTORY');
}
dispose(): void {
this.ctx.clearRect(0, 0, CW, CH);
}
private drawHud(game: Game): void {
const ctx = this.ctx;
const p = game.player;
const room = game.curRoom;
// Полоса здоровья.
const bx = 20, by = 20, bw = 140, bh = 14;
ctx.fillStyle = '#111'; ctx.fillRect(bx, by, bw, bh);
ctx.fillStyle = '#2a0a0a'; ctx.fillRect(bx + 2, by + 2, bw - 4, bh - 4);
const hpRatio = Math.max(0, p.hp / p.maxHp);
ctx.fillStyle = hpRatio > 0.5 ? '#993333' : hpRatio > 0.25 ? '#994422' : '#663322';
ctx.fillRect(bx + 2, by + 2, (bw - 4) * hpRatio, bh - 4);
ctx.strokeStyle = '#333'; ctx.lineWidth = 1; ctx.strokeRect(bx, by, bw, bh);
ctx.fillStyle = '#bbb'; ctx.font = '10px monospace'; ctx.textAlign = 'center';
ctx.fillText(`HP ${p.hp}/${p.maxHp}`, bx + bw / 2, by + bh - 3);
// Название текущего уровня (правил).
ctx.textAlign = 'left'; ctx.fillStyle = '#667'; ctx.font = '11px monospace';
ctx.fillText(`Уровень: ${game.rules.name}`, bx, by + bh + 14);
// Индикатор режима боя.
const my = CH - 46;
const ranged = p.mode === MODE_RANGED;
const mText = ranged ? 'RANGED' : 'MELEE';
const mCol = ranged ? '#4488cc' : '#cc6644';
ctx.textAlign = 'center';
ctx.fillStyle = '#0d0d0d'; ctx.fillRect(CW / 2 - 95, my - 18, 190, 34);
ctx.strokeStyle = mCol; ctx.lineWidth = 2; ctx.strokeRect(CW / 2 - 95, my - 18, 190, 34);
ctx.fillStyle = mCol; ctx.font = 'bold 17px monospace'; ctx.fillText(`[ ${mText} ]`, CW / 2, my + 8);
ctx.fillStyle = '#555'; ctx.font = '11px monospace'; ctx.fillText('[Tab] сменить оружие', CW / 2, my - 26);
// Счётчик врагов / подсказка зачистки.
ctx.textAlign = 'left';
const alive = room.enemies.filter((e) => e.alive).length;
if (alive > 0) {
ctx.fillStyle = '#aa4444'; ctx.font = '13px monospace';
ctx.fillText(`${alive}`, 20, CH - 18);
} else if (!room.cleared && room.type !== 'spawn') {
ctx.fillStyle = '#886633'; ctx.font = '13px monospace';
ctx.fillText('Зачисти комнату', 20, CH - 18);
}
// Подпись типа комнаты.
if (room.visited) {
const label = { spawn: 'СТАРТ', normal: '', treasure: 'СОКРОВИЩЕ', boss: 'БОСС' }[room.type];
if (label) {
ctx.textAlign = 'right'; ctx.fillStyle = '#555'; ctx.font = '11px monospace';
ctx.fillText(label, CW - 20, OY + RH + 30);
}
}
}
private drawMinimap(game: Game): void {
const ctx = this.ctx;
const ox = CW - 180, oy = 12, cell = 14, gap = 2, cs = cell + gap;
ctx.fillStyle = 'rgba(0,0,0,0.75)'; ctx.fillRect(ox - 8, oy - 8, cs * 7 + 16, cs * 7 + 16);
ctx.strokeStyle = '#333'; ctx.lineWidth = 1; ctx.strokeRect(ox - 8, oy - 8, cs * 7 + 16, cs * 7 + 16);
for (let r = -3; r <= 3; r++) {
for (let c = -3; c <= 3; c++) {
const room = game.roomMap.get(game.cc + c, game.cr + r);
if (!room) continue;
const x = ox + (c + 3) * cs, y = oy + (r + 3) * cs;
let color = '#141414';
if (room.visited) {
color = { spawn: '#2a5a2a', boss: '#5a1a1a', treasure: '#5a5a1a', normal: '#555' }[room.type];
}
ctx.fillStyle = color; ctx.fillRect(x, y, cell, cell);
if (room.visited) {
ctx.fillStyle = 'rgba(255,255,255,0.5)';
if (room.doors.up) ctx.fillRect(x + cs / 2 - 2, y - 2, 4, 3);
if (room.doors.down) ctx.fillRect(x + cs / 2 - 2, y + cell - 1, 4, 3);
if (room.doors.left) ctx.fillRect(x - 2, y + cs / 2 - 2, 3, 4);
if (room.doors.right) ctx.fillRect(x + cell - 1, y + cs / 2 - 2, 3, 4);
}
if (c === 0 && r === 0) {
ctx.strokeStyle = '#ddd'; ctx.lineWidth = 2; ctx.strokeRect(x - 1.5, y - 1.5, cell + 3, cell + 3);
}
}
}
}
private drawOverlay(color: string, text: string): void {
const ctx = this.ctx;
ctx.fillStyle = 'rgba(0,0,0,0.8)'; ctx.fillRect(0, 0, CW, CH);
ctx.fillStyle = color; ctx.font = 'bold 56px monospace'; ctx.textAlign = 'center';
ctx.fillText(text, CW / 2, CH / 2 - 20);
ctx.fillStyle = '#888'; ctx.font = '18px monospace';
ctx.fillText('[R] заново', CW / 2, CH / 2 + 40);
ctx.fillStyle = '#666'; ctx.font = '14px monospace';
ctx.fillText('[Esc] в меню', CW / 2, CH / 2 + 68);
}
}
+21
View File
@@ -0,0 +1,21 @@
import type { Game } from '../core/Game';
/**
* Контракт любого рендера. Игровая логика про него ничего не знает —
* рендер только ЧИТАЕТ состояние Game и рисует его.
*
* Хочешь другой рендер (чистый Canvas2D, пиксель-арт, настоящий 3D) —
* реализуй этот интерфейс и подмени в main.ts. Ядро менять не нужно.
*/
export interface Renderer {
/**
* Нарисовать кадр.
* @param game текущее состояние игры (только чтение).
* @param alpha доля времени до следующего шага [0..1) для интерполяции
* позиций между prevX/prevY и x/y (плавность на >60 Гц).
*/
render(game: Game, alpha: number): void;
/** Освободить ресурсы GPU/DOM. */
dispose(): void;
}
+230
View File
@@ -0,0 +1,230 @@
import * as THREE from 'three';
import {
CW, CH, OX, OY, TILE, COLS, ROWS,
T_WALL, T_DOOR, MODE_RANGED, PROJECTILE,
} from '../config';
import { lerp } from '../core/util';
import type { Game } from '../core/Game';
import type { Room } from '../core/world/Room';
import type { Enemy } from '../core/entities/Enemy';
import type { Projectile } from '../core/entities/Projectile';
import type { Renderer } from './Renderer';
import { DEFAULT_THEME, type Theme } from './theme';
/** Z-слои: больше значение — ближе к камере (рисуется поверх). */
const Z = { floor: 0, wall: 1, door: 0.5, swing: 4, entity: 5, tear: 6 };
/**
* Все материалы — DoubleSide. Наша ортокамера переворачивает ось Y
* (top=0 сверху), из-за чего инвертируется порядок вершин и при обычном
* отсечении задних граней плоскости становятся невидимыми. DoubleSide
* рисует грань с обеих сторон — для плоского 2D это правильный выбор.
*/
function flatMat(params: THREE.MeshBasicMaterialParameters = {}): THREE.MeshBasicMaterial {
return new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, ...params });
}
/**
* Рендер мира на three.js с ОРТОГРАФИЧЕСКОЙ камерой: 3D-движок, но картинка
* плоская 2D-сверху (как у настоящего Isaac). Мировые координаты совпадают
* с пиксельными координатами логики (x вправо, y вниз), поэтому вся
* математика ядра остаётся валидной без пересчётов.
*
* Управление ресурсами:
* • геометрии-«единицы» (unitPlane/unitCircle) общие и переиспользуются
* масштабированием — не плодим геометрии;
* • тайлы комнаты пересобираются ТОЛЬКО при смене комнаты;
* • меши сущностей создаются/удаляются по мере появления/исчезновения
* (mark-and-sweep), их персональные материалы корректно dispose-ятся.
*/
export class ThreeRenderer implements Renderer {
private readonly renderer: THREE.WebGLRenderer;
private readonly scene = new THREE.Scene();
private readonly camera: THREE.OrthographicCamera;
// Общие геометрии-единицы (масштабируем под размер сущности).
private readonly unitPlane = new THREE.PlaneGeometry(1, 1);
private readonly unitCircle = new THREE.CircleGeometry(0.5, 24);
// Общие материалы тайлов (без пер-тайлового мигания — можно шарить).
private readonly tileMats: Record<string, THREE.MeshBasicMaterial>;
// Группа статичных тайлов текущей комнаты.
private roomGroup = new THREE.Group();
private renderedRoom: Room | null = null;
// Динамические меши с персональными материалами.
private readonly playerMesh: THREE.Mesh;
private readonly enemyMeshes = new Map<Enemy, THREE.Mesh>();
private readonly tearMeshes = new Map<Projectile, THREE.Mesh>();
private readonly swingMesh: THREE.Mesh;
private readonly theme: Theme;
constructor(canvas: HTMLCanvasElement, theme: Theme = DEFAULT_THEME) {
this.theme = theme;
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.renderer.setSize(CW, CH, false);
this.renderer.setClearColor(this.theme.bg, 1);
// Ортокамера: world (0,0) — верхний левый угол, (CW,CH) — нижний правый.
this.camera = new THREE.OrthographicCamera(0, CW, 0, CH, 0.1, 1000);
this.camera.position.z = 100;
this.tileMats = {
floorA: flatMat({ color: this.theme.floorA }),
floorB: flatMat({ color: this.theme.floorB }),
wall: flatMat({ color: this.theme.wall }),
door: flatMat({ color: this.theme.door }),
};
this.scene.add(this.roomGroup);
this.playerMesh = new THREE.Mesh(this.unitPlane, flatMat({ color: this.theme.playerRanged }));
this.playerMesh.position.z = Z.entity;
this.scene.add(this.playerMesh);
this.swingMesh = new THREE.Mesh(
this.unitPlane,
flatMat({ color: this.theme.swing, transparent: true, opacity: 0.45 }),
);
this.swingMesh.position.z = Z.swing;
this.swingMesh.visible = false;
this.scene.add(this.swingMesh);
}
render(game: Game, alpha: number): void {
const room = game.curRoom;
if (room !== this.renderedRoom) this.buildRoom(room);
this.syncPlayer(game, alpha);
this.syncEnemies(room, alpha);
this.syncTears(room, alpha);
this.syncSwing(game);
this.renderer.render(this.scene, this.camera);
}
// ── Статичная геометрия комнаты ───────────────────────────
private buildRoom(room: Room): void {
this.clearGroup(this.roomGroup);
this.renderedRoom = room;
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const t = room.tiles[r][c];
let mat: THREE.MeshBasicMaterial;
let z = Z.floor;
if (t === T_WALL) { mat = this.tileMats.wall; z = Z.wall; }
else if (t === T_DOOR) { mat = this.tileMats.door; z = Z.door; }
else { mat = (r + c) % 2 === 0 ? this.tileMats.floorA : this.tileMats.floorB; }
const mesh = new THREE.Mesh(this.unitPlane, mat);
mesh.scale.set(TILE, TILE, 1);
mesh.position.set(OX + c * TILE + TILE / 2, OY + r * TILE + TILE / 2, z);
this.roomGroup.add(mesh);
}
}
}
// ── Динамические сущности ─────────────────────────────────
private syncPlayer(game: Game, alpha: number): void {
const p = game.player;
const x = lerp(p.prevX, p.x, alpha);
const y = lerp(p.prevY, p.y, alpha);
this.playerMesh.position.set(x, y, Z.entity);
this.playerMesh.scale.set(p.w, p.h, 1);
const base = p.mode === MODE_RANGED ? this.theme.playerRanged : this.theme.playerMelee;
const flashing = p.invTimer > 0 && p.invTimer % 6 < 3;
(this.playerMesh.material as THREE.MeshBasicMaterial).color.setHex(flashing ? this.theme.flash : base);
}
private syncEnemies(room: Room, alpha: number): void {
const live = new Set<Enemy>();
for (const e of room.enemies) {
if (!e.alive) continue;
live.add(e);
let mesh = this.enemyMeshes.get(e);
if (!mesh) {
const geo = e.type === 'normal' ? this.unitPlane : this.unitCircle;
mesh = new THREE.Mesh(geo, flatMat());
mesh.position.z = Z.entity;
this.scene.add(mesh);
this.enemyMeshes.set(e, mesh);
}
const x = lerp(e.prevX, e.x, alpha);
const y = lerp(e.prevY, e.y, alpha);
mesh.position.set(x, y, Z.entity);
mesh.scale.set(e.w, e.h, 1);
const base = e.type === 'fast' ? this.theme.enemyFast : e.type === 'boss' ? this.theme.enemyBoss : this.theme.enemyNormal;
const flashing = e.hitTimer > 0 && e.hitTimer % 4 < 2;
(mesh.material as THREE.MeshBasicMaterial).color.setHex(flashing ? this.theme.flash : base);
}
this.sweep(this.enemyMeshes, live);
}
private syncTears(room: Room, alpha: number): void {
const live = new Set<Projectile>();
for (const t of room.tears) {
if (!t.alive) continue;
live.add(t);
let mesh = this.tearMeshes.get(t);
if (!mesh) {
mesh = new THREE.Mesh(this.unitCircle, flatMat({ color: this.theme.tear }));
mesh.position.z = Z.tear;
mesh.scale.set(PROJECTILE.radius * 2, PROJECTILE.radius * 2, 1);
this.scene.add(mesh);
this.tearMeshes.set(t, mesh);
}
mesh.position.set(lerp(t.prevX, t.x, alpha), lerp(t.prevY, t.y, alpha), Z.tear);
}
this.sweep(this.tearMeshes, live);
}
private syncSwing(game: Game): void {
const s = game.meleeSwing;
if (!s || !s.alive) { this.swingMesh.visible = false; return; }
this.swingMesh.visible = true;
this.swingMesh.position.set(s.box.x + s.box.w / 2, s.box.y + s.box.h / 2, Z.swing);
this.swingMesh.scale.set(s.box.w, s.box.h, 1);
(this.swingMesh.material as THREE.MeshBasicMaterial).opacity = 0.45 * (s.life / 10);
}
// ── Утилиты управления ресурсами ──────────────────────────
/** Удаляет меши, чьих сущностей больше нет, освобождая их материалы. */
private sweep<K>(map: Map<K, THREE.Mesh>, live: Set<K>): void {
for (const [key, mesh] of map) {
if (live.has(key)) continue;
this.scene.remove(mesh);
(mesh.material as THREE.Material).dispose();
map.delete(key);
}
}
private clearGroup(group: THREE.Group): void {
// Материалы и геометрия тайлов общие (живут весь срок рендера),
// поэтому здесь только убираем меши из сцены — без dispose.
group.clear();
}
dispose(): void {
this.clearGroup(this.roomGroup);
this.sweep(this.enemyMeshes, new Set());
this.sweep(this.tearMeshes, new Set());
(this.playerMesh.material as THREE.Material).dispose();
(this.swingMesh.material as THREE.Material).dispose();
this.unitPlane.dispose();
this.unitCircle.dispose();
for (const m of Object.values(this.tileMats)) m.dispose();
this.renderer.dispose();
}
}
-270
View File
@@ -1,270 +0,0 @@
import { DIR, OX, OY, TILE } from '../constants';
import type { Room } from '../room/Room';
import type { Player } from '../entities/Player';
import type { MeleeSwing } from '../entities/MeleeSwing';
/** Draw enemies, player, tears, and the melee swing arc */
export function drawEntities(
ctx: CanvasRenderingContext2D,
room: Room,
player: Player,
meleeSwing: MeleeSwing | null,
): void {
// --- ENEMIES ---
for (const e of room.enemies) {
if (!e.alive) continue;
const flash = e.hitTimer > 0 && e.hitTimer % 4 < 2;
ctx.save();
// Shadow
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.beginPath();
ctx.ellipse(e.x + 2, e.y + e.h / 4, e.w / 3, 4, 0, 0, Math.PI * 2);
ctx.fill();
if (e.type === 'boss') {
drawBoss(ctx, e, flash);
} else if (e.type === 'fast') {
drawFastEnemy(ctx, e, flash);
} else {
drawNormalEnemy(ctx, e, flash);
}
ctx.restore();
}
// --- PLAYER ---
drawPlayer(ctx, player);
// --- TEARS ---
for (const t of room.tears) {
if (!t.alive) continue;
ctx.save();
ctx.fillStyle = '#6699cc';
ctx.beginPath();
ctx.arc(t.x, t.y, t.r, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#99bbee';
ctx.beginPath();
ctx.arc(t.x - 1.5, t.y - 1.5, t.r - 2, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
// --- MELEE SWING ---
if (meleeSwing && meleeSwing.alive) {
drawMeleeSwing(ctx, meleeSwing);
}
}
function drawBoss(ctx: CanvasRenderingContext2D, e: any, flash: boolean): void {
ctx.fillStyle = flash ? '#ddd' : '#5a0a0a';
ctx.beginPath();
ctx.arc(e.x, e.y, e.w / 2, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#4a0808';
ctx.beginPath();
ctx.arc(e.x - 3, e.y - 3, e.w / 2 - 4, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = flash ? '#000' : '#ff3333';
ctx.beginPath();
ctx.arc(e.x - 8, e.y - 8, 5, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(e.x + 8, e.y - 8, 5, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(e.x - 8, e.y - 8, 2.5, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(e.x + 8, e.y - 8, 2.5, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = flash ? '#bbb' : '#3a0505';
ctx.beginPath();
ctx.moveTo(e.x - 16, e.y - e.w / 2 + 4);
ctx.lineTo(e.x - 8, e.y - e.w / 2 - 16);
ctx.lineTo(e.x, e.y - e.w / 2 + 4);
ctx.fill();
ctx.beginPath();
ctx.moveTo(e.x - 4, e.y - e.w / 2 + 4);
ctx.lineTo(e.x + 4, e.y - e.w / 2 - 16);
ctx.lineTo(e.x + 12, e.y - e.w / 2 + 4);
ctx.fill();
if (e.hp < e.maxHp) {
ctx.fillStyle = '#222';
ctx.fillRect(e.x - 22, e.y - e.h / 2 - 14, 44, 4);
ctx.fillStyle = '#c33';
ctx.fillRect(e.x - 22, e.y - e.h / 2 - 14, 44 * (e.hp / e.maxHp), 4);
}
}
function drawFastEnemy(ctx: CanvasRenderingContext2D, e: any, flash: boolean): void {
ctx.fillStyle = flash ? '#ddd' : '#992222';
ctx.beginPath();
ctx.arc(e.x, e.y, e.w / 2, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#771111';
ctx.beginPath();
ctx.arc(e.x - 1, e.y - 1, e.w / 2 - 3, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#ff4444';
ctx.beginPath();
ctx.arc(e.x - 5, e.y - 4, 3, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(e.x + 5, e.y - 4, 3, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(e.x - 5, e.y - 5, 1.5, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(e.x + 5, e.y - 5, 1.5, 0, Math.PI * 2);
ctx.fill();
}
function drawNormalEnemy(ctx: CanvasRenderingContext2D, e: any, flash: boolean): void {
ctx.fillStyle = flash ? '#ccc' : '#5a4a2e';
ctx.fillRect(e.x - e.w / 2, e.y - e.h / 2, e.w, e.h);
ctx.fillStyle = '#4a3a1e';
ctx.fillRect(e.x - e.w / 2 + 3, e.y - e.h / 2 + 3, e.w - 6, e.h - 6);
ctx.fillStyle = '#332816';
ctx.fillRect(e.x - e.w / 2 + 6, e.y - e.h / 2 + 6, e.w - 12, e.h - 12);
ctx.fillStyle = '#ffcc66';
ctx.fillRect(e.x - 7, e.y - 5, 5, 5);
ctx.fillRect(e.x + 2, e.y - 5, 5, 5);
ctx.fillStyle = '#000';
ctx.fillRect(e.x - 6, e.y - 4, 3, 3);
ctx.fillRect(e.x + 3, e.y - 4, 3, 3);
}
function drawPlayer(ctx: CanvasRenderingContext2D, p: Player): void {
ctx.save();
const flash = p.invTimer > 0 && p.invTimer % 6 < 3;
const bodyColor = p.mode === 0 ? '#2a6a9a' : '#9a3a2a';
ctx.fillStyle = flash ? '#ddd' : bodyColor;
ctx.fillRect(p.x - p.w / 2, p.y - p.h / 2, p.w, p.h);
ctx.fillStyle = flash ? '#ccc' : 'rgba(0,0,0,0.3)';
ctx.fillRect(p.x - p.w / 2 + 3, p.y - p.h / 2 + 3, p.w - 6, p.h - 6);
// Weapon
const [fx, fy] = DIR[p.facing];
const wx = p.x + fx * (p.w / 2 + 4);
const wy = p.y + fy * (p.h / 2 + 4);
if (p.mode === 0) {
drawPistol(ctx, p, wx, wy, fx, fy, flash);
} else {
drawKnife(ctx, wx, wy, fx, fy, flash);
}
// Eyes
ctx.fillStyle = '#fff';
const ex = p.x + fx * 5;
const ey = p.y + fy * 5;
ctx.fillRect(ex - 5, ey - 4, 4, 5);
ctx.fillRect(ex + 1, ey - 4, 4, 5);
ctx.fillStyle = '#111';
ctx.fillRect(ex - 4 + fx, ey - 3 + fy, 2, 3);
ctx.fillRect(ex + 2 + fx, ey - 3 + fy, 2, 3);
ctx.restore();
}
function drawPistol(
ctx: CanvasRenderingContext2D,
p: Player,
wx: number, wy: number,
fx: number, fy: number,
flash: boolean,
): void {
ctx.strokeStyle = flash ? '#999' : '#555';
ctx.lineWidth = 3;
ctx.lineCap = 'round';
// Barrel
ctx.beginPath();
ctx.moveTo(wx, wy);
ctx.lineTo(wx + fx * 14 + fy * 2, wy + fy * 14 + fx * 2);
ctx.stroke();
// Body
ctx.fillStyle = flash ? '#aaa' : '#444';
ctx.save();
const angle = fy !== 0 ? (Math.PI / 2) * (fy < 0 ? -1 : 1) : fx < 0 ? Math.PI : 0;
ctx.translate(p.x + fx * 8, p.y + fy * 8);
ctx.rotate(angle);
ctx.fillRect(-7, -4, 14, 8);
ctx.restore();
// Muzzle flash
if (p.atkCD > 8 && p.mode === 0) {
ctx.fillStyle = 'rgba(255,200,50,0.6)';
ctx.beginPath();
ctx.arc(wx + fx * 16, wy + fy * 16, 6, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'rgba(255,255,200,0.4)';
ctx.beginPath();
ctx.arc(wx + fx * 18, wy + fy * 18, 8, 0, Math.PI * 2);
ctx.fill();
}
}
function drawKnife(
ctx: CanvasRenderingContext2D,
wx: number, wy: number,
fx: number, fy: number,
flash: boolean,
): void {
ctx.strokeStyle = flash ? '#bbb' : '#ccc';
ctx.lineWidth = 2;
// Blade triangle
const kx = wx + fx * 6;
const ky = wy + fy * 6;
ctx.beginPath();
ctx.moveTo(kx, ky);
ctx.lineTo(kx + fx * 16 - fy * 6, ky + fy * 16 + fx * 6);
ctx.lineTo(kx + fx * 16 + fy * 6, ky + fy * 16 - fx * 6);
ctx.closePath();
ctx.fillStyle = flash ? '#ddd' : '#d4d4d4';
ctx.fill();
ctx.stroke();
// Handle
ctx.fillStyle = flash ? '#a99' : '#5a3a1a';
ctx.fillRect(kx - fx * 3 - fy * 3, ky - fy * 3 - fx * 3, 8, 8);
// Guard
ctx.fillStyle = flash ? '#bbb' : '#888';
ctx.fillRect(kx - fx * 2 - fy * 5, ky - fy * 2 - fx * 5, 5, 12);
}
function drawMeleeSwing(ctx: CanvasRenderingContext2D, s: MeleeSwing): void {
const alpha = s.life / 10;
ctx.save();
ctx.globalAlpha = alpha * 0.35;
ctx.fillStyle = '#cc8844';
ctx.fillRect(s.box.x, s.box.y, s.box.w, s.box.h);
ctx.globalAlpha = alpha;
ctx.strokeStyle = '#ddbb88';
ctx.lineWidth = 2;
ctx.strokeRect(s.box.x, s.box.y, s.box.w, s.box.h);
ctx.globalAlpha = alpha * 0.8;
ctx.strokeStyle = '#ffcc88';
ctx.lineWidth = 3;
const [dx, dy] = DIR[s.dir];
ctx.beginPath();
ctx.moveTo(s.box.x + s.box.w / 2 - dx * 18, s.box.y + s.box.h / 2 - dy * 18);
ctx.lineTo(s.box.x + s.box.w / 2 + dx * 18, s.box.y + s.box.h / 2 + dy * 18);
ctx.stroke();
ctx.restore();
}
-100
View File
@@ -1,100 +0,0 @@
import { CW, CH, OY, RH } from '../constants';
import { MODE_RANGED, MODE_MELEE } from '../constants';
import type { Player } from '../entities/Player';
import type { Room } from '../room/Room';
/** Draw the HUD: HP bar, mode indicator, enemy count, room label */
export function drawHUD(ctx: CanvasRenderingContext2D, player: Player, room: Room): void {
drawHPBar(ctx, player);
drawModeIndicator(ctx, player);
drawEnemyCount(ctx, room);
drawRoomLabel(ctx, room);
}
function drawHPBar(ctx: CanvasRenderingContext2D, p: Player): void {
const bx = 20, by = 20, bw = 140, bh = 14;
ctx.fillStyle = '#111';
ctx.fillRect(bx, by, bw, bh);
ctx.fillStyle = '#2a0a0a';
ctx.fillRect(bx + 2, by + 2, bw - 4, bh - 4);
const ratio = Math.max(0, p.hp / p.maxHp);
const color = ratio > 0.5 ? '#993333' : ratio > 0.25 ? '#994422' : '#663322';
ctx.fillStyle = color;
ctx.fillRect(bx + 2, by + 2, (bw - 4) * ratio, bh - 4);
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
ctx.strokeRect(bx, by, bw, bh);
ctx.fillStyle = '#bbb';
ctx.font = '10px monospace';
ctx.textAlign = 'center';
ctx.fillText(`HP ${p.hp}/${p.maxHp}`, bx + bw / 2, by + bh - 3);
}
function drawModeIndicator(ctx: CanvasRenderingContext2D, p: Player): void {
const my = CH - 46;
ctx.textAlign = 'center';
const label = p.mode === MODE_RANGED ? 'RANGED' : 'MELEE';
const color = p.mode === MODE_RANGED ? '#4488cc' : '#cc6644';
ctx.fillStyle = '#0d0d0d';
ctx.fillRect(CW / 2 - 95, my - 18, 190, 34);
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.strokeRect(CW / 2 - 95, my - 18, 190, 34);
ctx.fillStyle = color;
ctx.font = 'bold 17px monospace';
ctx.fillText(`[ ${label} ]`, CW / 2, my + 8);
ctx.fillStyle = '#555';
ctx.font = '11px monospace';
ctx.fillText('[Tab/Q] switch', CW / 2, my - 26);
// Small weapon icon
if (p.mode === MODE_RANGED) {
ctx.strokeStyle = '#88bbdd';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(CW / 2 - 82, my - 4);
ctx.lineTo(CW / 2 - 72, my - 4);
ctx.stroke();
ctx.fillStyle = '#88bbdd';
ctx.fillRect(CW / 2 - 82, my - 8, 10, 8);
} else {
ctx.fillStyle = '#ddbb88';
ctx.beginPath();
ctx.moveTo(CW / 2 - 82, my - 10);
ctx.lineTo(CW / 2 - 74, my - 2);
ctx.lineTo(CW / 2 - 82, my + 4);
ctx.fill();
}
}
function drawEnemyCount(ctx: CanvasRenderingContext2D, room: Room): void {
const alive = room.enemies.filter(e => e.alive).length;
ctx.textAlign = 'left';
if (alive > 0) {
ctx.fillStyle = '#aa4444';
ctx.font = '13px monospace';
ctx.fillText(`\u25B6 ${alive}`, 20, CH - 18);
} else if (!room.cleared && room.type !== 'spawn') {
ctx.fillStyle = '#886633';
ctx.font = '13px monospace';
ctx.fillText('Clear the room', 20, CH - 18);
}
}
function drawRoomLabel(ctx: CanvasRenderingContext2D, room: Room): void {
if (!room.visited) return;
ctx.textAlign = 'right';
const labels: Record<string, string> = { spawn: 'START', normal: '', treasure: 'TREASURE', boss: 'BOSS' };
const label = labels[room.type];
if (label) {
ctx.fillStyle = '#555';
ctx.font = '11px monospace';
ctx.fillText(label, CW - 20, OY + RH + 30);
}
}
-59
View File
@@ -1,59 +0,0 @@
import { CW } from '../constants';
import type { RoomMap } from '../room/RoomMap';
const CELL = 14;
const GAP = 2;
/** Draw the 7×7 minimap in the top-right corner */
export function drawMinimap(
ctx: CanvasRenderingContext2D,
map: RoomMap,
cc: number,
cr: number,
): void {
const cs = CELL + GAP;
const mx = CW - 180;
const my = 12;
ctx.fillStyle = 'rgba(0,0,0,0.75)';
ctx.fillRect(mx - 8, my - 8, cs * 7 + 16, cs * 7 + 16);
ctx.strokeStyle = '#333';
ctx.lineWidth = 1;
ctx.strokeRect(mx - 8, my - 8, cs * 7 + 16, cs * 7 + 16);
for (let r = -3; r <= 3; r++) {
for (let c = -3; c <= 3; c++) {
const room = map.get(cc + c, cr + r);
if (!room) continue;
const x = mx + (c + 3) * cs;
const y = my + (r + 3) * cs;
let color = '#141414';
if (room.visited) {
color = room.type === 'spawn' ? '#2a5a2a'
: room.type === 'boss' ? '#5a1a1a'
: room.type === 'treasure' ? '#5a5a1a'
: '#555';
}
ctx.fillStyle = color;
ctx.fillRect(x, y, CELL, CELL);
if (room.visited) {
ctx.strokeStyle = 'rgba(255,255,255,0.12)';
ctx.lineWidth = 1;
if (room.doors.up) ctx.fillRect(x + cs / 2 - 2, y - 2, 4, 3);
if (room.doors.down) ctx.fillRect(x + cs / 2 - 2, y + CELL - 1, 4, 3);
if (room.doors.left) ctx.fillRect(x - 2, y + cs / 2 - 2, 3, 4);
if (room.doors.right) ctx.fillRect(x + CELL - 1, y + cs / 2 - 2, 3, 4);
}
// Highlight current room
if (c === 0 && r === 0) {
ctx.strokeStyle = '#ddd';
ctx.lineWidth = 2;
ctx.strokeRect(x - 1.5, y - 1.5, CELL + 3, CELL + 3);
}
}
}
}
-50
View File
@@ -1,50 +0,0 @@
import { OX, OY, TILE, COLS, ROWS, RW, RH } from '../constants';
import { T_WALL, T_DOOR } from '../room/tiles';
import type { Room } from '../room/Room';
/** Draw the tile grid and wall overlays for a room */
export function drawRoom(ctx: CanvasRenderingContext2D, room: Room): void {
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const x = OX + c * TILE;
const y = OY + r * TILE;
const t = room.tiles[r][c];
if (t === T_WALL) {
ctx.fillStyle = '#1a1a24';
ctx.fillRect(x, y, TILE, TILE);
ctx.fillStyle = '#242436';
ctx.fillRect(x + 2, y + 2, TILE - 4, TILE - 4);
ctx.fillStyle = '#1e1e2c';
ctx.fillRect(x + 4, y + 4, TILE - 8, TILE - 8);
ctx.strokeStyle = '#161620';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x, y + TILE / 2);
ctx.lineTo(x + TILE, y + TILE / 2);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x + TILE / 2, y);
ctx.lineTo(x + TILE / 2, y + TILE / 2);
ctx.stroke();
} else if (t === T_DOOR) {
ctx.fillStyle = '#0d0d14';
ctx.fillRect(x, y, TILE, TILE);
ctx.fillStyle = '#2a1e0e';
ctx.fillRect(x + 6, y + 6, TILE - 12, TILE - 12);
ctx.fillStyle = '#3a2e14';
ctx.fillRect(x + 10, y + 10, TILE - 20, TILE - 20);
} else {
const dark = (r + c) % 2 === 0;
ctx.fillStyle = dark ? '#2e2e24' : '#353528';
ctx.fillRect(x, y, TILE, TILE);
}
}
}
// Border stroke
ctx.strokeStyle = 'rgba(0,0,0,0.3)';
ctx.lineWidth = 2;
ctx.strokeRect(OX, OY, RW, RH);
}
+48
View File
@@ -0,0 +1,48 @@
/**
* theme.ts — ВНЕШНИЙ ВИД мира (задел под кастомные ассеты).
*
* Сейчас «ассеты» — это просто цвета примитивов (квадраты/круги). Но рендер
* берёт их отсюда, а не из хардкода, поэтому вид легко подменить, не трогая
* логику: можно завести несколько тем или, в перспективе, расширить Theme
* полями со спрайтами/текстурами (см. комментарий ниже) и научить
* ThreeRenderer вешать их на материалы.
*/
export interface Theme {
/** Цвета (0xRRGGBB) элементов мира. */
bg: number;
floorA: number;
floorB: number;
wall: number;
door: number;
playerRanged: number;
playerMelee: number;
enemyNormal: number;
enemyFast: number;
enemyBoss: number;
tear: number;
swing: number;
flash: number; // цвет «вспышки» при попадании/неуязвимости
// ── Задел на будущее (пока не используется) ───────────────
// Чтобы перейти со сплошных цветов на картинки, добавь сюда, например:
// textures?: { floor?: string; wall?: string; player?: string; ... }
// (URL/путь к изображению), загрузи их через THREE.TextureLoader в
// ThreeRenderer и положи в material.map вместо/вместе с color.
}
/** Тема по умолчанию — текущая «тёмное подземелье». */
export const DEFAULT_THEME: Theme = {
bg: 0x0a0a0f,
floorA: 0x2e2e24,
floorB: 0x353528,
wall: 0x242436,
door: 0x3a2e14,
playerRanged: 0x2a6a9a,
playerMelee: 0x9a3a2a,
enemyNormal: 0x5a4a2e,
enemyFast: 0x992222,
enemyBoss: 0x5a0a0a,
tear: 0x6699cc,
swing: 0xcc8844,
flash: 0xdddddd,
};