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
+267 -45
View File
@@ -5,6 +5,7 @@
#include <algorithm>
#include <cmath>
#include <cstdlib>
namespace {
constexpr double kTankHalf = 0.4;
@@ -13,16 +14,27 @@ constexpr double kBulletSpeed = 8.0; // тайлов/сек
constexpr double kBulletHalf = 0.08;
constexpr int kFireCooldownTicks = 10; // 0.5с при 20 Гц
constexpr double kDt = Game::kTickMs / 1000.0;
constexpr double kBaseHalf = 0.45;
} // namespace
Game::Game(Room &room, std::function<void()> onFinished) : onFinished_(std::move(onFinished)) {
buildMap();
Game::Game(Room &room, std::function<void()> onFinished)
: mode_(room.mode), onFinished_(std::move(onFinished)) {
if (mode_ == "coop") {
buildCoopMap();
} else {
buildPvpMap();
}
for (int i = 0; i < 2; i++) {
Tank &t = tanks_[i];
t.player_id = room.players[i].player_id;
for (size_t i = 0; i < room.players.size(); i++) {
Tank t;
t.id = room.players[i].player_id;
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.y = kMapHeight - 2.5;
t.dir = Dir::Up;
@@ -31,6 +43,7 @@ Game::Game(Room &room, std::function<void()> onFinished) : onFinished_(std::move
t.y = 1.5;
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));
for (int y = 0; y < kMapHeight; y++) {
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) {
for (int dy = 0; dy < h; dy++) {
for (int dx = 0; dx < w; dx++) {
@@ -66,6 +78,46 @@ void Game::buildMap() {
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() {
timer_ = us_create_timer((us_loop_t *)uWS::Loop::get(), 0, sizeof(Game *));
*(Game **)us_timer_ext(timer_) = this;
@@ -80,7 +132,7 @@ void Game::start() {
void Game::handleInput(const std::string &player_id, const json &payload) {
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.down = payload.value("down", false);
t.left = payload.value("left", false);
@@ -125,6 +177,13 @@ bool Game::rectHitsTank(double x, double y, const Tank &self) const {
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) {
if (!tank.alive) {
return;
@@ -161,7 +220,7 @@ void Game::applyInput(Tank &tank) {
case Dir::Left: 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.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) {
if (tank.fire_cooldown > 0) {
return;
}
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) {
return;
}
Bullet b;
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;
double offset = kTankHalf + kBulletHalf + 0.01;
b.x = tank.x;
@@ -211,7 +331,6 @@ void Game::updateBullets() {
}
}
// Пуля против пули: встречные уничтожают друг друга.
std::vector<bool> dead(bullets_.size(), false);
for (size_t i = 0; i < bullets_.size(); i++) {
if (dead[i]) continue;
@@ -224,8 +343,7 @@ void Game::updateBullets() {
}
}
int loserIndex = -1;
bool anyoneHit = false;
int pvpLoserIndex = -1;
for (size_t i = 0; i < bullets_.size(); i++) {
if (dead[i]) continue;
@@ -246,21 +364,41 @@ void Game::updateBullets() {
dead[i] = true;
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];
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) {
dead[i] = true;
t.lives--;
anyoneHit = true;
if (t.lives <= 0) {
t.alive = false;
loserIndex = ti;
if (mode_ == "pvp") {
pvpLoserIndex = (int)ti;
}
} else {
// респаун на стартовой позиции
t.x = (ti == 0) ? 1.5 : kMapWidth - 2.5;
t.y = (ti == 0) ? kMapHeight - 2.5 : 1.5;
if (mode_ == "coop") {
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;
}
@@ -273,9 +411,29 @@ void Game::updateBullets() {
}
bullets_ = std::move(alive);
(void)anyoneHit;
if (loserIndex != -1) {
endGame(1 - loserIndex);
if (mode_ == "pvp" && pvpLoserIndex != -1) {
endGamePvp(1 - pvpLoserIndex);
}
}
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_++;
for (auto &t : tanks_) {
if (!t.alive) continue;
if (t.is_ai) {
updateAi(t);
}
double beforeX = t.x, beforeY = t.y;
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();
checkCoopEndConditions();
if (!finished_) {
broadcastState();
@@ -307,12 +480,13 @@ json Game::dirToJson(Dir d) {
json Game::serializeTank(const Tank &t) const {
return {
{"id", t.player_id},
{"id", t.id},
{"x", t.x},
{"y", t.y},
{"direction", dirToJson(t.dir)},
{"lives", t.lives},
{"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) {
if (!ws) {
return;
}
json msg = {{"type", type}, {"payload", std::move(payload)}};
ws->send(msg.dump(), uWS::OpCode::TEXT);
}
@@ -338,8 +515,13 @@ void Game::broadcastState() {
for (const auto &b : bullets_) bullets.push_back(serializeBullet(b));
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_) {
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();
for (const auto &t : tanks_) {
players.push_back({{"id", t.player_id}});
players.push_back({{"id", t.id}});
}
return {
json payload = {
{"map", mapJson},
{"mode", mode},
{"players", players},
{"tick_rate", 1000 / kTickMs},
};
if (base_) {
payload["base"] = {{"x", base_->x}, {"y", base_->y}};
}
return payload;
}
void Game::handleDisconnect(WS *ws) {
if (finished_) {
return;
}
for (int i = 0; i < 2; i++) {
if (tanks_[i].ws == ws) {
int winnerIndex = 1 - i;
finished_ = true;
if (timer_) {
us_timer_close(timer_);
timer_ = nullptr;
if (mode_ == "pvp") {
for (size_t i = 0; i < tanks_.size(); i++) {
if (tanks_[i].ws == ws) {
int winnerIndex = 1 - (int)i;
finished_ = true;
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;
if (timer_) {
us_timer_close(timer_);
timer_ = nullptr;
}
for (int i = 0; i < 2; i++) {
std::string result = (winnerIndex == -1) ? "draw" : (i == winnerIndex ? "win" : "lose");
for (size_t i = 0; i < tanks_.size(); i++) {
std::string result = (winnerIndex == -1) ? "draw" : ((int)i == winnerIndex ? "win" : "lose");
std::string reason = (winnerIndex == -1) ? "оба танка уничтожены одновременно"
: (i == winnerIndex) ? "противник уничтожен"
: "танк уничтожен";
: ((int)i == winnerIndex) ? "противник уничтожен"
: "танк уничтожен";
sendTo(tanks_[i].ws, "game.over", {{"result", result}, {"reason", reason}});
}
@@ -400,3 +604,21 @@ void Game::endGame(int winnerIndex) {
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 <array>
#include <functional>
#include <optional>
#include <string>
#include <vector>
struct us_timer_t;
// Authoritative-игра для одной комнаты в режиме pvp (этап 4 из TZ.md).
// Coop с AI — этап 5, наследует эту же тик-логику.
// Authoritative-игра для одной комнаты: pvp (этап 4) и coop с AI (этап 5).
class Game {
public:
static constexpr int kTickMs = 50; // 20 Гц
static constexpr int kMapWidth = 15;
static constexpr int kMapHeight = 15;
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 class Dir { Up, Right, Down, Left };
struct Tank {
std::string player_id;
WS *ws;
std::string id; // player_id для людей, "ai-N" для AI
WS *ws = nullptr; // nullptr для AI
bool is_ai = false;
double x, y;
Dir dir = Dir::Up;
int lives = kStartLives;
int fire_cooldown = 0;
bool up = false, down = false, left = false, right = false, fire = false;
bool alive = true;
// состояние простого AI (используется только если is_ai)
Dir ai_dir = Dir::Down;
int ai_redecide_ticks = 0;
};
struct Bullet {
int id;
std::string owner_id;
bool owner_is_ai;
double x, y;
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();
void start();
void handleInput(const std::string &player_id, const json &payload);
// Технический проигрыш отключившегося второй игрок побеждает.
// pvp: технический проигрыш отключившегося, второй побеждает.
// coop: игрок выбывает; если людей не осталось — поражение.
void handleDisconnect(WS *ws);
json buildStartPayload(const std::string &mode) const;
private:
std::string mode_;
std::vector<std::vector<int>> map_;
std::array<Tank, 2> tanks_;
std::vector<Tank> tanks_; // сначала люди, затем (в coop) появляющиеся AI
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_enemy_id_ = 1;
int tick_count_ = 0;
bool finished_ = false;
us_timer_t *timer_ = nullptr;
std::function<void()> onFinished_;
void buildMap();
void buildPvpMap();
void buildCoopMap();
void tick();
void applyInput(Tank &tank);
void updateAi(Tank &tank);
void spawnEnemiesIfNeeded();
void updateBullets();
bool tileSolid(int tx, int ty) const;
bool rectHitsSolid(double x, double y) 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 endGame(int winnerIndex); // -1 = ничья
void endGamePvp(int winnerIndex); // -1 = ничья
void endGameCoop(bool win, const std::string &reason);
void checkCoopEndConditions();
void broadcastState();
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;
}
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;
}
bool allReady = std::all_of(room.players.begin(), room.players.end(),