<!-- Основное Игровое Поле и Мини-Карта -->
<div id="mainGame">
<canvas id="gameCanvas" width="1200" height="800"></canvas>
<!-- Мини-Карта -->
<canvas id="miniMap" width="200" height="200"></canvas>
</div>
<!-- Нижняя Панель с Улучшениями и Технологиями -->
<div id="bottomPanel">
<div class="controls">
<button id="upgradeCastle">Улучшить Замок (Стоимость: 100 золота)</button>
<button id="buildBarracks">Построить Казарму (Стоимость: 150 дерева, 100 железа)</button>
<button id="upgradeTroops">Улучшить войска (Стоимость: 100 золота)</button>
<button id="saveGame">Сохранить игру</button>
<button id="loadGame">Загрузить игру</button>
</div>
<div class="technologies">
<h3>Технологии</h3>
<ul>
<li>
<span>Лесопилка (+5 Дерева/сек)</span>
<button id="upgradeWood">Улучшить (50 Дерева)</button>
</li>
<li>
<span>Железная Шахта (+5 Железа/сек)</span>
<button id="upgradeIron">Улучшить (50 Железа)</button>
</li>
<li>
<span>Ферма (+5 Еды/сек)</span>
<button id="upgradeFood">Улучшить (50 Еды)</button>
</li>
<li>
<span>Медная Шахта (+5 Меди/сек)</span>
<button id="upgradeCopper">Улучшить (50 Меди)</button>
</li>
<li>
<span>Золотая Шахта (+5 Золота/сек)</span>
<button id="upgradeGold">Улучшить (50 Золота)</button>
</li>
</ul>
</div>
</div>
<!-- Лог Событий -->
<div id="log">
<h3>Лог Событий</h3>
<ul id="logList"></ul>
</div>
<!-- Контекстное Меню -->
<div id="contextMenu">
<ul id="contextMenuList">
<!-- Пункты меню будут добавляться динамически через JS -->
</ul>
</div>
<!-- Модальное Окно для Покупки Войск -->
<div id="troopModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Разместить Войска</h2>
<label for="troopAmount">Количество войск:</label>
<input type="number" id="troopAmount" min="1" value="1">
<button id="buyTroops">Отправить Войска</button>
</div>
</div>
<!-- Всплывающая Подсказка -->
<div class="tooltip" id="tooltip"></div>
<!-- Модальное Окно для Окончания Игры -->
<div id="gameOverModal">
<div id="gameOverContent">
<h2 id="gameOverTitle">Игра окончена</h2>
<p id="gameOverMessage">Вы проиграли.</p>
<button id="restartGame">Начать заново</button>
</div>
</div>
</div>
<!-- Подключение игрового скрипта -->
<script>
// game.js
// Начальные ресурсы, одинаковые для игрока и бота
const INITIAL_RESOURCES = {
wood: 500,
iron: 300,
food: 200,
copper: 100,
gold: 500
};
class ResourceManager {
constructor(ui) {
this.resources = { ...INITIAL_RESOURCES }; // Копируем начальные ресурсы
this.ui = ui;
}
add(resource, amount) {
if (this.resources.hasOwnProperty(resource)) {
this.resources[resource] += amount;
if (this.ui) {
this.ui.updateResource(resource, this.resources[resource]);
}
}
}
subtract(resource, amount) {
if (this.resources.hasOwnProperty(resource) && this.resources[resource] >= amount) {
this.resources[resource] -= amount;
if (this.ui) {
this.ui.updateResource(resource, this.resources[resource]);
}
return true;
}
return false;
}
get(resource) {
return this.resources[resource] || 0;
}
getAll() {
return { ...this.resources };
}
setAll(newResources) {
this.resources = { ...newResources };
if (this.ui) {
this.ui.updateAllResources(this.resources);
}
}
}
class Hex {
constructor(row, col, x, y, size) {
this.row = row;
this.col = col;
this.x = x;
this.y = y;
this.size = size;
this.owned = false;
this.captured = false;
this.isCastle = false;
this.hasFort = false;
this.resources = this.generateRandomResources();
this.troops = 0; // Количество войск на гексе
this.owner = null; // "player" или "bot"
this.buildings = []; // Здания на гексе
this.isUnderAttack = false; // Флаг, обозначающий, что на гексе идёт битва
this.isDestination = false; // Флаг, обозначающий, что армия движется к гексу
this.movementTimer = null; // Таймер движения армии
this.captureTimer = null; // Таймер захвата гекса
this.movementTimeRemaining = 0;
this.captureTimeRemaining = 0;
}
generateRandomResources() {
// Генерация рандомных значений для ресурсов
return {
wood: (Math.random() * 5 + 1).toFixed(1), // 1.0 - 6.0
iron: (Math.random() * 5 + 1).toFixed(1),
food: (Math.random() * 5 + 1).toFixed(1),
copper: (Math.random() * 5 + 1).toFixed(1),
gold: (Math.random() * 5 + 1).toFixed(1)
};
}
startMovementTimer(time) {
this.movementTimeRemaining = time;
this.isDestination = true;
this.movementTimer = setInterval(() => {
this.movementTimeRemaining -= 1000;
if (this.movementTimeRemaining <= 0) {
clearInterval(this.movementTimer);
this.movementTimer = null;
this.isDestination = false;
}
}, 1000);
}
startCaptureTimer(time) {
this.captureTimeRemaining = time;
this.isUnderAttack = true;
this.captureTimer = setInterval(() => {
this.captureTimeRemaining -= 1000;
if (this.captureTimeRemaining <= 0) {
clearInterval(this.captureTimer);
this.captureTimer = null;
this.isUnderAttack = false;
}
}, 1000);
}
draw(ctx) {
const HEX_SIZE = this.size;
const angle = Math.PI / 3;
ctx.beginPath();
for (let i = 0; i < 6; i++) {
ctx.lineTo(
this.x + HEX_SIZE * Math.cos(angle * i),
this.y + HEX_SIZE * Math.sin(angle * i)
);
}
ctx.closePath();
// Устанавливаем цвет в зависимости от владельца
if (this.owner === 'player') {
if (this.isCastle) {
ctx.fillStyle = '#e74c3c'; // Красный для замка игрока
} else if (this.hasFort) {
ctx.fillStyle = '#f1c40f'; // Желтый для форта игрока
} else {
ctx.fillStyle = '#2ecc71'; // Зеленый для гексов игрока
}
} else if (this.owner === 'bot') {
if (this.isCastle) {
ctx.fillStyle = '#8e44ad'; // Фиолетовый для замка бота
} else if (this.hasFort) {
ctx.fillStyle = '#3498db'; // Синий для форта бота
} else {
ctx.fillStyle = '#1abc9c'; // Бирюзовый для гексов бота
}
} else {
ctx.fillStyle = '#ecf0f1'; // Белый для свободных гексов
}
ctx.fill();
ctx.strokeStyle = '#95a5a6';
ctx.stroke();
// Рисуем количество войск, если есть и нет активного таймера
if (this.troops > 0 && !this.isDestination && !this.isUnderAttack) {
ctx.fillStyle = '#fff';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(this.troops, this.x, this.y + 4);
}
// Отображение таймеров
if (this.movementTimer) {
// Отображаем зеленый таймер
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.beginPath();
ctx.arc(this.x, this.y, HEX_SIZE / 2, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#000';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(Math.ceil(this.movementTimeRemaining / 1000), this.x, this.y + 4);
}
if (this.captureTimer) {
// Отображаем красный таймер
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.beginPath();
ctx.arc(this.x, this.y, HEX_SIZE / 2, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#000';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(Math.ceil(this.captureTimeRemaining / 1000), this.x, this.y + 4);
}
// Если идёт битва, рисуем индикатор
if (this.isUnderAttack && !this.captureTimer) {
ctx.beginPath();
ctx.arc(this.x, this.y, HEX_SIZE / 2, 0, 2 * Math.PI);
ctx.strokeStyle = '#ff0000';
ctx.lineWidth = 3;
ctx.stroke();
ctx.lineWidth = 1;
}
}
isClicked(clickX, clickY) {
const dx = clickX - this.x;
const dy = clickY - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
return distance <= this.size;
}
}
class Castle {
constructor(hex, ui, owner) {
this.hex = hex;
this.hex.isCastle = true;
this.hex.owner = owner;
this.level = 1;
this.population = 1;
this.goldIncome = 10;
this.ui = ui;
this.barracks = 0; // Количество казарм
this.castleHealth = 500; // Начальное здоровье замка
this.owner = owner; // "player" или "bot"
this.troopLevel = 1; // Уровень войск
this.isDestroyed = false;
}
upgrade(resourceManager) {
const upgradeCost = 100 * this.level;
if (resourceManager.subtract('gold', upgradeCost)) {
this.level += 1;
this.population += 2;
this.goldIncome += 10;
if (this.owner === 'player') {
this.ui.updateCastle(this.level, this.population);
this.ui.logEvent(`Замок улучшен до уровня ${this.level}. Жители: ${this.population}, доход золота: ${this.goldIncome}`);
}
} else {
if (this.owner === 'player') {
this.ui.displayAlert('Недостаточно золота для улучшения замка!');
}
}
}
buildBarracks(resourceManager) {
const costWood = 150;
const costIron = 100;
if (resourceManager.subtract('wood', costWood) && resourceManager.subtract('iron', costIron)) {
this.barracks += 1;
if (this.owner === 'player') {
this.ui.logEvent(`Казарма построена. Всего казарм: ${this.barracks}`);
}
} else {
if (this.owner === 'player') {
this.ui.displayAlert('Недостаточно ресурсов для строительства казармы!');
}
}
}
upgradeTroops(resourceManager) {
const upgradeCost = 100 * this.troopLevel;
if (resourceManager.subtract('gold', upgradeCost)) {
this.troopLevel += 1;
if (this.owner === 'player') {
this.ui.logEvent(`Войска улучшены до уровня ${this.troopLevel}.`);
}
} else {
if (this.owner === 'player') {
this.ui.displayAlert('Недостаточно золота для улучшения войск!');
}
}
}
collectResources(resourceManager) {
resourceManager.add('gold', this.goldIncome);
if (this.owner === 'player') {
this.ui.updateResource('gold', resourceManager.get('gold'));
}
}
loseHealth(amount) {
this.castleHealth -= amount;
if (this.castleHealth <= 0 && !this.isDestroyed) {
this.isDestroyed = true;
this.hex.owned = false;
this.hex.owner = null;
if (this.owner === 'player') {
this.ui.showGameOver('Вы проиграли. Замок уничтожен.');
} else {
this.ui.logEvent('Вы победили! Замок противника разрушен.');
this.ui.showGameOver('Вы выиграли!');
}
}
}
}
class Building {
constructor(name, resource, increment, costResource, costAmount, ui) {
this.name = name;
this.resource = resource;
this.increment = increment;
this.costResource = costResource;
this.costAmount = costAmount;
this.level = 1;
this.ui = ui;
}
upgrade(resourceManager) {
const totalCost = this.costAmount * this.level;
if (resourceManager.subtract(this.costResource, totalCost)) {
this.level += 1;
this.increment += 5;
if (this.ui) {
this.ui.logEvent(`${this.name} улучшена до уровня ${this.level}. Производство: ${this.increment} ${this.resource}/сек`);
}
} else {
if (this.ui) {
this.ui.displayAlert(`Недостаточно ${this.costResource} для улучшения ${this.name}!`);
}
}
}
}
class UIManager {
constructor(game) {
this.game = game;
this.resourcesElements = {
wood: document.getElementById('wood'),
iron: document.getElementById('iron'),
food: document.getElementById('food'),
copper: document.getElementById('copper'),
gold: document.getElementById('gold')
};
this.populationElement = document.getElementById('population');
this.castleLevelElement = document.getElementById('castleLevel');
this.logList = document.getElementById('logList');
this.tooltip = document.getElementById('tooltip');
this.contextMenu = document.getElementById('contextMenu');
this.contextMenuList = document.getElementById('contextMenuList');
this.troopModal = document.getElementById('troopModal');
this.closeModal = document.querySelector('.close');
this.buyTroopsButton = document.getElementById('buyTroops');
this.gameOverModal = document.getElementById('gameOverModal');
this.gameOverTitle = document.getElementById('gameOverTitle');
this.gameOverMessage = document.getElementById('gameOverMessage');
this.restartGameButton = document.getElementById('restartGame');
// Закрыть модальное окно при клике на крестик
this.closeModal.onclick = () => {
this.hideTroopModal();
};
// Закрыть модальное окно при клике вне его
window.onclick = (event) => {
if (event.target == this.troopModal) {
this.hideTroopModal();
}
};
// Обработчик кнопки перезапуска игры
this.restartGameButton.onclick = () => {
location.reload();
};
}
updateResource(resource, value) {
if (this.resourcesElements[resource]) {
this.resourcesElements[resource].innerText = `${this.capitalize(resource)}: ${Math.floor(value)}`;
}
}
updateAllResources(resources) {
for (const [key, value] of Object.entries(resources)) {
this.updateResource(key, value);
}
}
updatePopulation(population) {
this.populationElement.innerText = `Жители: ${population}`;
}
updateCastle(level, population) {
this.castleLevelElement.innerText = `Уровень Замка: ${level}`;
this.updatePopulation(population);
}
logEvent(message) {
const li = document.createElement('li');
li.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
this.logList.prepend(li);
}
displayAlert(message) {
alert(message);
}
showContextMenu(options, x, y) {
// Очистить текущее содержание меню
this.contextMenuList.innerHTML = '';
// Добавить новые опции
options.forEach(option => {
const li = document.createElement('li');
li.id = option.id;
li.textContent = option.label;
this.contextMenuList.appendChild(li);
});
// Позиционировать и отображать меню
this.contextMenu.style.left = `${x}px`;
this.contextMenu.style.top = `${y}px`;
this.contextMenu.style.display = 'block';
}
hideContextMenu() {
this.contextMenu.style.display = 'none';
}
showTooltip(content, x, y) {
this.tooltip.innerHTML = content;
this.tooltip.style.left = `${x + 10}px`;
this.tooltip.style.top = `${y + 10}px`;
this.tooltip.style.display = 'block';
}
hideTooltip() {
this.tooltip.style.display = 'none';
}
showTroopModal() {
this.troopModal.style.display = 'block';
}
hideTroopModal() {
this.troopModal.style.display = 'none';
}
showGameOver(message) {
this.gameOverMessage.innerText = message;
this.gameOverModal.style.display = 'block';
}
capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
}
class MiniMap {
constructor(mainCanvas, miniCanvas, grid) {
this.mainCanvas = mainCanvas;
this.miniCanvas = miniCanvas;
this.ctx = miniCanvas.getContext('2d');
this.grid = grid;
// Расчет масштаба для 50x50 карты, предполагая размер каждого гекса 40px
this.scale = this.miniCanvas.width / (50 * Math.sqrt(3) * 40); // Пропорция для 50x50 карты
this.draw();
}
draw() {
this.ctx.clearRect(0, 0, this.miniCanvas.width, this.miniCanvas.height);
for (const hex of this.grid) {
if (hex.owned) {
if (hex.owner === 'player') {
this.ctx.fillStyle = hex.isCastle ? '#e74c3c' : (hex.hasFort ? '#f1c40f' : '#2ecc71');
} else if (hex.owner === 'bot') {
this.ctx.fillStyle = hex.isCastle ? '#8e44ad' : (hex.hasFort ? '#3498db' : '#1abc9c');
}
// Пропустить гексы вне 50x50
if (hex.row >= 50 || hex.col >= 50) continue;
const x = hex.col * (this.miniCanvas.width / 50) + (hex.row % 2) * (this.miniCanvas.width / 100);
const y = hex.row * (this.miniCanvas.height / 50) * 0.75 + 10; // Добавлен отступ сверху
this.ctx.beginPath();
const size = (this.miniCanvas.width / 50) / 2;
const angle = Math.PI / 3;
for (let i = 0; i < 6; i++) {
this.ctx.lineTo(
x + size * Math.cos(angle * i),
y + size * Math.sin(angle * i)
);
}
this.ctx.closePath();
this.ctx.fill();
this.ctx.strokeStyle = '#ffffff';
this.ctx.stroke();
}
}
}
}
class ModalManager {
constructor(ui, game) {
this.ui = ui;
this.game = game;
this.buyTroopsButton = document.getElementById('buyTroops');
this.troopAmountInput = document.getElementById('troopAmount');
this.buyTroopsButton.addEventListener('click', () => {
this.buyTroops();
});
}
buyTroops() {
const amount = parseInt(this.troopAmountInput.value);
if (isNaN(amount) || amount < 1) {
this.ui.displayAlert('Пожалуйста, введите корректное количество войск.');
return;
}
const troopCost = 10 * amount; // Стоимость 10 еды за каждое войско
if (this.game.resourceManager.subtract('food', troopCost)) {
// Армия движется от замка до целевого гекса
const distance = this.game.calculateDistance(this.game.castle.hex, this.game.selectedHex);
const travelTime = distance * 5 * 1000; // 5 секунд за каждый гекс
this.ui.logEvent(`Войска (${amount} ед.) отправлены к гексу (${this.game.selectedHex.row}, ${this.game.selectedHex.col}). Время в пути: ${travelTime / 1000} сек.`);
// Запускаем таймер движения на гексе
this.game.selectedHex.startMovementTimer(travelTime);
setTimeout(() => {
this.game.selectedHex.troops += amount;
this.ui.logEvent(`Подкрепление (${amount} ед.) прибыло на гекс (${this.game.selectedHex.row}, ${this.game.selectedHex.col}). Общие войска: ${this.game.selectedHex.troops}`);
// Останавливаем таймер движения
this.game.selectedHex.movementTimer = null;
this.game.selectedHex.movementTimeRemaining = 0;
this.game.selectedHex.isDestination = false;
}, travelTime);
this.ui.hideTroopModal();
} else {
this.ui.displayAlert('Недостаточно еды для покупки войск!');
}
}
}
class AIPlayer {
constructor(game, ui) {
this.game = game;
this.ui = ui;
this.resourceManager = new ResourceManager(null); // UI не нужен для бота
this.hexes = []; // Гексы, принадлежащие боту
this.castle = null;
this.buildings = [];
this.setup();
}
setup() {
this.placeStartingCastle();
this.initBuildings();
this.startResourceGeneration();
this.takeActions();
}
placeStartingCastle() {
const availableHexes = this.game.grid.filter(hex => !hex.owned);
const randomHex = availableHexes[Math.floor(Math.random() * availableHexes.length)];
randomHex.owned = true;
randomHex.owner = 'bot';
this.castle = new Castle(randomHex, null, 'bot');
this.hexes.push(randomHex);
this.resourceManager.add('gold', this.castle.goldIncome);
this.game.ui.logEvent(`Бот разместил замок на гексе (${randomHex.row}, ${randomHex.col}).`);
}
initBuildings() {
this.buildings.push(new Building('Лесопилка', 'wood', 5, 'wood', 50, null));
this.buildings.push(new Building('Железная Шахта', 'iron', 5, 'iron', 50, null));
this.buildings.push(new Building('Ферма', 'food', 5, 'food', 50, null));
this.buildings.push(new Building('Медная Шахта', 'copper', 5, 'copper', 50, null));
this.buildings.push(new Building('Золотая Шахта', 'gold', 5, 'gold', 50, null));
}
startResourceGeneration() {
// Генерация ресурсов каждые 1 секунду
setInterval(() => {
for (const building of this.buildings) {
this.resourceManager.add(building.resource, building.increment);
}
this.castle.collectResources(this.resourceManager);
}, 1000);
// Рост населения каждые 10 секунд
setInterval(() => {
const newResidents = this.castle.level;
this.castle.population += newResidents;
}, 10000);
}
takeActions() {
// Бот принимает решения каждые 5 секунд
setInterval(() => {
if (!this.castle.isDestroyed) {
this.considerUpgrades();
this.considerExpansion();
this.considerAttack();
}
}, 5000);
}
considerUpgrades() {
// Решение об улучшении войск
if (this.resourceManager.get('gold') >= 100 * this.castle.troopLevel) {
this.castle.upgradeTroops(this.resourceManager);
}
// Решение об улучшении замка
if (this.resourceManager.get('gold') >= 100 * this.castle.level) {
this.castle.upgrade(this.resourceManager);
}
// Решение об улучшении зданий
for (const building of this.buildings) {
const totalCost = building.costAmount * building.level;
if (this.resourceManager.get(building.costResource) >= totalCost * 1.5) {
building.upgrade(this.resourceManager);
}
}
}
considerExpansion() {
// Бот ищет гексы для захвата
const possibleHexes = [];
for (const hex of this.hexes) {
const neighbors = this.game.getNeighbors(hex);
for (const neighbor of neighbors) {
if (!neighbor.owned) {
possibleHexes.push(neighbor);
}
}
}
// Сортируем по количеству ресурсов
possibleHexes.sort((a, b) => {
const aResources = Object.values(a.resources).reduce((sum, val) => sum + parseFloat(val), 0);
const bResources = Object.values(b.resources).reduce((sum, val) => sum + parseFloat(val), 0);
return bResources - aResources;
});
// Пытаемся захватить лучший гекс
const captureCost = {
wood: 50,
iron: 30,
gold: 20
};
if (possibleHexes.length > 0) {
const hexToCapture = possibleHexes[0];
const canCapture = Object.keys(captureCost).every(resource => this.resourceManager.get(resource) >= captureCost[resource]);
if (canCapture) {
// Вычесть ресурсы
Object.keys(captureCost).forEach(resource => {
this.resourceManager.subtract(resource, captureCost[resource]);
});
hexToCapture.owned = true;
hexToCapture.owner = 'bot';
this.hexes.push(hexToCapture);
this.game.ui.logEvent(`Бот захватил гекс на (${hexToCapture.row}, ${hexToCapture.col}).`);
// Строим форт с вероятностью 70%
if (Math.random() < 0.7) {
this.buildFort(hexToCapture);
}
} else {
// Недостаточно ресурсов для захвата
// Можно добавить логику ожидания до накопления ресурсов
}
}
}
buildFort(hex) {
const costWood = 50;
const costIron = 25;
if (this.resourceManager.get('wood') >= costWood && this.resourceManager.get('iron') >= costIron) {
this.resourceManager.subtract('wood', costWood);
this.resourceManager.subtract('iron', costIron);
hex.hasFort = true;
// Размещаем войска
hex.troops = Math.floor(this.castle.level * 5 * this.castle.troopLevel);
this.game.ui.logEvent(`Бот построил форт и разместил войска на гексе (${hex.row}, ${hex.col}).`);
} else {
// Недостаточно ресурсов для строительства форта
// Можно добавить логику ожидания до накопления ресурсов
}
}
considerAttack() {
// Бот ищет соседние гексы игрока для атаки
for (const hex of this.hexes) {
const neighbors = this.game.getNeighbors(hex);
for (const neighbor of neighbors) {
if (neighbor.owner === 'player') {
// Проверяем наличие войск на нашем гексе
if (hex.troops > 0 && !neighbor.isUnderAttack) {
this.attackHex(hex, neighbor);
}
}
}
}
}
attackHex(fromHex, toHex) {
// Проверяем, нет ли уже таймера захвата на гексе
if (toHex.captureTimer) {
this.game.ui.logEvent(`Гекс (${toHex.row}, ${toHex.col}) уже находится под атакой.`);
return;
}
// Определяем время захвата
let captureTime;
if (!toHex.hasFort && toHex.troops === 0) {
// Без форта и армии — 10 секунд
captureTime = 10000;
} else if (toHex.hasFort) {
// С фортом — 45 секунд
captureTime = 45000;
} else {
// Иначе — стандартное время битвы
captureTime = 5000 * Math.ceil(Math.max(fromHex.troops, toHex.troops) / 10);
}
toHex.isUnderAttack = true;
toHex.startCaptureTimer(captureTime);
this.game.ui.logEvent(`Бот начал атаку на гекс (${toHex.row}, ${toHex.col}). Захват займет ${captureTime / 1000} секунд.`);
// Запускаем таймер захвата
setTimeout(() => {
// По завершении таймера гекс захватывается ботом
toHex.owner = 'bot';
toHex.owned = true;
toHex.troops = fromHex.troops; // Перемещаем войска на новый гекс
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.hexes.push(toHex);
this.game.ui.logEvent(`Бот захватил гекс на (${toHex.row}, ${toHex.col}).`);
// Проверяем, не был ли уничтожен замок игрока
if (toHex.isCastle) {
this.game.castle.loseHealth(1000); // Уничтожаем замок
}
}, captureTime);
}
}
class Game {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.ui = new UIManager(this);
this.resourceManager = new ResourceManager(this.ui);
this.hexSize = 40;
this.grid = [];
this.castle = null;
this.buildings = [];
this.selectedHex = null; // Для контекстного меню
this.tooltipHex = null; // Для подсказок
this.miniMapInstance = null;
this.panOffset = { x: 0, y: 0 };
this.viewport = { scale: 1 };
this.isPanning = false;
this.startPan = { x: 0, y: 0 };
this.modalManager = null;
this.aiPlayer = null; // Добавляем бота
this.setup();
}
setup() {
this.createGrid(50, 50); // 50x50 карта
this.placeStartingCastle();
this.initBuildings();
this.setupUIControls();
this.setupContextMenuHandlers();
this.mouseEvents();
this.initModalManager();
this.startResourceGeneration();
this.initMiniMap();
this.initAIPlayer(); // Инициализируем бота
this.gameLoop();
}
createGrid(rows, cols) {
const HEX_SIZE = this.hexSize;
const HEX_WIDTH = Math.sqrt(3) * HEX_SIZE;
const HEX_HEIGHT = 2 * HEX_SIZE;
const HEX_HORZ_SPACING = HEX_WIDTH;
const HEX_VERT_SPACING = 1.5 * HEX_SIZE;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
let x = HEX_WIDTH * col + (row % 2) * (HEX_WIDTH / 2);
let y = HEX_HEIGHT * 0.75 * row + HEX_SIZE;
this.grid.push(new Hex(row, col, x, y, HEX_SIZE));
}
}
}
placeStartingCastle() {
const availableHexes = this.grid.filter(hex => !hex.owned);
const randomHex = availableHexes[Math.floor(Math.random() * availableHexes.length)];
randomHex.owned = true;
randomHex.owner = 'player';
this.castle = new Castle(randomHex, this.ui, 'player');
this.resourceManager.add('gold', this.castle.goldIncome);
this.ui.logEvent(`Замок размещен на гексе (${randomHex.row}, ${randomHex.col}).`);
}
initBuildings() {
this.buildings.push(new Building('Лесопилка', 'wood', 5, 'wood', 50, this.ui));
this.buildings.push(new Building('Железная Шахта', 'iron', 5, 'iron', 50, this.ui));
this.buildings.push(new Building('Ферма', 'food', 5, 'food', 50, this.ui));
this.buildings.push(new Building('Медная Шахта', 'copper', 5, 'copper', 50, this.ui));
this.buildings.push(new Building('Золотая Шахта', 'gold', 5, 'gold', 50, this.ui));
}
setupUIControls() {
// Кнопки улучшения замка
document.getElementById('upgradeCastle').addEventListener('click', () => {
this.castle.upgrade(this.resourceManager);
});
// Кнопки строительства казарм
document.getElementById('buildBarracks').addEventListener('click', () => {
this.castle.buildBarracks(this.resourceManager);
});
// Кнопка улучшения войск
document.getElementById('upgradeTroops').addEventListener('click', () => {
this.castle.upgradeTroops(this.resourceManager);
});
// Кнопки сохранения и загрузки игры
document.getElementById('saveGame').addEventListener('click', () => {
this.saveGame();
});
document.getElementById('loadGame').addEventListener('click', () => {
this.loadGame();
});
// Кнопки улучшения зданий
document.getElementById('upgradeWood').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Лесопилка');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeIron').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Железная Шахта');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeFood').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Ферма');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeCopper').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Медная Шахта');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeGold').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Золотая Шахта');
building.upgrade(this.resourceManager);
});
}
setupContextMenuHandlers() {
// Обработка выбора пунктов контекстного меню
this.ui.contextMenuList.addEventListener('click', (e) => {
if (e.target && e.target.nodeName === 'LI') {
const action = e.target.id;
if (action === 'buildFort') {
if (this.selectedHex) {
this.buildFort(this.selectedHex);
this.ui.hideContextMenu();
}
} else if (action === 'placeTroops') {
if (this.selectedHex) {
this.openTroopModal(this.selectedHex);
this.ui.hideContextMenu();
}
} else if (action === 'upgradeCastleOption') {
this.castle.upgrade(this.resourceManager);
this.ui.hideContextMenu();
} else if (action === 'buildBarracksOption') {
this.castle.buildBarracks(this.resourceManager);
this.ui.hideContextMenu();
} else if (action === 'upgradeTroopsOption') {
this.castle.upgradeTroops(this.resourceManager);
this.ui.hideContextMenu();
}
}
});
}
mouseEvents() {
// Обработка обычного клика для захвата гекса
this.canvas.addEventListener('click', (e) => {
const rect = this.canvas.getBoundingClientRect();
const clickX = (e.clientX - rect.left - this.panOffset.x) / this.viewport.scale;
const clickY = (e.clientY - rect.top - this.panOffset.y) / this.viewport.scale;
const clickedHex = this.getHexAt(clickX, clickY);
if (clickedHex && !clickedHex.owned && !clickedHex.isCastle) {
// Захват территории требует затрат ресурсов
const captureCost = {
wood: 50,
iron: 30,
gold: 20
};
const canCapture = Object.keys(captureCost).every(resource => this.resourceManager.get(resource) >= captureCost[resource]);
if (canCapture && this.isAdjacentToOwnedHex(clickedHex, 'player')) {
// Вычесть ресурсы
Object.keys(captureCost).forEach(resource => {
this.resourceManager.subtract(resource, captureCost[resource]);
});
// Запускаем таймер захвата
let captureTime = clickedHex.hasFort ? 45000 : 10000;
if (clickedHex.captureTimer) {
this.ui.logEvent(`Гекс (${clickedHex.row}, ${clickedHex.col}) уже находится под атакой.`);
return;
}
clickedHex.isUnderAttack = true;
clickedHex.startCaptureTimer(captureTime);
this.ui.logEvent(`Вы начали захват гекса (${clickedHex.row}, ${clickedHex.col}). Захват займет ${captureTime / 1000} секунд.`);
setTimeout(() => {
clickedHex.owner = 'player';
clickedHex.owned = true;
clickedHex.isUnderAttack = false;
clickedHex.captureTimer = null;
clickedHex.captureTimeRemaining = 0;
this.ui.logEvent(`Вы захватили гекс на (${clickedHex.row}, ${clickedHex.col}).`);
}, captureTime);
} else if (!this.isAdjacentToOwnedHex(clickedHex, 'player')) {
this.ui.logEvent('Вы можете захватить только соседние гексы!');
} else {
this.ui.logEvent('Недостаточно ресурсов для захвата территории!');
}
} else if (clickedHex && clickedHex.owner === 'bot') {
// Атакуем гекс бота
const fromHex = this.getPlayerHexWithTroopsNearby(clickedHex);
if (fromHex) {
this.attackHex(fromHex, clickedHex);
} else {
this.ui.logEvent('Нет войск рядом для атаки!');
}
}
});
// Обработка правого клика для контекстного меню
this.canvas.addEventListener('contextmenu', (e) => {
e.preventDefault();
const rect = this.canvas.getBoundingClientRect();
const clickX = (e.clientX - rect.left - this.panOffset.x) / this.viewport.scale;
const clickY = (e.clientY - rect.top - this.panOffset.y) / this.viewport.scale;
const clickedHex = this.getHexAt(clickX, clickY);
if (clickedHex && clickedHex.owned && clickedHex.owner === 'player') {
this.selectedHex = clickedHex; // Сохранить выбранный гекс
if (clickedHex.isCastle) {
// Если это замок, показать контекстное меню для замка
this.ui.showContextMenu([
{ id: 'upgradeCastleOption', label: 'Улучшить Замок' },
{ id: 'buildBarracksOption', label: 'Построить Казарму' },
{ id: 'upgradeTroopsOption', label: 'Улучшить Войска' }
], e.clientX, e.clientY);
} else {
// Иначе, показать обычное контекстное меню
this.ui.showContextMenu([
{ id: 'buildFort', label: 'Построить Форт' },
{ id: 'placeTroops', label: 'Разместить Войска' }
], e.clientX, e.clientY);
}
}
});
// Обработка наведения курсора для показа подсказок
this.canvas.addEventListener('mousemove', (e) => {
const rect = this.canvas.getBoundingClientRect();
const moveX = (e.clientX - rect.left - this.panOffset.x) / this.viewport.scale;
const moveY = (e.clientY - rect.top - this.panOffset.y) / this.viewport.scale;
const hoveredHex = this.getHexAt(moveX, moveY);
if (hoveredHex) {
const resources = hoveredHex.resources;
let content = `<strong>Ресурсы:</strong><br>`;
content += `Дерево: ${(resources.wood * 10).toFixed(1)} / сек<br>`;
content += `Железо: ${(resources.iron * 10).toFixed(1)} / сек<br>`;
content += `Еда: ${(resources.food * 10).toFixed(1)} / сек<br>`;
content += `Медь: ${(resources.copper * 10).toFixed(1)} / сек<br>`;
content += `Золото: ${(resources.gold * 10).toFixed(1)} / сек<br>`;
if (hoveredHex.hasFort) {
content += `<strong>Форт:</strong> Размещено войск: ${hoveredHex.troops}`;
}
content += `<br><strong>Владелец:</strong> ${hoveredHex.owner === 'player' ? 'Вы' : hoveredHex.owner === 'bot' ? 'Бот' : 'Никто'}`;
this.ui.showTooltip(content, e.clientX, e.clientY);
this.tooltipHex = hoveredHex;
} else {
this.ui.hideTooltip();
this.tooltipHex = null;
}
});
// При уходе курсора с холста скрываем подсказку
this.canvas.addEventListener('mouseleave', () => {
this.ui.hideTooltip();
this.tooltipHex = null;
});
// Обработка перемещения по карте (панорамирование)
this.canvas.addEventListener('mousedown', (e) => {
if (e.button === 1 || (e.button === 0 && e.shiftKey)) { // Средняя кнопка или Shift + Левый
this.isPanning = true;
this.startPan.x = e.clientX;
this.startPan.y = e.clientY;
}
});
document.addEventListener('mouseup', (e) => {
this.isPanning = false;
});
document.addEventListener('mousemove', (e) => {
if (this.isPanning) {
const dx = e.clientX - this.startPan.x;
const dy = e.clientY - this.startPan.y;
this.panOffset.x += dx;
this.panOffset.y += dy;
this.startPan.x = e.clientX;
this.startPan.y = e.clientY;
}
});
// Обработка колесика мыши для масштабирования
this.canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const zoomIntensity = 0.1;
const delta = e.deltaY < 0 ? 1 : -1;
const factor = 1 + delta * zoomIntensity;
this.viewport.scale *= factor;
this.viewport.scale = Math.min(Math.max(this.viewport.scale, 0.5), 2);
});
}
initModalManager() {
this.modalManager = new ModalManager(this.ui, this);
}
openTroopModal(hex) {
if (hex.hasFort) {
this.ui.showTroopModal();
} else {
this.ui.displayAlert('На этом гексе не построен форт!');
}
}
getHexAt(x, y) {
return this.grid.find(hex => hex.isClicked(x, y));
}
isAdjacentToOwnedHex(targetHex, owner) {
const neighbors = this.getNeighbors(targetHex);
return neighbors.some(hex => hex.owner === owner);
}
getNeighbors(hex) {
const directions = [
{ dr: -1, dc: 0 }, { dr: -1, dc: 1 }, { dr: 0, dc: -1 },
{ dr: 0, dc: 1 }, { dr: 1, dc: -1 }, { dr: 1, dc: 0 }
];
const neighbors = [];
for (const dir of directions) {
const neighbor = this.grid.find(h => h.row === hex.row + dir.dr && h.col === hex.col + dir.dc);
if (neighbor) {
neighbors.push(neighbor);
}
}
return neighbors;
}
getPlayerHexWithTroopsNearby(targetHex) {
const neighbors = this.getNeighbors(targetHex);
return neighbors.find(hex => hex.owner === 'player' && hex.troops > 0);
}
captureHex(hex, owner) {
hex.owned = true;
hex.owner = owner;
this.ui.logEvent(`Гекс захвачен на (${hex.row}, ${hex.col}).`);
}
buildFort(hex) {
if (!hex.hasFort) {
const costWood = 50;
const costIron = 25;
if (this.resourceManager.subtract('wood', costWood) && this.resourceManager.subtract('iron', costIron)) {
hex.hasFort = true;
this.ui.logEvent(`Форт построен на гексе (${hex.row}, ${hex.col}).`);
} else {
this.ui.displayAlert('Недостаточно ресурсов для строительства форта!');
}
} else {
this.ui.displayAlert('На этом гексе уже построен форт!');
}
}
placeTroops(hex) {
if (hex.hasFort) {
if (this.castle.barracks > 0) {
this.openTroopModal(hex);
} else {
this.ui.displayAlert('Необходимо построить казармы в замке для размещения войск!');
}
} else {
this.ui.displayAlert('На этом гексе не построен форт!');
}
}
startResourceGeneration() {
// Генерация ресурсов каждые 1 секунду
setInterval(() => {
for (const building of this.buildings) {
this.resourceManager.add(building.resource, building.increment);
}
this.castle.collectResources(this.resourceManager);
}, 1000);
// Рост населения каждые 10 секунд в зависимости от уровня замка
setInterval(() => {
const newResidents = this.castle.level;
this.castle.population += newResidents;
this.ui.updatePopulation(this.castle.population);
this.ui.logEvent(`Население выросло на ${newResidents}. Всего жителей: ${this.castle.population}`);
}, 10000);
}
initMiniMap() {
this.miniMapInstance = new MiniMap(this.canvas, document.getElementById('miniMap'), this.grid);
}
initAIPlayer() {
this.aiPlayer = new AIPlayer(this, this.ui);
}
gameLoop() {
this.ctx.save();
this.ctx.translate(this.panOffset.x, this.panOffset.y);
this.ctx.scale(this.viewport.scale, this.viewport.scale);
this.ctx.clearRect(-this.panOffset.x / this.viewport.scale, -this.panOffset.y / this.viewport.scale, this.canvas.width / this.viewport.scale, this.canvas.height / this.viewport.scale);
this.drawGrid();
this.ctx.restore();
this.drawMiniMap();
// Проверка условий окончания игры
this.checkGameOver();
requestAnimationFrame(() => this.gameLoop());
}
drawGrid() {
for (const hex of this.grid) {
hex.draw(this.ctx);
}
}
drawMiniMap() {
// Обновление мини-карты
if (this.miniMapInstance) {
this.miniMapInstance.draw();
}
}
calculateDistance(hex1, hex2) {
// Простой способ расчёта расстояния между гексами
const dx = hex2.col - hex1.col;
const dy = hex2.row - hex1.row;
return Math.max(Math.abs(dx), Math.abs(dy));
}
saveGame() {
const gameState = {
resources: this.resourceManager.getAll(),
castle: {
level: this.castle.level,
population: this.castle.population,
goldIncome: this.castle.goldIncome,
barracks: this.castle.barracks,
troopLevel: this.castle.troopLevel,
location: {
row: this.castle.hex.row,
col: this.castle.hex.col
},
castleHealth: this.castle.castleHealth
},
buildings: this.buildings.map(b => ({
name: b.name,
level: b.level,
increment: b.increment
})),
grid: this.grid.map(hex => ({
row: hex.row,
col: hex.col,
owned: hex.owned,
owner: hex.owner,
isCastle: hex.isCastle,
hasFort: hex.hasFort,
troops: hex.troops,
resources: hex.resources
}))
};
localStorage.setItem('hexGameSave', JSON.stringify(gameState));
this.ui.logEvent('Игра сохранена.');
}
loadGame() {
const savedState = localStorage.getItem('hexGameSave');
if (savedState) {
const parsedState = JSON.parse(savedState);
this.resourceManager.setAll(parsedState.resources);
// Восстановление замка
const castleLocation = parsedState.castle.location;
const castleHex = this.grid.find(hex => hex.row === castleLocation.row && hex.col === castleLocation.col);
if (castleHex) {
this.castle = new Castle(castleHex, this.ui, 'player');
this.castle.level = parsedState.castle.level;
this.castle.population = parsedState.castle.population;
this.castle.goldIncome = parsedState.castle.goldIncome;
this.castle.barracks = parsedState.castle.barracks;
this.castle.troopLevel = parsedState.castle.troopLevel;
this.castle.castleHealth = parsedState.castle.castleHealth;
this.ui.updateCastle(this.castle.level, this.castle.population);
}
// Восстановление зданий
for (let i = 0; i < this.buildings.length; i++) {
const savedBuilding = parsedState.buildings.find(b => b.name === this.buildings[i].name);
if (savedBuilding) {
this.buildings[i].level = savedBuilding.level;
this.buildings[i].increment = savedBuilding.increment;
}
}
// Восстановление гексов
for (let i = 0; i < this.grid.length; i++) {
const savedHex = parsedState.grid[i];
this.grid[i].owned = savedHex.owned;
this.grid[i].owner = savedHex.owner;
this.grid[i].isCastle = savedHex.isCastle;
this.grid[i].hasFort = savedHex.hasFort;
this.grid[i].troops = savedHex.troops;
this.grid[i].resources = savedHex.resources;
if (this.grid[i].isCastle && this.grid[i].owner === 'player') {
this.castle.hex = this.grid[i];
}
}
this.ui.updateAllResources(this.resourceManager.getAll());
this.ui.logEvent('Игра загружена.');
} else {
this.ui.displayAlert('Сохранения не найдены!');
}
}
battle(attackerTroops, defenderTroops, attackerLevel = 1, defenderLevel = 1) {
// Улучшенная механика битвы с учетом уровня войск
const attackerPower = attackerTroops * attackerLevel;
const defenderPower = defenderTroops * defenderLevel;
if (attackerPower > defenderPower) {
const remainingTroops = Math.ceil((attackerPower - defenderPower) / attackerLevel);
return { winner: 'attacker', remainingTroops: remainingTroops };
} else if (defenderPower > attackerPower) {
const remainingDefenderTroops = Math.ceil((defenderPower - attackerPower) / defenderLevel);
return { winner: 'defender', remainingDefenderTroops: remainingDefenderTroops };
} else {
// Ничья, оба теряют войска
return { winner: 'none', remainingTroops: 0 };
}
}
attackHex(fromHex, toHex) {
// Проверяем, нет ли уже таймера захвата на гексе
if (toHex.captureTimer) {
this.ui.logEvent(`Гекс (${toHex.row}, ${toHex.col}) уже находится под атакой.`);
return;
}
// Определяем время захвата
let captureTime;
if (!toHex.hasFort && toHex.troops === 0) {
// Без форта и армии — 10 секунд
captureTime = 10000;
} else if (toHex.hasFort) {
// С фортом — 45 секунд
captureTime = 45000;
} else {
// Иначе — стандартное время битвы
captureTime = 5000 * Math.ceil(Math.max(fromHex.troops, toHex.troops) / 10);
}
toHex.isUnderAttack = true;
toHex.startCaptureTimer(captureTime);
this.ui.logEvent(`Вы начали атаку на гекс (${toHex.row}, ${toHex.col}). Захват займет ${captureTime / 1000} секунд.`);
// Запускаем таймер захвата
setTimeout(() => {
// По завершении таймера гекс захватывается игроком
toHex.owner = 'player';
toHex.owned = true;
toHex.troops = fromHex.troops; // Перемещаем войска на новый гекс
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.ui.logEvent(`Вы захватили гекс на (${toHex.row}, ${toHex.col}).`);
// Проверяем, не был ли уничтожен замок бота
if (toHex.isCastle) {
this.aiPlayer.castle.loseHealth(1000); // Уничтожаем замок
}
}, captureTime);
}
checkGameOver() {
if (this.castle.isDestroyed) {
this.ui.showGameOver('Вы проиграли. Замок уничтожен.');
} else if (this.aiPlayer.castle.isDestroyed) {
this.ui.showGameOver('Вы выиграли! Замок противника разрушен.');
} else {
// Проверяем, есть ли у бота гексы
const botHexes = this.grid.filter(hex => hex.owner === 'bot');
if (botHexes.length === 0) {
this.ui.showGameOver('Вы выиграли! Все гексы противника захвачены.');
}
}
}
}
// Запуск игры при загрузке страницы
window.onload = () => {
const game = new Game();
};
</script>
Конечно! Я внес необходимые изменения в ваш код, чтобы бот также имел ресурсы, добывал их для строительства улучшений, найма войск и т.д., как и игрок. Это создаст баланс между ботом и игроком.
Ниже приведен обновленный код с подробным объяснением изменений.
Основные изменения:
Добыча ресурсов с гексагонов:
Теперь и игрок, и бот добывают ресурсы не только из зданий, но и с захваченных ими гексагонов.
В методах startResourceGeneration() для игрока и бота добавлена логика сбора ресурсов с принадлежащих им гексагонов.
Использование ресурсов ботом для улучшений и найма войск:
Бот теперь ведет учет своих ресурсов с помощью ResourceManager и использует их для улучшения замка, войск и зданий.
В методе considerUpgrades() бот принимает решения об улучшении замка, войск и зданий на основе наличия ресурсов.
В методах considerExpansion() и considerAttack() бот проверяет свои ресурсы перед тем, как выполнять действия (захват гексов, строительство фортов, отправка войск).
Баланс между ботом и игроком:
Стоимость улучшений и доходы от зданий одинаковы для бота и игрока.
Ресурсы, добываемые с гексагонов, также одинаковы для бота и игрока.
Вот обновленный код:
html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Гексагональная Стратегия</title>
<!-- Стили -->
<style>
/* styles.css */
/* Общие стили */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #2c3e50;
color: #ecf0f1;
}
#gameContainer {
display: flex;
flex-direction: column;
align-items: center;
}
/* Верхняя Панель */
#topPanel {
display: flex;
justify-content: center;
width: 100%;
background-color: #34495e;
padding: 10px 0;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
}
.resource {
margin: 0 15px;
font-size: 16px;
}
/* Основное Игровое Поле */
#mainGame {
position: relative;
width: 1200px;
height: 800px;
border: 2px solid #34495e;
background-color: #1abc9c;
margin-top: 10px;
overflow: hidden;
border-radius: 10px;
}
/* Мини-Карта */
#miniMap {
position: absolute;
top: 10px;
right: 10px;
border: 1px solid #ecf0f1;
background-color: #95a5a6;
border-radius: 5px;
}
/* Нижняя Панель */
#bottomPanel {
display: flex;
justify-content: space-between;
width: 1200px;
background-color: #34495e;
padding: 15px;
box-shadow: 0 -2px 5px rgba(0,0,0,0.3);
border-radius: 0 0 10px 10px;
margin-top: 10px;
}
.controls, .technologies {
width: 48%;
}
.controls button, .technologies button {
width: 100%;
padding: 10px;
margin-top: 5px;
border: none;
border-radius: 5px;
background-color: #1abc9c;
color: #2c3e50;
cursor: pointer;
font-size: 14px;
}
.controls button:hover, .technologies button:hover {
background-color: #16a085;
}
.technologies h3 {
text-align: center;
margin-top: 10px;
}
.technologies ul {
list-style: none;
padding: 0;
}
.technologies li {
margin-bottom: 10px;
}
.technologies span {
display: inline-block;
width: 250px;
}
/* Лог Событий */
#log {
width: 1200px;
background-color: #34495e;
padding: 15px;
margin-top: 10px;
border-radius: 5px;
max-height: 200px;
overflow-y: auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
}
#log h3 {
text-align: center;
margin-top: 0;
}
#log ul {
list-style: none;
padding: 0;
margin: 0;
}
#log li {
margin-bottom: 5px;
font-size: 14px;
}
/* Контекстное Меню */
#contextMenu {
position: absolute;
display: none;
background-color: #34495e;
border: 1px solid #2c3e50;
border-radius: 5px;
box-shadow: 2px 2px 10px rgba(0,0,0,0.5);
z-index: 1000;
width: 200px;
}
#contextMenu ul {
list-style: none;
padding: 5px 0;
margin: 0;
}
#contextMenu li {
padding: 8px 12px;
cursor: pointer;
color: #ecf0f1;
}
#contextMenu li:hover {
background-color: #2c3e50;
}
/* Модальное Окно */
.modal {
display: none; /* Скрыто по умолчанию */
position: fixed; /* Остаётся на месте */
z-index: 2000; /* Сверху остальных элементов */
left: 0;
top: 0;
width: 100%; /* Ширина экрана */
height: 100%; /* Высота экрана */
overflow: auto; /* Включить прокрутку если необходимо */
background-color: rgba(0,0,0,0.5); /* Чёрный фон с прозрачностью */
}
.modal-content {
background-color: #34495e;
margin: 15% auto; /* 15% сверху и центровка */
padding: 20px;
border: 1px solid #888;
border-radius: 8px;
width: 300px; /* Ширина модального окна */
color: #ecf0f1;
}
.close {
color: #ecf0f1;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #f1c40f;
text-decoration: none;
}
/* Всплывающая Подсказка */
.tooltip {
position: absolute;
display: none;
background-color: rgba(44, 62, 80, 0.9);
color: #ecf0f1;
padding: 5px 10px;
border-radius: 4px;
pointer-events: none;
font-size: 12px;
z-index: 1000;
}
/* Окно для уведомления о конце игры */
#gameOverModal {
display: none;
position: fixed;
z-index: 3000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
}
#gameOverContent {
background-color: #34495e;
margin: 20% auto;
padding: 20px;
border: 1px solid #888;
border-radius: 8px;
width: 400px;
color: #ecf0f1;
text-align: center;
}
#gameOverContent h2 {
margin-top: 0;
}
#gameOverContent button {
padding: 10px 20px;
margin-top: 15px;
border: none;
border-radius: 5px;
background-color: #1abc9c;
color: #2c3e50;
cursor: pointer;
font-size: 16px;
}
#gameOverContent button:hover {
background-color: #16a085;
}
</style>
</head>
<body>
<div id="gameContainer">
<!-- Верхняя Панель с Ресурсами -->
<div id="topPanel">
<div class="resource" id="wood">Дерево: 0</div>
<div class="resource" id="iron">Железо: 0</div>
<div class="resource" id="food">Еда: 0</div>
<div class="resource" id="copper">Медь: 0</div>
<div class="resource" id="gold">Золото: 0</div>
<div class="resource" id="population">Жители: 1</div>
<div class="resource" id="castleLevel">Уровень Замка: 1</div>
</div>
<!-- Основное Игровое Поле и Мини-Карта -->
<div id="mainGame">
<canvas id="gameCanvas" width="1200" height="800"></canvas>
<!-- Мини-Карта -->
<canvas id="miniMap" width="200" height="200"></canvas>
</div>
<!-- Нижняя Панель с Улучшениями и Технологиями -->
<div id="bottomPanel">
<div class="controls">
<button id="upgradeCastle">Улучшить Замок (Стоимость: 100 золота)</button>
<button id="buildBarracks">Построить Казарму (Стоимость: 150 дерева, 100 железа)</button>
<button id="upgradeTroops">Улучшить войска (Стоимость: 100 золота)</button>
<button id="saveGame">Сохранить игру</button>
<button id="loadGame">Загрузить игру</button>
</div>
<div class="technologies">
<h3>Технологии</h3>
<ul>
<li>
<span>Лесопилка (+5 Дерева/сек)</span>
<button id="upgradeWood">Улучшить (50 Дерева)</button>
</li>
<li>
<span>Железная Шахта (+5 Железа/сек)</span>
<button id="upgradeIron">Улучшить (50 Железа)</button>
</li>
<li>
<span>Ферма (+5 Еды/сек)</span>
<button id="upgradeFood">Улучшить (50 Еды)</button>
</li>
<li>
<span>Медная Шахта (+5 Меди/сек)</span>
<button id="upgradeCopper">Улучшить (50 Меди)</button>
</li>
<li>
<span>Золотая Шахта (+5 Золота/сек)</span>
<button id="upgradeGold">Улучшить (50 Золота)</button>
</li>
</ul>
</div>
</div>
<!-- Лог Событий -->
<div id="log">
<h3>Лог Событий</h3>
<ul id="logList"></ul>
</div>
<!-- Контекстное Меню -->
<div id="contextMenu">
<ul id="contextMenuList">
<!-- Пункты меню будут добавляться динамически через JS -->
</ul>
</div>
<!-- Модальное Окно для Покупки Войск -->
<div id="troopModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Разместить Войска</h2>
<label for="troopAmount">Количество войск:</label>
<input type="number" id="troopAmount" min="1" value="1">
<button id="buyTroops">Отправить Войска</button>
</div>
</div>
<!-- Всплывающая Подсказка -->
<div class="tooltip" id="tooltip"></div>
<!-- Модальное Окно для Окончания Игры -->
<div id="gameOverModal">
<div id="gameOverContent">
<h2 id="gameOverTitle">Игра окончена</h2>
<p id="gameOverMessage">Вы проиграли.</p>
<button id="restartGame">Начать заново</button>
</div>
</div>
</div>
<!-- Подключение игрового скрипта -->
<script>
// game.js
// Начальные ресурсы, одинаковые для игрока и бота
const INITIAL_RESOURCES = {
wood: 500,
iron: 300,
food: 200,
copper: 100,
gold: 500
};
class ResourceManager {
constructor(ui) {
this.resources = { ...INITIAL_RESOURCES }; // Копируем начальные ресурсы
this.ui = ui;
}
add(resource, amount) {
if (this.resources.hasOwnProperty(resource)) {
this.resources[resource] += amount;
if (this.ui) {
this.ui.updateResource(resource, this.resources[resource]);
}
}
}
subtract(resource, amount) {
if (this.resources.hasOwnProperty(resource) && this.resources[resource] >= amount) {
this.resources[resource] -= amount;
if (this.ui) {
this.ui.updateResource(resource, this.resources[resource]);
}
return true;
}
return false;
}
get(resource) {
return this.resources[resource] || 0;
}
getAll() {
return { ...this.resources };
}
setAll(newResources) {
this.resources = { ...newResources };
if (this.ui) {
this.ui.updateAllResources(this.resources);
}
}
}
class Hex {
constructor(row, col, x, y, size) {
this.row = row;
this.col = col;
this.x = x;
this.y = y;
this.size = size;
this.owned = false;
this.captured = false;
this.isCastle = false;
this.hasFort = false;
this.resources = this.generateRandomResources();
this.troops = 0; // Количество войск на гексе
this.owner = null; // "player" или "bot"
this.buildings = []; // Здания на гексе
this.isUnderAttack = false; // Флаг, обозначающий, что на гексе идёт битва
this.isDestination = false; // Флаг, обозначающий, что армия движется к гексу
this.movementTimer = null; // Таймер движения армии
this.captureTimer = null; // Таймер захвата гекса
this.movementTimeRemaining = 0;
this.captureTimeRemaining = 0;
}
generateRandomResources() {
// Генерация рандомных значений для ресурсов
return {
wood: (Math.random() * 5 + 1).toFixed(1), // 1.0 - 6.0
iron: (Math.random() * 5 + 1).toFixed(1),
food: (Math.random() * 5 + 1).toFixed(1),
copper: (Math.random() * 5 + 1).toFixed(1),
gold: (Math.random() * 5 + 1).toFixed(1)
};
}
startMovementTimer(time) {
this.movementTimeRemaining = time;
this.isDestination = true;
this.movementTimer = setInterval(() => {
this.movementTimeRemaining -= 1000;
if (this.movementTimeRemaining <= 0) {
clearInterval(this.movementTimer);
this.movementTimer = null;
this.isDestination = false;
}
}, 1000);
}
startCaptureTimer(time) {
this.captureTimeRemaining = time;
this.isUnderAttack = true;
this.captureTimer = setInterval(() => {
this.captureTimeRemaining -= 1000;
if (this.captureTimeRemaining <= 0) {
clearInterval(this.captureTimer);
this.captureTimer = null;
this.isUnderAttack = false;
}
}, 1000);
}
draw(ctx) {
const HEX_SIZE = this.size;
const angle = Math.PI / 3;
ctx.beginPath();
for (let i = 0; i < 6; i++) {
ctx.lineTo(
this.x + HEX_SIZE * Math.cos(angle * i),
this.y + HEX_SIZE * Math.sin(angle * i)
);
}
ctx.closePath();
// Устанавливаем цвет в зависимости от владельца
if (this.owner === 'player') {
if (this.isCastle) {
ctx.fillStyle = '#e74c3c'; // Красный для замка игрока
} else if (this.hasFort) {
ctx.fillStyle = '#f1c40f'; // Желтый для форта игрока
} else {
ctx.fillStyle = '#2ecc71'; // Зеленый для гексов игрока
}
} else if (this.owner === 'bot') {
if (this.isCastle) {
ctx.fillStyle = '#8e44ad'; // Фиолетовый для замка бота
} else if (this.hasFort) {
ctx.fillStyle = '#3498db'; // Синий для форта бота
} else {
ctx.fillStyle = '#1abc9c'; // Бирюзовый для гексов бота
}
} else {
ctx.fillStyle = '#ecf0f1'; // Белый для свободных гексов
}
ctx.fill();
ctx.strokeStyle = '#95a5a6';
ctx.stroke();
// Рисуем количество войск, если есть и нет активного таймера
if (this.troops > 0 && !this.isDestination && !this.isUnderAttack) {
ctx.fillStyle = '#fff';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(this.troops, this.x, this.y + 4);
}
// Отображение таймеров
if (this.movementTimer) {
// Отображаем зеленый таймер
ctx.fillStyle = 'rgba(0, 255, 0, 0.5)';
ctx.beginPath();
ctx.arc(this.x, this.y, HEX_SIZE / 2, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#000';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(Math.ceil(this.movementTimeRemaining / 1000), this.x, this.y + 4);
}
if (this.captureTimer) {
// Отображаем красный таймер
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.beginPath();
ctx.arc(this.x, this.y, HEX_SIZE / 2, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#000';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(Math.ceil(this.captureTimeRemaining / 1000), this.x, this.y + 4);
}
// Если идёт битва, рисуем индикатор
if (this.isUnderAttack && !this.captureTimer) {
ctx.beginPath();
ctx.arc(this.x, this.y, HEX_SIZE / 2, 0, 2 * Math.PI);
ctx.strokeStyle = '#ff0000';
ctx.lineWidth = 3;
ctx.stroke();
ctx.lineWidth = 1;
}
}
isClicked(clickX, clickY) {
const dx = clickX - this.x;
const dy = clickY - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
return distance <= this.size;
}
}
class Castle {
constructor(hex, ui, owner) {
this.hex = hex;
this.hex.isCastle = true;
this.hex.owner = owner;
this.level = 1;
this.population = 1;
this.goldIncome = 10;
this.ui = ui;
this.barracks = 0; // Количество казарм
this.castleHealth = 500; // Начальное здоровье замка
this.owner = owner; // "player" или "bot"
this.troopLevel = 1; // Уровень войск
this.isDestroyed = false;
}
upgrade(resourceManager) {
const upgradeCost = 100 * this.level;
if (resourceManager.subtract('gold', upgradeCost)) {
this.level += 1;
this.population += 2;
this.goldIncome += 10;
if (this.owner === 'player') {
this.ui.updateCastle(this.level, this.population);
this.ui.logEvent(`Замок улучшен до уровня ${this.level}. Жители: ${this.population}, доход золота: ${this.goldIncome}`);
}
} else {
if (this.owner === 'player') {
this.ui.displayAlert('Недостаточно золота для улучшения замка!');
}
}
}
buildBarracks(resourceManager) {
const costWood = 150;
const costIron = 100;
if (resourceManager.subtract('wood', costWood) && resourceManager.subtract('iron', costIron)) {
this.barracks += 1;
if (this.owner === 'player') {
this.ui.logEvent(`Казарма построена. Всего казарм: ${this.barracks}`);
}
} else {
if (this.owner === 'player') {
this.ui.displayAlert('Недостаточно ресурсов для строительства казармы!');
}
}
}
upgradeTroops(resourceManager) {
const upgradeCost = 100 * this.troopLevel;
if (resourceManager.subtract('gold', upgradeCost)) {
this.troopLevel += 1;
if (this.owner === 'player') {
this.ui.logEvent(`Войска улучшены до уровня ${this.troopLevel}.`);
}
} else {
if (this.owner === 'player') {
this.ui.displayAlert('Недостаточно золота для улучшения войск!');
}
}
}
collectResources(resourceManager) {
resourceManager.add('gold', this.goldIncome);
if (this.owner === 'player') {
this.ui.updateResource('gold', resourceManager.get('gold'));
}
}
loseHealth(amount) {
this.castleHealth -= amount;
if (this.castleHealth <= 0 && !this.isDestroyed) {
this.isDestroyed = true;
this.hex.owned = false;
this.hex.owner = null;
if (this.owner === 'player') {
this.ui.showGameOver('Вы проиграли. Замок уничтожен.');
} else {
this.ui.logEvent('Вы победили! Замок противника разрушен.');
this.ui.showGameOver('Вы выиграли!');
}
}
}
}
class Building {
constructor(name, resource, increment, costResource, costAmount, ui) {
this.name = name;
this.resource = resource;
this.increment = increment;
this.costResource = costResource;
this.costAmount = costAmount;
this.level = 1;
this.ui = ui;
}
upgrade(resourceManager) {
const totalCost = this.costAmount * this.level;
if (resourceManager.subtract(this.costResource, totalCost)) {
this.level += 1;
this.increment += 5;
if (this.ui) {
this.ui.logEvent(`${this.name} улучшена до уровня ${this.level}. Производство: ${this.increment} ${this.resource}/сек`);
}
} else {
if (this.ui) {
this.ui.displayAlert(`Недостаточно ${this.costResource} для улучшения ${this.name}!`);
}
}
}
}
class UIManager {
constructor(game) {
this.game = game;
this.resourcesElements = {
wood: document.getElementById('wood'),
iron: document.getElementById('iron'),
food: document.getElementById('food'),
copper: document.getElementById('copper'),
gold: document.getElementById('gold')
};
this.populationElement = document.getElementById('population');
this.castleLevelElement = document.getElementById('castleLevel');
this.logList = document.getElementById('logList');
this.tooltip = document.getElementById('tooltip');
this.contextMenu = document.getElementById('contextMenu');
this.contextMenuList = document.getElementById('contextMenuList');
this.troopModal = document.getElementById('troopModal');
this.closeModal = document.querySelector('.close');
this.buyTroopsButton = document.getElementById('buyTroops');
this.gameOverModal = document.getElementById('gameOverModal');
this.gameOverTitle = document.getElementById('gameOverTitle');
this.gameOverMessage = document.getElementById('gameOverMessage');
this.restartGameButton = document.getElementById('restartGame');
// Закрыть модальное окно при клике на крестик
this.closeModal.onclick = () => {
this.hideTroopModal();
};
// Закрыть модальное окно при клике вне его
window.onclick = (event) => {
if (event.target == this.troopModal) {
this.hideTroopModal();
}
};
// Обработчик кнопки перезапуска игры
this.restartGameButton.onclick = () => {
location.reload();
};
}
updateResource(resource, value) {
if (this.resourcesElements[resource]) {
this.resourcesElements[resource].innerText = `${this.capitalize(resource)}: ${Math.floor(value)}`;
}
}
updateAllResources(resources) {
for (const [key, value] of Object.entries(resources)) {
this.updateResource(key, value);
}
}
updatePopulation(population) {
this.populationElement.innerText = `Жители: ${population}`;
}
updateCastle(level, population) {
this.castleLevelElement.innerText = `Уровень Замка: ${level}`;
this.updatePopulation(population);
}
logEvent(message) {
const li = document.createElement('li');
li.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
this.logList.prepend(li);
}
displayAlert(message) {
alert(message);
}
showContextMenu(options, x, y) {
// Очистить текущее содержание меню
this.contextMenuList.innerHTML = '';
// Добавить новые опции
options.forEach(option => {
const li = document.createElement('li');
li.id = option.id;
li.textContent = option.label;
this.contextMenuList.appendChild(li);
});
// Позиционировать и отображать меню
this.contextMenu.style.left = `${x}px`;
this.contextMenu.style.top = `${y}px`;
this.contextMenu.style.display = 'block';
}
hideContextMenu() {
this.contextMenu.style.display = 'none';
}
showTooltip(content, x, y) {
this.tooltip.innerHTML = content;
this.tooltip.style.left = `${x + 10}px`;
this.tooltip.style.top = `${y + 10}px`;
this.tooltip.style.display = 'block';
}
hideTooltip() {
this.tooltip.style.display = 'none';
}
showTroopModal() {
this.troopModal.style.display = 'block';
}
hideTroopModal() {
this.troopModal.style.display = 'none';
}
showGameOver(message) {
this.gameOverMessage.innerText = message;
this.gameOverModal.style.display = 'block';
}
capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
}
class MiniMap {
constructor(mainCanvas, miniCanvas, grid) {
this.mainCanvas = mainCanvas;
this.miniCanvas = miniCanvas;
this.ctx = miniCanvas.getContext('2d');
this.grid = grid;
// Расчет масштаба для 50x50 карты, предполагая размер каждого гекса 40px
this.scale = this.miniCanvas.width / (50 * Math.sqrt(3) * 40); // Пропорция для 50x50 карты
this.draw();
}
draw() {
this.ctx.clearRect(0, 0, this.miniCanvas.width, this.miniCanvas.height);
for (const hex of this.grid) {
if (hex.owned) {
if (hex.owner === 'player') {
if (hex.isCastle) {
this.ctx.fillStyle = '#e74c3c';
} else if (hex.hasFort) {
this.ctx.fillStyle = '#f1c40f';
} else {
this.ctx.fillStyle = '#2ecc71';
}
} else if (hex.owner === 'bot') {
if (hex.isCastle) {
this.ctx.fillStyle = '#8e44ad';
} else if (hex.hasFort) {
this.ctx.fillStyle = '#3498db';
} else {
this.ctx.fillStyle = '#1abc9c';
}
}
// Пропустить гексы вне 50x50
if (hex.row >= 50 || hex.col >= 50) continue;
const x = hex.col * (this.miniCanvas.width / 50) + (hex.row % 2) * (this.miniCanvas.width / 100);
const y = hex.row * (this.miniCanvas.height / 50) * 0.75 + 10; // Добавлен отступ сверху
this.ctx.beginPath();
const size = (this.miniCanvas.width / 50) / 2;
const angle = Math.PI / 3;
for (let i = 0; i < 6; i++) {
this.ctx.lineTo(
x + size * Math.cos(angle * i),
y + size * Math.sin(angle * i)
);
}
this.ctx.closePath();
this.ctx.fill();
this.ctx.strokeStyle = '#ffffff';
this.ctx.stroke();
}
}
}
}
class ModalManager {
constructor(ui, game) {
this.ui = ui;
this.game = game;
this.buyTroopsButton = document.getElementById('buyTroops');
this.troopAmountInput = document.getElementById('troopAmount');
this.buyTroopsButton.addEventListener('click', () => {
this.buyTroops();
});
}
buyTroops() {
const amount = parseInt(this.troopAmountInput.value);
if (isNaN(amount) || amount < 1) {
this.ui.displayAlert('Пожалуйста, введите корректное количество войск.');
return;
}
const troopCost = 10 * amount; // Стоимость 10 еды за каждое войско
if (this.game.resourceManager.subtract('food', troopCost)) {
// Армия движется от замка до целевого гекса
const distance = this.game.calculateDistance(this.game.castle.hex, this.game.selectedHex);
const travelTime = distance * 5 * 1000; // 5 секунд за каждый гекс
this.ui.logEvent(`Войска (${amount} ед.) отправлены к гексу (${this.game.selectedHex.row}, ${this.game.selectedHex.col}). Время в пути: ${travelTime / 1000} сек.`);
// Запускаем таймер движения на гексе
this.game.selectedHex.startMovementTimer(travelTime);
setTimeout(() => {
this.game.selectedHex.troops += amount;
this.ui.logEvent(`Подкрепление (${amount} ед.) прибыло на гекс (${this.game.selectedHex.row}, ${this.game.selectedHex.col}). Общие войска: ${this.game.selectedHex.troops}`);
// Останавливаем таймер движения
this.game.selectedHex.movementTimer = null;
this.game.selectedHex.movementTimeRemaining = 0;
this.game.selectedHex.isDestination = false;
}, travelTime);
this.ui.hideTroopModal();
} else {
this.ui.displayAlert('Недостаточно еды для покупки войск!');
}
}
}
class AIPlayer {
constructor(game, ui) {
this.game = game;
this.ui = ui;
this.resourceManager = new ResourceManager(null); // UI не нужен для бота
this.hexes = []; // Гексы, принадлежащие боту
this.castle = null;
this.buildings = [];
this.setup();
}
setup() {
this.placeStartingCastle();
this.initBuildings();
this.startResourceGeneration();
this.takeActions();
}
placeStartingCastle() {
const availableHexes = this.game.grid.filter(hex => !hex.owned);
const randomHex = availableHexes[Math.floor(Math.random() * availableHexes.length)];
randomHex.owned = true;
randomHex.owner = 'bot';
this.castle = new Castle(randomHex, null, 'bot');
this.hexes.push(randomHex);
this.resourceManager.add('gold', this.castle.goldIncome);
this.game.ui.logEvent(`Бот разместил замок на гексе (${randomHex.row}, ${randomHex.col}).`);
}
initBuildings() {
this.buildings.push(new Building('Лесопилка', 'wood', 5, 'wood', 50, null));
this.buildings.push(new Building('Железная Шахта', 'iron', 5, 'iron', 50, null));
this.buildings.push(new Building('Ферма', 'food', 5, 'food', 50, null));
this.buildings.push(new Building('Медная Шахта', 'copper', 5, 'copper', 50, null));
this.buildings.push(new Building('Золотая Шахта', 'gold', 5, 'gold', 50, null));
}
startResourceGeneration() {
// Генерация ресурсов каждые 1 секунду
setInterval(() => {
// Сбор ресурсов с собственных зданий
for (const building of this.buildings) {
this.resourceManager.add(building.resource, building.increment);
}
this.castle.collectResources(this.resourceManager);
// Сбор ресурсов с принадлежащих гексагонов
for (const hex of this.hexes) {
for (const resource in hex.resources) {
this.resourceManager.add(resource, parseFloat(hex.resources[resource]));
}
}
}, 1000);
// Рост населения каждые 10 секунд
setInterval(() => {
const newResidents = this.castle.level;
this.castle.population += newResidents;
}, 10000);
}
takeActions() {
// Бот принимает решения каждые 5 секунд
setInterval(() => {
if (!this.castle.isDestroyed) {
this.considerUpgrades();
this.considerExpansion();
this.considerAttack();
}
}, 5000);
}
considerUpgrades() {
// Решение об улучшении войск
if (this.resourceManager.get('gold') >= 100 * this.castle.troopLevel) {
this.castle.upgradeTroops(this.resourceManager);
}
// Решение об улучшении замка
if (this.resourceManager.get('gold') >= 100 * this.castle.level) {
this.castle.upgrade(this.resourceManager);
}
// Решение об улучшении зданий
for (const building of this.buildings) {
const totalCost = building.costAmount * building.level;
if (this.resourceManager.get(building.costResource) >= totalCost * 1.5) {
building.upgrade(this.resourceManager);
}
}
}
considerExpansion() {
// Бот ищет гексы для захвата
const possibleHexes = [];
for (const hex of this.hexes) {
const neighbors = this.game.getNeighbors(hex);
for (const neighbor of neighbors) {
if (!neighbor.owned) {
possibleHexes.push(neighbor);
}
}
}
// Сортируем по количеству ресурсов
possibleHexes.sort((a, b) => {
const aResources = Object.values(a.resources).reduce((sum, val) => sum + parseFloat(val), 0);
const bResources = Object.values(b.resources).reduce((sum, val) => sum + parseFloat(val), 0);
return bResources - aResources;
});
// Пытаемся захватить лучший гекс
const captureCost = {
wood: 50,
iron: 30,
gold: 20
};
if (possibleHexes.length > 0) {
const hexToCapture = possibleHexes[0];
const canCapture = Object.keys(captureCost).every(resource => this.resourceManager.get(resource) >= captureCost[resource]);
if (canCapture) {
// Вычесть ресурсы
Object.keys(captureCost).forEach(resource => {
this.resourceManager.subtract(resource, captureCost[resource]);
});
hexToCapture.owned = true;
hexToCapture.owner = 'bot';
this.hexes.push(hexToCapture);
this.game.ui.logEvent(`Бот начал захват гекса на (${hexToCapture.row}, ${hexToCapture.col}).`);
// Запускаем таймер захвата
let captureTime = hexToCapture.hasFort ? 45000 : 10000;
if (hexToCapture.captureTimer) {
this.game.ui.logEvent(`Гекс (${hexToCapture.row}, ${hexToCapture.col}) уже находится под атакой.`);
return;
}
hexToCapture.isUnderAttack = true;
hexToCapture.startCaptureTimer(captureTime);
this.game.ui.logEvent(`Бот захватывает гекс (${hexToCapture.row}, ${hexToCapture.col}). Захват займет ${captureTime / 1000} секунд.`);
setTimeout(() => {
hexToCapture.isUnderAttack = false;
hexToCapture.captureTimer = null;
hexToCapture.captureTimeRemaining = 0;
this.game.ui.logEvent(`Бот захватил гекс на (${hexToCapture.row}, ${hexToCapture.col}).`);
// Строим форт с вероятностью 70%
if (Math.random() < 0.7) {
this.buildFort(hexToCapture);
}
}, captureTime);
} else {
// Недостаточно ресурсов для захвата
// Можно добавить логику ожидания до накопления ресурсов
}
}
}
buildFort(hex) {
const costWood = 50;
const costIron = 25;
if (this.resourceManager.get('wood') >= costWood && this.resourceManager.get('iron') >= costIron) {
this.resourceManager.subtract('wood', costWood);
this.resourceManager.subtract('iron', costIron);
hex.hasFort = true;
// Размещаем войска
hex.troops = Math.floor(this.castle.level * 5 * this.castle.troopLevel);
this.game.ui.logEvent(`Бот построил форт и разместил войска на гексе (${hex.row}, ${hex.col}).`);
} else {
// Недостаточно ресурсов для строительства форта
// Можно добавить логику ожидания до накопления ресурсов
}
}
considerAttack() {
// Бот ищет соседние гексы игрока для атаки
for (const hex of this.hexes) {
const neighbors = this.game.getNeighbors(hex);
for (const neighbor of neighbors) {
if (neighbor.owner === 'player') {
// Проверяем наличие войск на нашем гексе
if (hex.troops > 0 && !neighbor.isUnderAttack) {
this.attackHex(hex, neighbor);
}
}
}
}
}
attackHex(fromHex, toHex) {
// Проверяем, нет ли уже таймера захвата на гексе
if (toHex.captureTimer) {
this.game.ui.logEvent(`Гекс (${toHex.row}, ${toHex.col}) уже находится под атакой.`);
return;
}
// Определяем время захвата
let captureTime;
if (!toHex.hasFort && toHex.troops === 0) {
// Без форта и армии — 10 секунд
captureTime = 10000;
} else if (toHex.hasFort) {
// С фортом — 45 секунд
captureTime = 45000;
} else {
// Иначе — стандартное время битвы
captureTime = 5000 * Math.ceil(Math.max(fromHex.troops, toHex.troops) / 10);
}
toHex.isUnderAttack = true;
toHex.startCaptureTimer(captureTime);
this.game.ui.logEvent(`Бот начал атаку на гекс (${toHex.row}, ${toHex.col}). Захват займет ${captureTime / 1000} секунд.`);
// Запускаем таймер захвата
setTimeout(() => {
// По завершении таймера гекс захватывается ботом
toHex.owner = 'bot';
toHex.owned = true;
toHex.troops = fromHex.troops; // Перемещаем войска на новый гекс
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.hexes.push(toHex);
this.game.ui.logEvent(`Бот захватил гекс на (${toHex.row}, ${toHex.col}).`);
// Проверяем, не был ли уничтожен замок игрока
if (toHex.isCastle) {
this.game.castle.loseHealth(1000); // Уничтожаем замок
}
}, captureTime);
}
}
class Game {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.ui = new UIManager(this);
this.resourceManager = new ResourceManager(this.ui);
this.hexSize = 40;
this.grid = [];
this.castle = null;
this.buildings = [];
this.selectedHex = null; // Для контекстного меню
this.tooltipHex = null; // Для подсказок
this.miniMapInstance = null;
this.panOffset = { x: 0, y: 0 };
this.viewport = { scale: 1 };
this.isPanning = false;
this.startPan = { x: 0, y: 0 };
this.modalManager = null;
this.aiPlayer = null; // Добавляем бота
this.setup();
}
setup() {
this.createGrid(50, 50); // 50x50 карта
this.placeStartingCastle();
this.initBuildings();
this.setupUIControls();
this.setupContextMenuHandlers();
this.mouseEvents();
this.initModalManager();
this.startResourceGeneration();
this.initMiniMap();
this.initAIPlayer(); // Инициализируем бота
this.gameLoop();
}
createGrid(rows, cols) {
const HEX_SIZE = this.hexSize;
const HEX_WIDTH = Math.sqrt(3) * HEX_SIZE;
const HEX_HEIGHT = 2 * HEX_SIZE;
const HEX_HORZ_SPACING = HEX_WIDTH;
const HEX_VERT_SPACING = 1.5 * HEX_SIZE;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
let x = HEX_WIDTH * col + (row % 2) * (HEX_WIDTH / 2);
let y = HEX_HEIGHT * 0.75 * row + HEX_SIZE;
this.grid.push(new Hex(row, col, x, y, HEX_SIZE));
}
}
}
placeStartingCastle() {
const availableHexes = this.grid.filter(hex => !hex.owned);
const randomHex = availableHexes[Math.floor(Math.random() * availableHexes.length)];
randomHex.owned = true;
randomHex.owner = 'player';
this.castle = new Castle(randomHex, this.ui, 'player');
this.resourceManager.add('gold', this.castle.goldIncome);
this.ui.logEvent(`Замок размещен на гексе (${randomHex.row}, ${randomHex.col}).`);
}
initBuildings() {
this.buildings.push(new Building('Лесопилка', 'wood', 5, 'wood', 50, this.ui));
this.buildings.push(new Building('Железная Шахта', 'iron', 5, 'iron', 50, this.ui));
this.buildings.push(new Building('Ферма', 'food', 5, 'food', 50, this.ui));
this.buildings.push(new Building('Медная Шахта', 'copper', 5, 'copper', 50, this.ui));
this.buildings.push(new Building('Золотая Шахта', 'gold', 5, 'gold', 50, this.ui));
}
setupUIControls() {
// Кнопки улучшения замка
document.getElementById('upgradeCastle').addEventListener('click', () => {
this.castle.upgrade(this.resourceManager);
});
// Кнопки строительства казарм
document.getElementById('buildBarracks').addEventListener('click', () => {
this.castle.buildBarracks(this.resourceManager);
});
// Кнопка улучшения войск
document.getElementById('upgradeTroops').addEventListener('click', () => {
this.castle.upgradeTroops(this.resourceManager);
});
// Кнопки сохранения и загрузки игры
document.getElementById('saveGame').addEventListener('click', () => {
this.saveGame();
});
document.getElementById('loadGame').addEventListener('click', () => {
this.loadGame();
});
// Кнопки улучшения зданий
document.getElementById('upgradeWood').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Лесопилка');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeIron').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Железная Шахта');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeFood').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Ферма');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeCopper').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Медная Шахта');
building.upgrade(this.resourceManager);
});
document.getElementById('upgradeGold').addEventListener('click', () => {
const building = this.buildings.find(b => b.name === 'Золотая Шахта');
building.upgrade(this.resourceManager);
});
}
setupContextMenuHandlers() {
// Обработка выбора пунктов контекстного меню
this.ui.contextMenuList.addEventListener('click', (e) => {
if (e.target && e.target.nodeName === 'LI') {
const action = e.target.id;
if (action === 'buildFort') {
if (this.selectedHex) {
this.buildFort(this.selectedHex);
this.ui.hideContextMenu();
}
} else if (action === 'placeTroops') {
if (this.selectedHex) {
this.openTroopModal(this.selectedHex);
this.ui.hideContextMenu();
}
} else if (action === 'upgradeCastleOption') {
this.castle.upgrade(this.resourceManager);
this.ui.hideContextMenu();
} else if (action === 'buildBarracksOption') {
this.castle.buildBarracks(this.resourceManager);
this.ui.hideContextMenu();
} else if (action === 'upgradeTroopsOption') {
this.castle.upgradeTroops(this.resourceManager);
this.ui.hideContextMenu();
}
}
});
}
mouseEvents() {
// Обработка обычного клика для захвата гекса
this.canvas.addEventListener('click', (e) => {
const rect = this.canvas.getBoundingClientRect();
const clickX = (e.clientX - rect.left - this.panOffset.x) / this.viewport.scale;
const clickY = (e.clientY - rect.top - this.panOffset.y) / this.viewport.scale;
const clickedHex = this.getHexAt(clickX, clickY);
if (clickedHex && !clickedHex.owned && !clickedHex.isCastle) {
// Захват территории требует затрат ресурсов
const captureCost = {
wood: 50,
iron: 30,
gold: 20
};
const canCapture = Object.keys(captureCost).every(resource => this.resourceManager.get(resource) >= captureCost[resource]);
if (canCapture && this.isAdjacentToOwnedHex(clickedHex, 'player')) {
// Вычесть ресурсы
Object.keys(captureCost).forEach(resource => {
this.resourceManager.subtract(resource, captureCost[resource]);
});
// Запускаем таймер захвата
let captureTime = clickedHex.hasFort ? 45000 : 10000;
if (clickedHex.captureTimer) {
this.ui.logEvent(`Гекс (${clickedHex.row}, ${clickedHex.col}) уже находится под атакой.`);
return;
}
clickedHex.isUnderAttack = true;
clickedHex.startCaptureTimer(captureTime);
this.ui.logEvent(`Вы начали захват гекса (${clickedHex.row}, ${clickedHex.col}). Захват займет ${captureTime / 1000} секунд.`);
setTimeout(() => {
clickedHex.owner = 'player';
clickedHex.owned = true;
clickedHex.isUnderAttack = false;
clickedHex.captureTimer = null;
clickedHex.captureTimeRemaining = 0;
this.ui.logEvent(`Вы захватили гекс на (${clickedHex.row}, ${clickedHex.col}).`);
}, captureTime);
} else if (!this.isAdjacentToOwnedHex(clickedHex, 'player')) {
this.ui.logEvent('Вы можете захватить только соседние гексы!');
} else {
this.ui.logEvent('Недостаточно ресурсов для захвата территории!');
}
} else if (clickedHex && clickedHex.owner === 'bot') {
// Атакуем гекс бота
const fromHex = this.getPlayerHexWithTroopsNearby(clickedHex);
if (fromHex) {
this.attackHex(fromHex, clickedHex);
} else {
this.ui.logEvent('Нет войск рядом для атаки!');
}
}
});
// Обработка правого клика для контекстного меню
this.canvas.addEventListener('contextmenu', (e) => {
e.preventDefault();
const rect = this.canvas.getBoundingClientRect();
const clickX = (e.clientX - rect.left - this.panOffset.x) / this.viewport.scale;
const clickY = (e.clientY - rect.top - this.panOffset.y) / this.viewport.scale;
const clickedHex = this.getHexAt(clickX, clickY);
if (clickedHex && clickedHex.owned && clickedHex.owner === 'player') {
this.selectedHex = clickedHex; // Сохранить выбранный гекс
if (clickedHex.isCastle) {
// Если это замок, показать контекстное меню для замка
this.ui.showContextMenu([
{ id: 'upgradeCastleOption', label: 'Улучшить Замок' },
{ id: 'buildBarracksOption', label: 'Построить Казарму' },
{ id: 'upgradeTroopsOption', label: 'Улучшить Войска' }
], e.clientX, e.clientY);
} else {
// Иначе, показать обычное контекстное меню
this.ui.showContextMenu([
{ id: 'buildFort', label: 'Построить Форт' },
{ id: 'placeTroops', label: 'Разместить Войска' }
], e.clientX, e.clientY);
}
}
});
// Обработка наведения курсора для показа подсказок
this.canvas.addEventListener('mousemove', (e) => {
const rect = this.canvas.getBoundingClientRect();
const moveX = (e.clientX - rect.left - this.panOffset.x) / this.viewport.scale;
const moveY = (e.clientY - rect.top - this.panOffset.y) / this.viewport.scale;
const hoveredHex = this.getHexAt(moveX, moveY);
if (hoveredHex) {
const resources = hoveredHex.resources;
let content = `<strong>Ресурсы:</strong><br>`;
content += `Дерево: ${(resources.wood * 10).toFixed(1)} / сек<br>`;
content += `Железо: ${(resources.iron * 10).toFixed(1)} / сек<br>`;
content += `Еда: ${(resources.food * 10).toFixed(1)} / сек<br>`;
content += `Медь: ${(resources.copper * 10).toFixed(1)} / сек<br>`;
content += `Золото: ${(resources.gold * 10).toFixed(1)} / сек<br>`;
if (hoveredHex.hasFort) {
content += `<strong>Форт:</strong> Размещено войск: ${hoveredHex.troops}`;
}
content += `<br><strong>Владелец:</strong> ${hoveredHex.owner === 'player' ? 'Вы' : hoveredHex.owner === 'bot' ? 'Бот' : 'Никто'}`;
this.ui.showTooltip(content, e.clientX, e.clientY);
this.tooltipHex = hoveredHex;
} else {
this.ui.hideTooltip();
this.tooltipHex = null;
}
});
// При уходе курсора с холста скрываем подсказку
this.canvas.addEventListener('mouseleave', () => {
this.ui.hideTooltip();
this.tooltipHex = null;
});
// Обработка перемещения по карте (панорамирование)
this.canvas.addEventListener('mousedown', (e) => {
if (e.button === 1 || (e.button === 0 && e.shiftKey)) { // Средняя кнопка или Shift + Левый
this.isPanning = true;
this.startPan.x = e.clientX;
this.startPan.y = e.clientY;
}
});
document.addEventListener('mouseup', (e) => {
this.isPanning = false;
});
document.addEventListener('mousemove', (e) => {
if (this.isPanning) {
const dx = e.clientX - this.startPan.x;
const dy = e.clientY - this.startPan.y;
this.panOffset.x += dx;
this.panOffset.y += dy;
this.startPan.x = e.clientX;
this.startPan.y = e.clientY;
}
});
// Обработка колесика мыши для масштабирования
this.canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const zoomIntensity = 0.1;
const delta = e.deltaY < 0 ? 1 : -1;
const factor = 1 + delta * zoomIntensity;
this.viewport.scale *= factor;
this.viewport.scale = Math.min(Math.max(this.viewport.scale, 0.5), 2);
});
}
initModalManager() {
this.modalManager = new ModalManager(this.ui, this);
}
openTroopModal(hex) {
if (hex.hasFort) {
this.ui.showTroopModal();
} else {
this.ui.displayAlert('На этом гексе не построен форт!');
}
}
getHexAt(x, y) {
return this.grid.find(hex => hex.isClicked(x, y));
}
isAdjacentToOwnedHex(targetHex, owner) {
const neighbors = this.getNeighbors(targetHex);
return neighbors.some(hex => hex.owner === owner);
}
getNeighbors(hex) {
const directions = [
{ dr: -1, dc: 0 }, { dr: -1, dc: 1 }, { dr: 0, dc: -1 },
{ dr: 0, dc: 1 }, { dr: 1, dc: -1 }, { dr: 1, dc: 0 }
];
const neighbors = [];
for (const dir of directions) {
const neighbor = this.grid.find(h => h.row === hex.row + dir.dr && h.col === hex.col + dir.dc);
if (neighbor) {
neighbors.push(neighbor);
}
}
return neighbors;
}
getPlayerHexWithTroopsNearby(targetHex) {
const neighbors = this.getNeighbors(targetHex);
return neighbors.find(hex => hex.owner === 'player' && hex.troops > 0);
}
captureHex(hex, owner) {
hex.owned = true;
hex.owner = owner;
this.ui.logEvent(`Гекс захвачен на (${hex.row}, ${hex.col}).`);
}
buildFort(hex) {
if (!hex.hasFort) {
const costWood = 50;
const costIron = 25;
if (this.resourceManager.subtract('wood', costWood) && this.resourceManager.subtract('iron', costIron)) {
hex.hasFort = true;
this.ui.logEvent(`Форт построен на гексе (${hex.row}, ${hex.col}).`);
} else {
this.ui.displayAlert('Недостаточно ресурсов для строительства форта!');
}
} else {
this.ui.displayAlert('На этом гексе уже построен форт!');
}
}
placeTroops(hex) {
if (hex.hasFort) {
if (this.castle.barracks > 0) {
this.openTroopModal(hex);
} else {
this.ui.displayAlert('Необходимо построить казармы в замке для размещения войск!');
}
} else {
this.ui.displayAlert('На этом гексе не построен форт!');
}
}
startResourceGeneration() {
// Генерация ресурсов каждые 1 секунду
setInterval(() => {
// Сбор ресурсов со зданий
for (const building of this.buildings) {
this.resourceManager.add(building.resource, building.increment);
}
this.castle.collectResources(this.resourceManager);
// Сбор ресурсов с принадлежащих гексагонов
const ownedHexes = this.grid.filter(hex => hex.owner === 'player');
for (const hex of ownedHexes) {
for (const resource in hex.resources) {
this.resourceManager.add(resource, parseFloat(hex.resources[resource]));
}
}
}, 1000);
// Рост населения каждые 10 секунд в зависимости от уровня замка
setInterval(() => {
const newResidents = this.castle.level;
this.castle.population += newResidents;
this.ui.updatePopulation(this.castle.population);
this.ui.logEvent(`Население выросло на ${newResidents}. Всего жителей: ${this.castle.population}`);
}, 10000);
}
initMiniMap() {
this.miniMapInstance = new MiniMap(this.canvas, document.getElementById('miniMap'), this.grid);
}
initAIPlayer() {
this.aiPlayer = new AIPlayer(this, this.ui);
}
gameLoop() {
this.ctx.save();
this.ctx.translate(this.panOffset.x, this.panOffset.y);
this.ctx.scale(this.viewport.scale, this.viewport.scale);
this.ctx.clearRect(-this.panOffset.x / this.viewport.scale, -this.panOffset.y / this.viewport.scale, this.canvas.width / this.viewport.scale, this.canvas.height / this.viewport.scale);
this.drawGrid();
this.ctx.restore();
this.drawMiniMap();
// Проверка условий окончания игры
this.checkGameOver();
requestAnimationFrame(() => this.gameLoop());
}
drawGrid() {
for (const hex of this.grid) {
hex.draw(this.ctx);
}
}
drawMiniMap() {
// Обновление мини-карты
if (this.miniMapInstance) {
this.miniMapInstance.draw();
}
}
calculateDistance(hex1, hex2) {
// Простой способ расчёта расстояния между гексами
const dx = hex2.col - hex1.col;
const dy = hex2.row - hex1.row;
return Math.max(Math.abs(dx), Math.abs(dy));
}
saveGame() {
const gameState = {
resources: this.resourceManager.getAll(),
castle: {
level: this.castle.level,
population: this.castle.population,
goldIncome: this.castle.goldIncome,
barracks: this.castle.barracks,
troopLevel: this.castle.troopLevel,
location: {
row: this.castle.hex.row,
col: this.castle.hex.col
},
castleHealth: this.castle.castleHealth
},
buildings: this.buildings.map(b => ({
name: b.name,
level: b.level,
increment: b.increment
})),
grid: this.grid.map(hex => ({
row: hex.row,
col: hex.col,
owned: hex.owned,
owner: hex.owner,
isCastle: hex.isCastle,
hasFort: hex.hasFort,
troops: hex.troops,
resources: hex.resources
}))
};
localStorage.setItem('hexGameSave', JSON.stringify(gameState));
this.ui.logEvent('Игра сохранена.');
}
loadGame() {
const savedState = localStorage.getItem('hexGameSave');
if (savedState) {
const parsedState = JSON.parse(savedState);
this.resourceManager.setAll(parsedState.resources);
// Восстановление замка
const castleLocation = parsedState.castle.location;
const castleHex = this.grid.find(hex => hex.row === castleLocation.row && hex.col === castleLocation.col);
if (castleHex) {
this.castle = new Castle(castleHex, this.ui, 'player');
this.castle.level = parsedState.castle.level;
this.castle.population = parsedState.castle.population;
this.castle.goldIncome = parsedState.castle.goldIncome;
this.castle.barracks = parsedState.castle.barracks;
this.castle.troopLevel = parsedState.castle.troopLevel;
this.castle.castleHealth = parsedState.castle.castleHealth;
this.ui.updateCastle(this.castle.level, this.castle.population);
}
// Восстановление зданий
for (let i = 0; i < this.buildings.length; i++) {
const savedBuilding = parsedState.buildings.find(b => b.name === this.buildings[i].name);
if (savedBuilding) {
this.buildings[i].level = savedBuilding.level;
this.buildings[i].increment = savedBuilding.increment;
}
}
// Восстановление гексов
for (let i = 0; i < this.grid.length; i++) {
const savedHex = parsedState.grid[i];
this.grid[i].owned = savedHex.owned;
this.grid[i].owner = savedHex.owner;
this.grid[i].isCastle = savedHex.isCastle;
this.grid[i].hasFort = savedHex.hasFort;
this.grid[i].troops = savedHex.troops;
this.grid[i].resources = savedHex.resources;
if (this.grid[i].isCastle && this.grid[i].owner === 'player') {
this.castle.hex = this.grid[i];
}
}
this.ui.updateAllResources(this.resourceManager.getAll());
this.ui.logEvent('Игра загружена.');
} else {
this.ui.displayAlert('Сохранения не найдены!');
}
}
battle(attackerTroops, defenderTroops, attackerLevel = 1, defenderLevel = 1) {
// Улучшенная механика битвы с учетом уровня войск
const attackerPower = attackerTroops * attackerLevel;
const defenderPower = defenderTroops * defenderLevel;
if (attackerPower > defenderPower) {
const remainingTroops = Math.ceil((attackerPower - defenderPower) / attackerLevel);
return { winner: 'attacker', remainingTroops: remainingTroops };
} else if (defenderPower > attackerPower) {
const remainingDefenderTroops = Math.ceil((defenderPower - attackerPower) / defenderLevel);
return { winner: 'defender', remainingDefenderTroops: remainingDefenderTroops };
} else {
// Ничья, оба теряют войска
return { winner: 'none', remainingTroops: 0 };
}
}
attackHex(fromHex, toHex) {
// Проверяем, нет ли уже таймера захвата на гексе
if (toHex.captureTimer) {
this.ui.logEvent(`Гекс (${toHex.row}, ${toHex.col}) уже находится под атакой.`);
return;
}
// Определяем время захвата
let captureTime;
if (!toHex.hasFort && toHex.troops === 0) {
// Без форта и армии — 10 секунд
captureTime = 10000;
} else if (toHex.hasFort) {
// С фортом — 45 секунд
captureTime = 45000;
} else {
// Иначе — стандартное время битвы
captureTime = 5000 * Math.ceil(Math.max(fromHex.troops, toHex.troops) / 10);
}
toHex.isUnderAttack = true;
toHex.startCaptureTimer(captureTime);
this.ui.logEvent(`Вы начали атаку на гекс (${toHex.row}, ${toHex.col}). Захват займет ${captureTime / 1000} секунд.`);
// Запускаем таймер захвата
setTimeout(() => {
// По завершении таймера гекс захватывается игроком
toHex.owner = 'player';
toHex.owned = true;
toHex.troops = fromHex.troops; // Перемещаем войска на новый гекс
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.ui.logEvent(`Вы захватили гекс на (${toHex.row}, ${toHex.col}).`);
// Проверяем, не был ли уничтожен замок бота
if (toHex.isCastle) {
this.aiPlayer.castle.loseHealth(1000); // Уничтожаем замок
}
}, captureTime);
}
checkGameOver() {
if (this.castle.isDestroyed) {
this.ui.showGameOver('Вы проиграли. Замок уничтожен.');
} else if (this.aiPlayer.castle.isDestroyed) {
this.ui.showGameOver('Вы выиграли! Замок противника разрушен.');
} else {
// Проверяем, есть ли у бота гексы
const botHexes = this.grid.filter(hex => hex.owner === 'bot');
if (botHexes.length === 0) {
this.ui.showGameOver('Вы выиграли! Все гексы противника захвачены.');
}
}
}
}
// Запуск игры при загрузке страницы
window.onload = () => {
const game = new Game();
};
</script>
</body>
</html>
Теперь бот добывает ресурсы с принадлежащих ему гексагонов, использует их для улучшения замка, войск и зданий, а также для захвата новых территорий и строительства фортов. Это создает баланс между ботом и игроком, делая игру более интересной и динамичной.
Если у вас возникнут дополнительные вопросы или потребуется помощь с дальнейшим улучшением игры, пожалуйста, дайте мне знать!