Coop с AI/базой (соло-старт), реванш, чистые URL, доработки клиента

Сервер (Game.hpp/cpp):
- coop-режим: AI-противники (волна 8, до 3 одновременно), простое
  преследование базы с рандомизацией, база с укрытием из кирпича.
- Комната стартует соло (1 игрок), второй может подключиться позже.
- Fix: хитбокс пули по базе брал радиус танка вместо пули.
- Fix: AI при столкновении со стеной теперь сразу перерешает направление,
  а не долбит в одну точку до 3с — без этого база падала за секунды.

Клиент:
- Танк: гусеницы, башня, заметный ствол (было — незаметный нубик).
- Рендер базы (укрытие/флаг), AI-танки — отдельным оттенком зелёного.
- Экран победы/поражения — крупный glitch-текст на весь оверлей вместо
  строки текста; кнопки "играть ещё" (без reload) и "в лобби".
- Блок кнопок управления (D-pad + огонь) справа от игрового поля.
- Лобби: coop стартует по кнопке "готов" в одиночку.

nginx: try_files с fallback на .html — чистые URL (/projects, /game)
без расширения, старые /projects.html и т.п. продолжают работать.
This commit is contained in:
2026-08-06 11:39:09 +05:00
parent 8a4c48c5e1
commit 84da9b49e2
10 changed files with 588 additions and 94 deletions
+114 -9
View File
@@ -90,32 +90,137 @@
} }
#battlecity-canvas-container { #battlecity-canvas-container {
max-width: 640px; position: relative;
max-width: 900px;
margin: 1.5rem 0; margin: 1.5rem 0;
} }
#battlecity-canvas-container canvas { .battle-layout {
display: flex;
align-items: flex-start;
gap: 1.5rem;
flex-wrap: wrap;
}
#battle-canvas-slot canvas {
border: var(--border); border: var(--border);
background: var(--color-bg); background: var(--color-bg);
display: block; display: block;
} }
#battle-result { /* --- блок управления справа от поля --- */
color: var(--color-accent); .battle-controls {
font-size: 1.1rem; display: flex;
margin: 0.75rem 0; flex-direction: column;
align-items: center;
gap: 1.25rem;
padding-top: 0.5rem;
} }
#battle-back { .dpad {
display: grid;
grid-template-columns: repeat(3, 44px);
grid-template-rows: repeat(2, 44px);
gap: 4px;
}
.dpad button {
background: var(--color-bg-raised);
border: 1px solid var(--color-accent-dim);
color: var(--color-accent);
font-family: var(--font-mono);
font-size: 1.1rem;
cursor: pointer;
user-select: none;
touch-action: none;
}
.dpad button:active {
background: var(--color-accent-dim);
color: var(--color-bg);
}
.dpad__up { grid-column: 2; grid-row: 1; }
.dpad__left { grid-column: 1; grid-row: 2; }
.dpad__right { grid-column: 3; grid-row: 2; }
.dpad__down { grid-column: 2; grid-row: 2; }
.fire-btn {
background: var(--color-bg-raised);
border: 1px solid var(--color-accent);
color: var(--color-accent);
font-family: var(--font-mono);
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 0.75rem 1.5rem;
cursor: pointer;
user-select: none;
touch-action: none;
}
.fire-btn:active {
background: var(--color-accent);
color: var(--color-bg);
}
/* --- экран победы/поражения --- */
#battle-result-overlay {
display: none;
position: absolute;
inset: 0;
align-items: center;
justify-content: center;
background: rgba(10, 14, 12, 0.9);
z-index: 5;
}
.battle-result {
text-align: center;
padding: 2rem;
border: var(--border);
background: var(--color-bg-raised);
}
.battle-result h2 {
font-size: 3rem;
margin: 0 0 1rem;
letter-spacing: 0.05em;
}
.battle-result--win h2 {
color: var(--color-accent);
text-shadow: 0 0 16px var(--color-accent-dim);
}
.battle-result--lose h2 {
color: var(--color-silver);
}
.battle-result--draw h2 {
color: var(--color-silver);
}
.battle-result p {
color: var(--color-fg);
margin: 0 0 1.5rem;
}
.battle-result__actions {
display: flex;
gap: 1rem;
justify-content: center;
}
.battle-result__actions button {
background: transparent; background: transparent;
border: 1px solid var(--color-accent-dim); border: 1px solid var(--color-accent-dim);
color: var(--color-accent); color: var(--color-accent);
font-family: var(--font-mono); font-family: var(--font-mono);
padding: 0.35rem 0.75rem; padding: 0.5rem 1.25rem;
cursor: pointer; cursor: pointer;
} }
#battle-back:hover { .battle-result__actions button:hover {
border-color: var(--color-accent); border-color: var(--color-accent);
box-shadow: 0 0 6px var(--color-accent-dim); box-shadow: 0 0 6px var(--color-accent-dim);
} }
+2 -3
View File
@@ -19,13 +19,12 @@
</a> </a>
<ul class="nav-links"> <ul class="nav-links">
<li><a href="/">whoami</a></li> <li><a href="/">whoami</a></li>
<li><a href="/projects.html">ls projects/</a></li> <li><a href="/projects">ls projects/</a></li>
<li><a href="/game.html" aria-current="page">./battlecity</a></li> <li><a href="/game" aria-current="page">./battlecity</a></li>
</ul> </ul>
</header> </header>
<main id="game-root"> <main id="game-root">
<!-- TODO: coop-режим с AI и защитой базы — этап 5 -->
<h2 class="prompt">./battlecity</h2> <h2 class="prompt">./battlecity</h2>
<div id="lobby"></div> <div id="lobby"></div>
<div id="battlecity-canvas-container" style="display: none"></div> <div id="battlecity-canvas-container" style="display: none"></div>
+2 -2
View File
@@ -20,8 +20,8 @@
</a> </a>
<ul class="nav-links"> <ul class="nav-links">
<li><a href="/" aria-current="page">whoami</a></li> <li><a href="/" aria-current="page">whoami</a></li>
<li><a href="/projects.html">ls projects/</a></li> <li><a href="/projects">ls projects/</a></li>
<li><a href="/game.html">./battlecity</a></li> <li><a href="/game">./battlecity</a></li>
</ul> </ul>
</header> </header>
+143 -15
View File
@@ -1,4 +1,5 @@
import { ClientMessage, ServerMessage } from './protocol.js'; import { ClientMessage, ServerMessage } from './protocol.js';
import { returnToLobbyContainer, leaveRoomAndReturn } from './lobby.js';
const TILE_PX = 32; const TILE_PX = 32;
// Quintus транслирует и вращает контекст сам (Sprite.render -> matrix.setContextTransform) // Quintus транслирует и вращает контекст сам (Sprite.render -> matrix.setContextTransform)
@@ -12,21 +13,46 @@ let myPlayerId = null;
let stage = null; let stage = null;
let tankSprites = new Map(); let tankSprites = new Map();
let bulletSprites = new Map(); let bulletSprites = new Map();
let baseSprite = null;
let lastSentInput = null; let lastSentInput = null;
let seq = 0; let seq = 0;
let polling = false; let polling = false;
function tankColor(p) {
if (p.isAi) return '#0a8f2c';
return p.isMe ? '#00ff41' : '#9fa3a0';
}
function setupEntities() { function setupEntities() {
Q.Sprite.extend('Tank', { Q.Sprite.extend('Tank', {
init(p) { init(p) {
this._super(p, { w: 26, h: 26, renderAlways: true }); this._super(p, { w: 24, h: 24, renderAlways: true });
}, },
draw(ctx) { draw(ctx) {
const p = this.p; const p = this.p;
ctx.fillStyle = p.isMe ? '#00ff41' : '#9fa3a0'; const color = tankColor(p);
// корпус
ctx.fillStyle = color;
ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h); ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
// гусеницы по бокам
ctx.fillStyle = '#0a0e0c'; ctx.fillStyle = '#0a0e0c';
ctx.fillRect(-3, -p.h / 2 - 8, 6, 12); ctx.fillRect(-p.w / 2, -p.h / 2, 3, p.h);
ctx.fillRect(p.w / 2 - 3, -p.h / 2, 3, p.h);
// башня
ctx.beginPath();
ctx.arc(0, 0, p.w / 2 - 5, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.lineWidth = 1.5;
ctx.strokeStyle = '#0a0e0c';
ctx.stroke();
// ствол — явно торчит вперёд по направлению взгляда (локально «вверх»)
ctx.fillStyle = '#0a0e0c';
ctx.fillRect(-2.5, -p.h / 2 - 12, 5, 16);
}, },
}); });
@@ -59,6 +85,26 @@ function setupEntities() {
} }
}, },
}); });
Q.Sprite.extend('Base', {
init(p) {
this._super(p, { w: TILE_PX * 0.85, h: TILE_PX * 0.85, renderAlways: true });
},
draw(ctx) {
const p = this.p;
ctx.fillStyle = p.alive ? '#9fa3a0' : '#2a2d2b';
ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
ctx.strokeStyle = '#0a0e0c';
ctx.strokeRect(-p.w / 2 + 1, -p.h / 2 + 1, p.w - 2, p.h - 2);
ctx.fillStyle = p.alive ? '#00ff41' : '#0a0e0c';
ctx.beginPath();
ctx.moveTo(0, -p.h / 2);
ctx.lineTo(-p.w / 4, 0);
ctx.lineTo(p.w / 4, 0);
ctx.closePath();
ctx.fill();
},
});
} }
function ensureQuintus(cols, rows) { function ensureQuintus(cols, rows) {
@@ -78,8 +124,6 @@ function ensureQuintus(cols, rows) {
Q.scene('battle', (stageRef) => { Q.scene('battle', (stageRef) => {
stage = stageRef; stage = stageRef;
}); });
document.getElementById('battlecity-canvas-container').appendChild(Q.el);
} }
function buildMap(map) { function buildMap(map) {
@@ -100,6 +144,28 @@ function buildMap(map) {
} }
} }
function bindControlButtons(root) {
const press = (input, active) => {
if (Q) {
Q.inputs[input] = active;
}
};
root.querySelectorAll('[data-input]').forEach((btn) => {
const input = btn.dataset.input;
btn.addEventListener('mousedown', () => press(input, true));
btn.addEventListener('mouseup', () => press(input, false));
btn.addEventListener('mouseleave', () => press(input, false));
btn.addEventListener('touchstart', (e) => {
e.preventDefault();
press(input, true);
});
btn.addEventListener('touchend', (e) => {
e.preventDefault();
press(input, false);
});
});
}
function pollInput() { function pollInput() {
if (!polling) { if (!polling) {
return; return;
@@ -121,10 +187,17 @@ function pollInput() {
} }
function onState(payload) { function onState(payload) {
const seenTanks = new Set();
for (const t of payload.tanks) { for (const t of payload.tanks) {
seenTanks.add(t.id);
let sprite = tankSprites.get(t.id); let sprite = tankSprites.get(t.id);
if (!sprite) { if (!sprite) {
sprite = new Q.Tank({ x: t.x * TILE_PX, y: t.y * TILE_PX, isMe: t.id === myPlayerId }); sprite = new Q.Tank({
x: t.x * TILE_PX,
y: t.y * TILE_PX,
isMe: t.id === myPlayerId,
isAi: !!t.is_ai,
});
stage.insert(sprite); stage.insert(sprite);
tankSprites.set(t.id, sprite); tankSprites.set(t.id, sprite);
} }
@@ -133,6 +206,12 @@ function onState(payload) {
sprite.p.angle = DIR_DEGREES[t.direction] || 0; sprite.p.angle = DIR_DEGREES[t.direction] || 0;
sprite.p.hidden = !t.alive; sprite.p.hidden = !t.alive;
} }
for (const [id, sprite] of tankSprites) {
if (!seenTanks.has(id)) {
sprite.destroy();
tankSprites.delete(id);
}
}
const seenBullets = new Set(); const seenBullets = new Set();
for (const b of payload.bullets) { for (const b of payload.bullets) {
@@ -152,14 +231,49 @@ function onState(payload) {
bulletSprites.delete(id); bulletSprites.delete(id);
} }
} }
if (payload.base) {
if (!baseSprite) {
baseSprite = new Q.Base({
x: payload.base.x * TILE_PX,
y: payload.base.y * TILE_PX,
alive: payload.base.alive,
});
stage.insert(baseSprite);
} else {
baseSprite.p.alive = payload.base.alive;
}
}
} }
function onOver(payload) { function onOver(payload) {
polling = false; polling = false;
const resultText = { win: обеда', lose: оражение', draw: 'Ничья' }[payload.result] || payload.result; const titles = { win: ОБЕДА', lose: ОРАЖЕНИЕ', draw: 'НИЧЬЯ' };
const resultEl = document.getElementById('battle-result'); const title = titles[payload.result] || payload.result.toUpperCase();
resultEl.textContent = `${resultText}${payload.reason}`; const overlay = document.getElementById('battle-result-overlay');
document.getElementById('battle-back').style.display = 'inline-block'; overlay.innerHTML = `
<div class="battle-result battle-result--${payload.result}">
<h2 class="glitch" data-text="${title}">${title}</h2>
<p>${payload.reason}</p>
<div class="battle-result__actions">
<button data-action="rematch">играть ещё</button>
<button data-action="to-lobby">в лобби</button>
</div>
</div>`;
overlay.style.display = 'flex';
}
function onOverlayClick(e) {
const btn = e.target.closest('[data-action]');
if (!btn) return;
const overlay = document.getElementById('battle-result-overlay');
overlay.style.display = 'none';
overlay.innerHTML = '';
if (btn.dataset.action === 'rematch') {
returnToLobbyContainer();
} else {
leaveRoomAndReturn();
}
} }
export function startBattle(networkInstance, payload, ownPlayerId) { export function startBattle(networkInstance, payload, ownPlayerId) {
@@ -172,12 +286,30 @@ export function startBattle(networkInstance, payload, ownPlayerId) {
document.getElementById('lobby').style.display = 'none'; document.getElementById('lobby').style.display = 'none';
const container = document.getElementById('battlecity-canvas-container'); const container = document.getElementById('battlecity-canvas-container');
container.style.display = 'block'; container.style.display = 'block';
container.innerHTML = '<p id="battle-result"></p><button id="battle-back" style="display:none">выйти в лобби</button>'; container.innerHTML = `
<div class="battle-layout">
<div id="battle-canvas-slot"></div>
<div class="battle-controls">
<div class="dpad">
<button class="dpad__up" data-input="up">&uarr;</button>
<button class="dpad__left" data-input="left">&larr;</button>
<button class="dpad__right" data-input="right">&rarr;</button>
<button class="dpad__down" data-input="down">&darr;</button>
</div>
<button class="fire-btn" data-input="fire">огонь</button>
</div>
</div>
<div id="battle-result-overlay"></div>`;
ensureQuintus(cols, rows); ensureQuintus(cols, rows);
document.getElementById('battle-canvas-slot').appendChild(Q.el);
bindControlButtons(container.querySelector('.battle-controls'));
container.querySelector('#battle-result-overlay').addEventListener('click', onOverlayClick);
Q.stageScene('battle', 0); Q.stageScene('battle', 0);
tankSprites = new Map(); tankSprites = new Map();
bulletSprites = new Map(); bulletSprites = new Map();
baseSprite = null;
buildMap(payload.map); buildMap(payload.map);
@@ -188,8 +320,4 @@ export function startBattle(networkInstance, payload, ownPlayerId) {
seq = 0; seq = 0;
polling = true; polling = true;
requestAnimationFrame(pollInput); requestAnimationFrame(pollInput);
document.getElementById('battle-back').addEventListener('click', () => {
location.reload();
});
} }
+17 -6
View File
@@ -52,14 +52,12 @@ function renderLobbyView() {
function renderRoomView() { function renderRoomView() {
const full = currentRoom.players.length >= 2; const full = currentRoom.players.length >= 2;
let statusLine = ''; let statusLine = '';
let readyBtn = ''; let readyBtn = '<button data-action="ready">готов</button>';
if (currentRoom.mode !== 'pvp') { if (currentRoom.mode === 'pvp' && !full) {
statusLine = '<p class="lobby-error">coop ещё не реализован (этап 5)</p>';
} else if (!full) {
statusLine = '<p class="lobby-error">жду второго игрока (1/2) — открой комнату во второй вкладке/другим человеком</p>'; statusLine = '<p class="lobby-error">жду второго игрока (1/2) — открой комнату во второй вкладке/другим человеком</p>';
readyBtn = '<button data-action="ready" disabled>готов</button>'; readyBtn = '<button data-action="ready" disabled>готов</button>';
} else { } else if (currentRoom.mode === 'coop' && !full) {
readyBtn = '<button data-action="ready">готов</button>'; statusLine = '<p class="lobby-error">можно начать соло, второй игрок сможет подключиться позже</p>';
} }
container.innerHTML = ` container.innerHTML = `
<div class="lobby-panel"> <div class="lobby-panel">
@@ -83,6 +81,19 @@ function render() {
} }
} }
// Вызывается из battle.js по кнопкам экрана победы/поражения.
export function returnToLobbyContainer() {
document.getElementById('battlecity-canvas-container').style.display = 'none';
container.style.display = '';
render();
}
export function leaveRoomAndReturn() {
currentRoom = null;
net.leaveRoom();
returnToLobbyContainer();
}
container?.addEventListener('click', (e) => { container?.addEventListener('click', (e) => {
const btn = e.target.closest('[data-action]'); const btn = e.target.closest('[data-action]');
if (!btn) return; if (!btn) return;
+2 -2
View File
@@ -20,8 +20,8 @@
</a> </a>
<ul class="nav-links"> <ul class="nav-links">
<li><a href="/">whoami</a></li> <li><a href="/">whoami</a></li>
<li><a href="/projects.html" aria-current="page">ls projects/</a></li> <li><a href="/projects" aria-current="page">ls projects/</a></li>
<li><a href="/game.html">./battlecity</a></li> <li><a href="/game">./battlecity</a></li>
</ul> </ul>
</header> </header>
+267 -45
View File
@@ -5,6 +5,7 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <cstdlib>
namespace { namespace {
constexpr double kTankHalf = 0.4; constexpr double kTankHalf = 0.4;
@@ -13,16 +14,27 @@ constexpr double kBulletSpeed = 8.0; // тайлов/сек
constexpr double kBulletHalf = 0.08; constexpr double kBulletHalf = 0.08;
constexpr int kFireCooldownTicks = 10; // 0.5с при 20 Гц constexpr int kFireCooldownTicks = 10; // 0.5с при 20 Гц
constexpr double kDt = Game::kTickMs / 1000.0; constexpr double kDt = Game::kTickMs / 1000.0;
constexpr double kBaseHalf = 0.45;
} // namespace } // namespace
Game::Game(Room &room, std::function<void()> onFinished) : onFinished_(std::move(onFinished)) { Game::Game(Room &room, std::function<void()> onFinished)
buildMap(); : mode_(room.mode), onFinished_(std::move(onFinished)) {
if (mode_ == "coop") {
buildCoopMap();
} else {
buildPvpMap();
}
for (int i = 0; i < 2; i++) { for (size_t i = 0; i < room.players.size(); i++) {
Tank &t = tanks_[i]; Tank t;
t.player_id = room.players[i].player_id; t.id = room.players[i].player_id;
t.ws = room.players[i].ws; t.ws = room.players[i].ws;
if (i == 0) { if (mode_ == "coop") {
// оба человека стартуют у базы, чуть в стороны друг от друга
t.x = kMapWidth / 2.0 - 1.0 + i * 2.0;
t.y = kMapHeight - 2.5;
t.dir = Dir::Up;
} else if (i == 0) {
t.x = 1.5; t.x = 1.5;
t.y = kMapHeight - 2.5; t.y = kMapHeight - 2.5;
t.dir = Dir::Up; t.dir = Dir::Up;
@@ -31,6 +43,7 @@ Game::Game(Room &room, std::function<void()> onFinished) : onFinished_(std::move
t.y = 1.5; t.y = 1.5;
t.dir = Dir::Down; t.dir = Dir::Down;
} }
tanks_.push_back(t);
} }
} }
@@ -40,7 +53,7 @@ Game::~Game() {
} }
} }
void Game::buildMap() { void Game::buildPvpMap() {
map_.assign(kMapHeight, std::vector<int>(kMapWidth, kEmpty)); map_.assign(kMapHeight, std::vector<int>(kMapWidth, kEmpty));
for (int y = 0; y < kMapHeight; y++) { for (int y = 0; y < kMapHeight; y++) {
for (int x = 0; x < kMapWidth; x++) { for (int x = 0; x < kMapWidth; x++) {
@@ -50,7 +63,6 @@ void Game::buildMap() {
} }
} }
// Симметричные (180°) кластеры кирпича/стали в интерьере карты.
auto placeMirrored = [this](int x, int y, int w, int h, int tile) { auto placeMirrored = [this](int x, int y, int w, int h, int tile) {
for (int dy = 0; dy < h; dy++) { for (int dy = 0; dy < h; dy++) {
for (int dx = 0; dx < w; dx++) { for (int dx = 0; dx < w; dx++) {
@@ -66,6 +78,46 @@ void Game::buildMap() {
placeMirrored(6, 6, 3, 3, kBrick); placeMirrored(6, 6, 3, 3, kBrick);
} }
void Game::buildCoopMap() {
map_.assign(kMapHeight, std::vector<int>(kMapWidth, kEmpty));
for (int y = 0; y < kMapHeight; y++) {
for (int x = 0; x < kMapWidth; x++) {
if (x == 0 || y == 0 || x == kMapWidth - 1 || y == kMapHeight - 1) {
map_[y][x] = kSteel;
}
}
}
// немного укрытий по полю
auto block = [this](int x, int y, int w, int h, int tile) {
for (int dy = 0; dy < h; dy++) {
for (int dx = 0; dx < w; dx++) {
map_[y + dy][x + dx] = tile;
}
}
};
block(2, 5, 2, 2, kBrick);
block(11, 5, 2, 2, kBrick);
block(6, 4, 3, 1, kSteel);
block(4, 8, 2, 2, kBrick);
block(9, 8, 2, 2, kBrick);
// база внизу по центру, укрыта кирпичом с трёх сторон
int bx = kMapWidth / 2;
int by = kMapHeight - 2;
base_ = Base{bx + 0.5, by + 0.5, true};
block(bx - 1, by - 1, 3, 1, kBrick); // сверху
map_[by][bx - 1] = kBrick; // слева
map_[by][bx + 1] = kBrick; // справа
map_[by][bx] = kEmpty; // сама база — не стена
enemy_spawn_points_ = {
{3.5, 1.5},
{kMapWidth / 2.0 + 0.5, 1.5},
{kMapWidth - 3.5, 1.5},
};
}
void Game::start() { void Game::start() {
timer_ = us_create_timer((us_loop_t *)uWS::Loop::get(), 0, sizeof(Game *)); timer_ = us_create_timer((us_loop_t *)uWS::Loop::get(), 0, sizeof(Game *));
*(Game **)us_timer_ext(timer_) = this; *(Game **)us_timer_ext(timer_) = this;
@@ -80,7 +132,7 @@ void Game::start() {
void Game::handleInput(const std::string &player_id, const json &payload) { void Game::handleInput(const std::string &player_id, const json &payload) {
for (auto &t : tanks_) { for (auto &t : tanks_) {
if (t.player_id == player_id) { if (!t.is_ai && t.id == player_id) {
t.up = payload.value("up", false); t.up = payload.value("up", false);
t.down = payload.value("down", false); t.down = payload.value("down", false);
t.left = payload.value("left", false); t.left = payload.value("left", false);
@@ -125,6 +177,13 @@ bool Game::rectHitsTank(double x, double y, const Tank &self) const {
return false; return false;
} }
bool Game::rectHitsBase(double x, double y, double half) const {
if (!base_ || !base_->alive) {
return false;
}
return std::abs(x - base_->x) < half + kBaseHalf && std::abs(y - base_->y) < half + kBaseHalf;
}
void Game::applyInput(Tank &tank) { void Game::applyInput(Tank &tank) {
if (!tank.alive) { if (!tank.alive) {
return; return;
@@ -161,7 +220,7 @@ void Game::applyInput(Tank &tank) {
case Dir::Left: nx -= step; break; case Dir::Left: nx -= step; break;
case Dir::Right: nx += step; break; case Dir::Right: nx += step; break;
} }
if (!rectHitsSolid(nx, ny) && !rectHitsTank(nx, ny, tank)) { if (!rectHitsSolid(nx, ny) && !rectHitsTank(nx, ny, tank) && !rectHitsBase(nx, ny, kTankHalf)) {
tank.x = nx; tank.x = nx;
tank.y = ny; tank.y = ny;
} }
@@ -172,19 +231,80 @@ void Game::applyInput(Tank &tank) {
} }
} }
void Game::updateAi(Tank &tank) {
if (tank.ai_redecide_ticks > 0) {
tank.ai_redecide_ticks--;
} else {
double tx = base_ ? base_->x : tank.x;
double ty = base_ ? base_->y : tank.y;
double dx = tx - tank.x, dy = ty - tank.y;
if (std::rand() % 5 == 0) {
// изредка идём в случайную сторону, чтобы враги не были предсказуемы
tank.ai_dir = static_cast<Dir>(std::rand() % 4);
} else if (std::abs(dx) > std::abs(dy)) {
tank.ai_dir = dx > 0 ? Dir::Right : Dir::Left;
} else {
tank.ai_dir = dy > 0 ? Dir::Down : Dir::Up;
}
tank.ai_redecide_ticks = 30 + std::rand() % 30; // 1.5-3с
}
tank.up = tank.ai_dir == Dir::Up;
tank.down = tank.ai_dir == Dir::Down;
tank.left = tank.ai_dir == Dir::Left;
tank.right = tank.ai_dir == Dir::Right;
tank.fire = (std::rand() % 15) == 0;
}
void Game::spawnEnemiesIfNeeded() {
if (enemies_spawned_total_ >= kMaxEnemiesTotal) {
return;
}
if (enemy_spawn_cooldown_ > 0) {
enemy_spawn_cooldown_--;
return;
}
int concurrent = 0;
for (const auto &t : tanks_) {
if (t.is_ai && t.alive) {
concurrent++;
}
}
if (concurrent >= kMaxConcurrentEnemies) {
return;
}
const auto &sp = enemy_spawn_points_[enemies_spawned_total_ % enemy_spawn_points_.size()];
Tank t;
t.id = "ai-" + std::to_string(next_enemy_id_++);
t.is_ai = true;
t.ws = nullptr;
t.x = sp.first;
t.y = sp.second;
t.dir = Dir::Down;
t.lives = 1;
tanks_.push_back(t);
enemies_spawned_total_++;
enemy_spawn_cooldown_ = kEnemySpawnCooldownTicks;
}
void Game::fireBullet(Tank &tank) { void Game::fireBullet(Tank &tank) {
if (tank.fire_cooldown > 0) { if (tank.fire_cooldown > 0) {
return; return;
} }
bool hasOwnBullet = std::any_of(bullets_.begin(), bullets_.end(), bool hasOwnBullet = std::any_of(bullets_.begin(), bullets_.end(),
[&](const Bullet &b) { return b.owner_id == tank.player_id; }); [&](const Bullet &b) { return b.owner_id == tank.id; });
if (hasOwnBullet) { if (hasOwnBullet) {
return; return;
} }
Bullet b; Bullet b;
b.id = next_bullet_id_++; b.id = next_bullet_id_++;
b.owner_id = tank.player_id; b.owner_id = tank.id;
b.owner_is_ai = tank.is_ai;
b.dir = tank.dir; b.dir = tank.dir;
double offset = kTankHalf + kBulletHalf + 0.01; double offset = kTankHalf + kBulletHalf + 0.01;
b.x = tank.x; b.x = tank.x;
@@ -211,7 +331,6 @@ void Game::updateBullets() {
} }
} }
// Пуля против пули: встречные уничтожают друг друга.
std::vector<bool> dead(bullets_.size(), false); std::vector<bool> dead(bullets_.size(), false);
for (size_t i = 0; i < bullets_.size(); i++) { for (size_t i = 0; i < bullets_.size(); i++) {
if (dead[i]) continue; if (dead[i]) continue;
@@ -224,8 +343,7 @@ void Game::updateBullets() {
} }
} }
int loserIndex = -1; int pvpLoserIndex = -1;
bool anyoneHit = false;
for (size_t i = 0; i < bullets_.size(); i++) { for (size_t i = 0; i < bullets_.size(); i++) {
if (dead[i]) continue; if (dead[i]) continue;
@@ -246,21 +364,41 @@ void Game::updateBullets() {
dead[i] = true; dead[i] = true;
continue; continue;
} }
if (rectHitsBase(b.x, b.y, kBulletHalf)) {
dead[i] = true;
if (base_) {
base_->alive = false;
}
continue;
}
for (int ti = 0; ti < 2; ti++) { for (size_t ti = 0; ti < tanks_.size(); ti++) {
Tank &t = tanks_[ti]; Tank &t = tanks_[ti];
if (!t.alive || t.player_id == b.owner_id) continue; if (!t.alive || t.id == b.owner_id) continue;
if (mode_ == "coop" && t.is_ai == b.owner_is_ai) continue; // без дружественного огня
if (std::abs(b.x - t.x) < kTankHalf + kBulletHalf && std::abs(b.y - t.y) < kTankHalf + kBulletHalf) { if (std::abs(b.x - t.x) < kTankHalf + kBulletHalf && std::abs(b.y - t.y) < kTankHalf + kBulletHalf) {
dead[i] = true; dead[i] = true;
t.lives--; t.lives--;
anyoneHit = true;
if (t.lives <= 0) { if (t.lives <= 0) {
t.alive = false; t.alive = false;
loserIndex = ti; if (mode_ == "pvp") {
pvpLoserIndex = (int)ti;
}
} else { } else {
// респаун на стартовой позиции // респаун на стартовой позиции
t.x = (ti == 0) ? 1.5 : kMapWidth - 2.5; if (mode_ == "coop") {
t.y = (ti == 0) ? kMapHeight - 2.5 : 1.5; size_t humanIdx = 0;
for (auto &tt : tanks_) {
if (&tt == &t) break;
if (!tt.is_ai) humanIdx++;
}
t.x = kMapWidth / 2.0 - 1.0 + humanIdx * 2.0;
t.y = kMapHeight - 2.5;
} else {
t.x = (ti == 0) ? 1.5 : kMapWidth - 2.5;
t.y = (ti == 0) ? kMapHeight - 2.5 : 1.5;
}
} }
break; break;
} }
@@ -273,9 +411,29 @@ void Game::updateBullets() {
} }
bullets_ = std::move(alive); bullets_ = std::move(alive);
(void)anyoneHit; if (mode_ == "pvp" && pvpLoserIndex != -1) {
if (loserIndex != -1) { endGamePvp(1 - pvpLoserIndex);
endGame(1 - loserIndex); }
}
void Game::checkCoopEndConditions() {
if (finished_ || mode_ != "coop") {
return;
}
if (base_ && !base_->alive) {
endGameCoop(false, "база уничтожена");
return;
}
bool anyHumanAlive = std::any_of(tanks_.begin(), tanks_.end(),
[](const Tank &t) { return !t.is_ai && t.alive; });
if (!anyHumanAlive) {
endGameCoop(false, "все танки уничтожены");
return;
}
bool anyEnemyAlive = std::any_of(tanks_.begin(), tanks_.end(),
[](const Tank &t) { return t.is_ai && t.alive; });
if (enemies_spawned_total_ >= kMaxEnemiesTotal && !anyEnemyAlive) {
endGameCoop(true, "волна противника уничтожена");
} }
} }
@@ -286,9 +444,24 @@ void Game::tick() {
tick_count_++; tick_count_++;
for (auto &t : tanks_) { for (auto &t : tanks_) {
if (!t.alive) continue;
if (t.is_ai) {
updateAi(t);
}
double beforeX = t.x, beforeY = t.y;
applyInput(t); applyInput(t);
// Врезались в стену/базу — не долбим её до конца таймера, перерешаем сразу.
if (t.is_ai && t.x == beforeX && t.y == beforeY && (t.up || t.down || t.left || t.right)) {
t.ai_redecide_ticks = 0;
}
} }
if (mode_ == "coop") {
spawnEnemiesIfNeeded();
}
updateBullets(); updateBullets();
checkCoopEndConditions();
if (!finished_) { if (!finished_) {
broadcastState(); broadcastState();
@@ -307,12 +480,13 @@ json Game::dirToJson(Dir d) {
json Game::serializeTank(const Tank &t) const { json Game::serializeTank(const Tank &t) const {
return { return {
{"id", t.player_id}, {"id", t.id},
{"x", t.x}, {"x", t.x},
{"y", t.y}, {"y", t.y},
{"direction", dirToJson(t.dir)}, {"direction", dirToJson(t.dir)},
{"lives", t.lives}, {"lives", t.lives},
{"alive", t.alive}, {"alive", t.alive},
{"is_ai", t.is_ai},
}; };
} }
@@ -327,6 +501,9 @@ json Game::serializeBullet(const Bullet &b) const {
} }
void Game::sendTo(WS *ws, const std::string &type, json payload) { void Game::sendTo(WS *ws, const std::string &type, json payload) {
if (!ws) {
return;
}
json msg = {{"type", type}, {"payload", std::move(payload)}}; json msg = {{"type", type}, {"payload", std::move(payload)}};
ws->send(msg.dump(), uWS::OpCode::TEXT); ws->send(msg.dump(), uWS::OpCode::TEXT);
} }
@@ -338,8 +515,13 @@ void Game::broadcastState() {
for (const auto &b : bullets_) bullets.push_back(serializeBullet(b)); for (const auto &b : bullets_) bullets.push_back(serializeBullet(b));
json payload = {{"tick", tick_count_}, {"tanks", tanks}, {"bullets", bullets}}; json payload = {{"tick", tick_count_}, {"tanks", tanks}, {"bullets", bullets}};
if (base_) {
payload["base"] = {{"x", base_->x}, {"y", base_->y}, {"alive", base_->alive}};
}
for (const auto &t : tanks_) { for (const auto &t : tanks_) {
sendTo(t.ws, "game.state", payload); if (!t.is_ai) {
sendTo(t.ws, "game.state", payload);
}
} }
} }
@@ -350,49 +532,71 @@ json Game::buildStartPayload(const std::string &mode) const {
} }
json players = json::array(); json players = json::array();
for (const auto &t : tanks_) { for (const auto &t : tanks_) {
players.push_back({{"id", t.player_id}}); players.push_back({{"id", t.id}});
} }
return { json payload = {
{"map", mapJson}, {"map", mapJson},
{"mode", mode}, {"mode", mode},
{"players", players}, {"players", players},
{"tick_rate", 1000 / kTickMs}, {"tick_rate", 1000 / kTickMs},
}; };
if (base_) {
payload["base"] = {{"x", base_->x}, {"y", base_->y}};
}
return payload;
} }
void Game::handleDisconnect(WS *ws) { void Game::handleDisconnect(WS *ws) {
if (finished_) { if (finished_) {
return; return;
} }
for (int i = 0; i < 2; i++) {
if (tanks_[i].ws == ws) { if (mode_ == "pvp") {
int winnerIndex = 1 - i; for (size_t i = 0; i < tanks_.size(); i++) {
finished_ = true; if (tanks_[i].ws == ws) {
if (timer_) { int winnerIndex = 1 - (int)i;
us_timer_close(timer_); finished_ = true;
timer_ = nullptr; if (timer_) {
us_timer_close(timer_);
timer_ = nullptr;
}
sendTo(tanks_[winnerIndex].ws, "game.over", {{"result", "win"}, {"reason", "соперник отключился"}});
if (onFinished_) {
onFinished_();
}
return;
} }
sendTo(tanks_[winnerIndex].ws, "game.over", {{"result", "win"}, {"reason", "соперник отключился"}});
if (onFinished_) {
onFinished_();
}
return;
} }
return;
}
// coop
for (auto &t : tanks_) {
if (!t.is_ai && t.ws == ws) {
t.alive = false;
t.ws = nullptr;
break;
}
}
bool anyHumanAlive = std::any_of(tanks_.begin(), tanks_.end(),
[](const Tank &t) { return !t.is_ai && t.alive; });
if (!anyHumanAlive) {
endGameCoop(false, "все игроки отключились");
} }
} }
void Game::endGame(int winnerIndex) { void Game::endGamePvp(int winnerIndex) {
finished_ = true; finished_ = true;
if (timer_) { if (timer_) {
us_timer_close(timer_); us_timer_close(timer_);
timer_ = nullptr; timer_ = nullptr;
} }
for (int i = 0; i < 2; i++) { for (size_t i = 0; i < tanks_.size(); i++) {
std::string result = (winnerIndex == -1) ? "draw" : (i == winnerIndex ? "win" : "lose"); std::string result = (winnerIndex == -1) ? "draw" : ((int)i == winnerIndex ? "win" : "lose");
std::string reason = (winnerIndex == -1) ? "оба танка уничтожены одновременно" std::string reason = (winnerIndex == -1) ? "оба танка уничтожены одновременно"
: (i == winnerIndex) ? "противник уничтожен" : ((int)i == winnerIndex) ? "противник уничтожен"
: "танк уничтожен"; : "танк уничтожен";
sendTo(tanks_[i].ws, "game.over", {{"result", result}, {"reason", reason}}); sendTo(tanks_[i].ws, "game.over", {{"result", result}, {"reason", reason}});
} }
@@ -400,3 +604,21 @@ void Game::endGame(int winnerIndex) {
onFinished_(); onFinished_();
} }
} }
void Game::endGameCoop(bool win, const std::string &reason) {
finished_ = true;
if (timer_) {
us_timer_close(timer_);
timer_ = nullptr;
}
for (const auto &t : tanks_) {
if (!t.is_ai && t.ws) {
sendTo(t.ws, "game.over", {{"result", win ? "win" : "lose"}, {"reason", reason}});
}
}
if (onFinished_) {
onFinished_();
}
}
+35 -10
View File
@@ -2,72 +2,97 @@
#include "Lobby.hpp" #include "Lobby.hpp"
#include <array>
#include <functional> #include <functional>
#include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
struct us_timer_t; struct us_timer_t;
// Authoritative-игра для одной комнаты в режиме pvp (этап 4 из TZ.md). // Authoritative-игра для одной комнаты: pvp (этап 4) и coop с AI (этап 5).
// Coop с AI — этап 5, наследует эту же тик-логику.
class Game { class Game {
public: public:
static constexpr int kTickMs = 50; // 20 Гц static constexpr int kTickMs = 50; // 20 Гц
static constexpr int kMapWidth = 15; static constexpr int kMapWidth = 15;
static constexpr int kMapHeight = 15; static constexpr int kMapHeight = 15;
static constexpr int kStartLives = 3; static constexpr int kStartLives = 3;
static constexpr int kMaxEnemiesTotal = 8; // размер волны в coop
static constexpr int kMaxConcurrentEnemies = 3;
static constexpr int kEnemySpawnCooldownTicks = 60; // 3с
enum Tile { kEmpty = 0, kBrick = 1, kSteel = 2 }; enum Tile { kEmpty = 0, kBrick = 1, kSteel = 2 };
enum class Dir { Up, Right, Down, Left }; enum class Dir { Up, Right, Down, Left };
struct Tank { struct Tank {
std::string player_id; std::string id; // player_id для людей, "ai-N" для AI
WS *ws; WS *ws = nullptr; // nullptr для AI
bool is_ai = false;
double x, y; double x, y;
Dir dir = Dir::Up; Dir dir = Dir::Up;
int lives = kStartLives; int lives = kStartLives;
int fire_cooldown = 0; int fire_cooldown = 0;
bool up = false, down = false, left = false, right = false, fire = false; bool up = false, down = false, left = false, right = false, fire = false;
bool alive = true; bool alive = true;
// состояние простого AI (используется только если is_ai)
Dir ai_dir = Dir::Down;
int ai_redecide_ticks = 0;
}; };
struct Bullet { struct Bullet {
int id; int id;
std::string owner_id; std::string owner_id;
bool owner_is_ai;
double x, y; double x, y;
Dir dir; Dir dir;
}; };
// room.players.size() должен быть == 2 на момент создания. struct Base {
double x, y;
bool alive = true;
};
// room.players.size() — 2 для pvp, 1 или 2 для coop.
Game(Room &room, std::function<void()> onFinished); Game(Room &room, std::function<void()> onFinished);
~Game(); ~Game();
void start(); void start();
void handleInput(const std::string &player_id, const json &payload); void handleInput(const std::string &player_id, const json &payload);
// Технический проигрыш отключившегося второй игрок побеждает. // pvp: технический проигрыш отключившегося, второй побеждает.
// coop: игрок выбывает; если людей не осталось — поражение.
void handleDisconnect(WS *ws); void handleDisconnect(WS *ws);
json buildStartPayload(const std::string &mode) const; json buildStartPayload(const std::string &mode) const;
private: private:
std::string mode_;
std::vector<std::vector<int>> map_; std::vector<std::vector<int>> map_;
std::array<Tank, 2> tanks_; std::vector<Tank> tanks_; // сначала люди, затем (в coop) появляющиеся AI
std::vector<Bullet> bullets_; std::vector<Bullet> bullets_;
std::optional<Base> base_;
std::vector<std::pair<double, double>> enemy_spawn_points_;
int enemies_spawned_total_ = 0;
int enemy_spawn_cooldown_ = 0;
int next_bullet_id_ = 1; int next_bullet_id_ = 1;
int next_enemy_id_ = 1;
int tick_count_ = 0; int tick_count_ = 0;
bool finished_ = false; bool finished_ = false;
us_timer_t *timer_ = nullptr; us_timer_t *timer_ = nullptr;
std::function<void()> onFinished_; std::function<void()> onFinished_;
void buildMap(); void buildPvpMap();
void buildCoopMap();
void tick(); void tick();
void applyInput(Tank &tank); void applyInput(Tank &tank);
void updateAi(Tank &tank);
void spawnEnemiesIfNeeded();
void updateBullets(); void updateBullets();
bool tileSolid(int tx, int ty) const; bool tileSolid(int tx, int ty) const;
bool rectHitsSolid(double x, double y) const; bool rectHitsSolid(double x, double y) const;
bool rectHitsTank(double x, double y, const Tank &self) const; bool rectHitsTank(double x, double y, const Tank &self) const;
bool rectHitsBase(double x, double y, double half) const;
void fireBullet(Tank &tank); void fireBullet(Tank &tank);
void endGame(int winnerIndex); // -1 = ничья void endGamePvp(int winnerIndex); // -1 = ничья
void endGameCoop(bool win, const std::string &reason);
void checkCoopEndConditions();
void broadcastState(); void broadcastState();
void sendTo(WS *ws, const std::string &type, json payload); void sendTo(WS *ws, const std::string &type, json payload);
+5 -1
View File
@@ -250,7 +250,11 @@ void Lobby::maybeStartGame(const std::string &room_id) {
return; return;
} }
Room &room = it->second; Room &room = it->second;
if (room.mode != "pvp" || room.state != "waiting" || room.players.size() != kMaxPlayersPerRoom) { if (room.state != "waiting" || room.players.empty()) {
return;
}
// pvp — строго вдвоём; coop — можно соло, второй подключается позже.
if (room.mode == "pvp" && room.players.size() != kMaxPlayersPerRoom) {
return; return;
} }
bool allReady = std::all_of(room.players.begin(), room.players.end(), bool allReady = std::all_of(room.players.begin(), room.players.end(),
+1 -1
View File
@@ -5,7 +5,7 @@ server {
index index.html; index index.html;
location / { location / {
try_files $uri $uri/ =404; try_files $uri $uri.html $uri/ =404;
} }
# без хешей в именах файлов — просим браузер всегда переспрашивать свежесть # без хешей в именах файлов — просим браузер всегда переспрашивать свежесть