Explore добавь в базовые ресурсы население , бот не может нанять армию без населения также как и… Save Share Download ▾ Reportдобавь в базовые ресурсы население , бот не может нанять армию без населения также как и игрок , про балансируй его логику const INITIAL_RESOURCES = {
wood: 1500,
iron: 1300,
food: 1200,
copper: 1100,
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;
this.buildings = [];
this.isUnderAttack = false;
this.isDestination = false;
this.movementTimer = null;
this.captureTimer = null;
this.movementTimeRemaining = 0;
this.captureTimeRemaining = 0;
this.incomingTroops = []; // Массив перемещающихся к гексу войск
this.attackingTroops = []; // Массив атакующих гекс войск
}
generateRandomResources() {
return {
wood: (Math.random() * 5 + 1).toFixed(1),
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;
}
Assistant2024-10-07 05:09 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 7, 2024
Added to archive Nov 16, 2026
ID 01m7h41wnd21bbvp9fwddk3wx5Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 08e191ec62f0fb24eb0a6f846a0fe63a
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
добавь в базовые ресурсы население , бот не может нанять… · The Chat Archive // Класс замка
class Castle {
constructor(hex, ui, owner) {
this.hex = hex;
this.hex.isCastle = true;
this.hex.owner = owner;
this.level = 1;
this.population = 10; // Увеличенное начальное население
this.goldIncome = 10;
this.ui = ui;
this.barracks = 0;
this.castleHealth = 500; // Здоровье замка
this.owner = owner;
this.troopLevel = 1; // Уровень войск
this.isDestroyed = false;
this.soldiers = 0; // Общее количество солдат
}
upgrade(resourceManager) {
const upgradeCost = 100 * this.level;
if (resourceManager.subtract('gold', upgradeCost)) {
this.level += 1;
this.population += 5; // Увеличение населения при улучшении замка
this.goldIncome += 10;
if (this.owner === 'player') {
this.ui.updateCastle(this.level, this.population);
this.ui.logEvent(`Замок улучшен до уровня ${this.level}. Жители: ${this.population}, доход золота: ${this.goldIncome}`);
this.ui.showNotification(`Замок улучшен до уровня ${this.level}.`);
}
} 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}`);
this.ui.showNotification(`Казарма построена.`);
}
} 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}.`);
this.ui.showNotification(`Войска улучшены до уровня ${this.troopLevel}.`);
this.ui.updateTroopLevel(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.owner === 'player') {
this.ui.updateCastleHealth(this.castleHealth);
this.ui.showNotification(`Ваш замок атакован! Здоровье: ${this.castleHealth}`);
}
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}/сек`);
this.ui.showNotification(`${this.name} улучшена до уровня ${this.level}.`);
}
} 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.castleHealthElement = document.getElementById('castleHealth');
this.troopLevelElement = document.getElementById('troopLevel');
this.soldiersElement = document.getElementById('soldiers');
this.foodConsumptionElement = document.getElementById('foodConsumption');
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('.modal .close');
this.buyTroopsButton = document.getElementById('buyTroops');
this.notificationPanel = document.getElementById('notificationPanel');
this.tradeModal = document.getElementById('tradeModal');
this.tradeContent = document.getElementById('tradeContent');
this.closeTrade = document.getElementById('closeTrade');
this.techModal = document.getElementById('techModal');
this.techContent = document.getElementById('techContent');
this.closeTech = document.getElementById('closeTech');
this.techTreeContainer = document.getElementById('techTree');
// Удалено: this.viewRectangle = document.getElementById('viewRectangle');
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();
}
if (event.target == this.tradeModal) {
this.hideTradeModal();
}
if (event.target == this.techModal) {
this.hideTechModal();
}
};
this.restartGameButton.onclick = () => {
location.reload();
};
}
updateResource(resource, value) {
if (this.resourcesElements[resource]) {
this.resourcesElements[resource].innerText = `${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);
}
updateCastleHealth(health) {
this.castleHealthElement.innerText = `Здоровье Замка: ${health}`;
}
updateTroopLevel(level) {
this.troopLevelElement.innerText = `Уровень Войск: ${level}`;
}
updateSoldiers(count) {
this.soldiersElement.innerText = `Войска: ${count}`;
}
updateFoodConsumption(consumption) {
this.foodConsumptionElement.innerText = `Потребление Еды: ${consumption.toFixed(2)}`;
}
logEvent(message) {
const li = document.createElement('li');
li.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
this.logList.prepend(li);
}
displayAlert(message) {
alert(message);
}
showNotification(message) {
const notification = document.createElement('div');
notification.className = 'notification';
notification.innerText = message;
this.notificationPanel.prepend(notification);
// Удалить уведомление через 5 секунд
setTimeout(() => {
notification.remove();
}, 5000);
}
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';
}
showTradeModal() {
this.tradeModal.style.display = 'block';
}
hideTradeModal() {
this.tradeModal.style.display = 'none';
}
showTechModal() {
this.techModal.style.display = 'block';
}
hideTechModal() {
this.techModal.style.display = 'none';
}
showGameOver(message) {
this.gameOverMessage.innerText = message;
this.gameOverModal.style.display = 'block';
}
capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
// Удалено: Обновление прямоугольника зоны видимости
// Теперь это полностью управляется классом MiniMap
// Класс мини-карты
class MiniMap {
constructor(mainCanvas, miniCanvas, grid, game) {
this.mainCanvas = mainCanvas;
this.miniCanvas = miniCanvas;
this.ctx = miniCanvas.getContext('2d');
this.grid = grid;
this.game = game;
this.scale = this.miniCanvas.width / (50 * Math.sqrt(3) * 40);
}
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');
}
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();
}
}
// Отображение прямоугольника зоны видимости
this.drawViewRectangle();
}
drawViewRectangle() {
const canvasRect = this.mainCanvas.getBoundingClientRect();
const miniMapRect = this.miniCanvas.getBoundingClientRect();
const scaleX = this.miniCanvas.width / (this.game.gridWidth * Math.sqrt(3) * this.game.hexSize);
const scaleY = this.miniCanvas.height / (this.game.gridHeight * 2 * this.game.hexSize * 0.75);
const viewWidth = this.mainCanvas.width / this.game.viewport.scale * scaleX;
const viewHeight = this.mainCanvas.height / this.game.viewport.scale * scaleY;
const offsetX = -this.game.panOffset.x / this.game.viewport.scale * scaleX;
const offsetY = -this.game.panOffset.y / this.game.viewport.scale * scaleY;
this.ctx.strokeStyle = 'red';
this.ctx.lineWidth = 2;
this.ctx.strokeRect(offsetX, offsetY, viewWidth, viewHeight);
}
// Класс управления модальными окнами
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 costGold = 50 * amount * this.game.troopCostMultiplier;
const costCopper = 20 * amount * this.game.troopCostMultiplier;
// Проверка наличия ресурсов
if (this.game.resourceManager.get('gold') < costGold || this.game.resourceManager.get('copper') < costCopper) {
this.ui.displayAlert('Недостаточно ресурсов для найма войск!');
return;
}
// Проверка наличия населения
if (this.game.castle.population < amount) {
this.ui.displayAlert('Недостаточно населения для найма войск!');
return;
}
// Вычитаем ресурсы и население
this.game.resourceManager.subtract('gold', costGold);
this.game.resourceManager.subtract('copper', costCopper);
this.game.castle.population -= amount;
this.game.ui.updatePopulation(this.game.castle.population);
// Увеличиваем общее количество солдат
this.game.castle.soldiers += amount;
this.game.ui.updateSoldiers(this.game.castle.soldiers);
const distance = this.game.calculateDistance(this.game.castle.hex, this.game.selectedHex);
const travelTime = distance * 5000 / this.game.troopMovementSpeedMultiplier;
this.ui.logEvent(`Войска (${amount} ед.) отправлены к гексу (${this.game.selectedHex.row}, ${this.game.selectedHex.col}). Время в пути: ${Math.round(travelTime / 1000)} сек.`);
this.ui.showNotification(`Войска отправлены к гексу (${this.game.selectedHex.row}, ${this.game.selectedHex.col}).`);
// Создаем объект с информацией о перемещающихся войсках
const troopMovement = {
amount: amount,
arrivalTime: Date.now() + travelTime
};
// Добавляем перемещающиеся войска к гексу
this.game.selectedHex.incomingTroops.push(troopMovement);
this.game.selectedHex.startMovementTimer(travelTime);
setTimeout(() => {
this.game.selectedHex.troops += amount;
// Удаляем информацию о перемещающихся войсках
this.game.selectedHex.incomingTroops = this.game.selectedHex.incomingTroops.filter(troop => troop !== troopMovement);
this.ui.logEvent(`Подкрепление (${amount} ед.) прибыло на гекс (${this.game.selectedHex.row}, ${this.game.selectedHex.col}). Общие войска: ${this.game.selectedHex.troops}`);
this.ui.showNotification(`Подкрепление прибыло на гекс (${this.game.selectedHex.row}, ${this.game.selectedHex.col}).`);
this.game.selectedHex.movementTimer = null;
this.game.selectedHex.movementTimeRemaining = 0;
this.game.selectedHex.isDestination = false;
}, travelTime);
this.ui.hideTroopModal();
}
// Класс ИИ игрока (бота)
class AIPlayer {
constructor(game, ui) {
this.game = game;
this.ui = ui;
this.resourceManager = new ResourceManager(null);
this.hexes = [];
this.castle = null;
this.buildings = [];
this.techTree = new TechTree(null, this.resourceManager, null);
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() {
setInterval(() => {
for (const building of this.buildings) {
this.resourceManager.add(building.resource, building.increment);
}
this.castle.collectResources(this.resourceManager);
}, 1000);
setInterval(() => {
const newResidents = this.castle.level;
this.castle.population += newResidents;
}, 10000);
}
takeActions() {
setInterval(() => {
if (!this.castle.isDestroyed) {
this.considerUpgrades();
this.considerExpansion();
this.considerAttack();
this.considerResearch();
}
}, 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}).`);
if (Math.random() < 0.7) {
this.buildFort(hexToCapture);
}
}
}
}
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}).`);
}
}
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) {
captureTime = 10000;
} else if (toHex.hasFort) {
captureTime = 45000;
} else {
captureTime = 5000 * Math.ceil(Math.max(fromHex.troops, toHex.troops) / 10);
}
toHex.isUnderAttack = true;
toHex.startCaptureTimer(captureTime);
// Добавляем данные об атакующих войсках
const attackingTroop = {
amount: fromHex.troops,
arrivalTime: Date.now() + captureTime
};
toHex.attackingTroops.push(attackingTroop);
this.game.ui.logEvent(`Бот начал атаку на гекс (${toHex.row}, ${toHex.col}). Захват займет ${Math.round(captureTime / 1000)} секунд.`);
this.game.ui.showNotification(`Бот атакует гекс (${toHex.row}, ${toHex.col}).`);
setTimeout(() => {
const battleResult = this.game.battle(fromHex.troops, toHex.troops, this.castle.troopLevel, this.game.castle.troopLevel);
// Удаляем данные об атакующих войсках
toHex.attackingTroops = toHex.attackingTroops.filter(troop => troop !== attackingTroop);
if (battleResult.winner === 'attacker') {
toHex.owner = 'bot';
toHex.owned = true;
toHex.troops = battleResult.remainingTroops;
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);
}
} else {
toHex.troops = battleResult.remainingDefenderTroops || 0;
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.game.ui.logEvent(`Бот не смог захватить гекс (${toHex.row}, ${toHex.col}).`);
}
}, captureTime);
}
considerResearch() {
// Бот автоматически исследует доступные технологии
for (const tech of this.techTree.technologies) {
if (!tech.unlocked && this.resourceManager.get('gold') >= tech.cost['gold']) {
const canResearch = Object.keys(tech.cost).every(resource => this.resourceManager.get(resource) >= tech.cost[resource]);
if (canResearch) {
Object.keys(tech.cost).forEach(resource => {
this.resourceManager.subtract(resource, tech.cost[resource]);
});
tech.unlocked = true;
tech.effect(this);
this.game.ui.logEvent(`Бот исследовал технологию: ${tech.name}`);
}
}
}
}
// Класс игры
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.gridWidth = 50;
this.gridHeight = 50;
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.techTree = new TechTree(this.ui, this.resourceManager, this);
this.tradeManager = new TradeManager(this.ui, this.resourceManager);
this.troopCostMultiplier = 1; // Мультипликатор стоимости найма войск (может изменяться технологиями)
this.troopMovementSpeedMultiplier = 1; // Мультипликатор скорости перемещения войск (может изменяться технологиями)
this.troopDamageMultiplier = 1; // Мультипликатор урона войск (может изменяться технологиями)
this.setup();
}
setup() {
this.createGrid(50, 50);
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}).`);
this.ui.updateCastleHealth(this.castle.castleHealth);
this.ui.updateTroopLevel(this.castle.troopLevel);
}
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);
});
document.getElementById('openTrade').addEventListener('click', () => {
this.tradeManager.openTradeWindow();
});
document.getElementById('confirmTrade').addEventListener('click', () => {
this.tradeManager.confirmTrade();
});
this.ui.closeTrade.addEventListener('click', () => {
this.ui.hideTradeModal();
});
document.getElementById('openTechTree').addEventListener('click', () => {
this.techTree.openTechTree();
});
this.ui.closeTech.addEventListener('click', () => {
this.ui.hideTechModal();
});
}
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);
// Добавляем данные об атакующих войсках
const attackingTroop = {
amount: 0, // В случае захвата без войск
arrivalTime: Date.now() + captureTime
};
clickedHex.attackingTroops.push(attackingTroop);
this.ui.logEvent(`Вы начали захват гекса (${clickedHex.row}, ${clickedHex.col}). Захват займет ${Math.round(captureTime / 1000)} сек.`);
this.ui.showNotification(`Захват гекса (${clickedHex.row}, ${clickedHex.col}) начат.`);
setTimeout(() => {
clickedHex.owner = 'player';
clickedHex.owned = true;
clickedHex.isUnderAttack = false;
clickedHex.captureTimer = null;
clickedHex.captureTimeRemaining = 0;
// Удаляем информацию об атакующих войсках
clickedHex.attackingTroops = clickedHex.attackingTroops.filter(troop => troop !== attackingTroop);
this.ui.logEvent(`Вы захватили гекс на (${clickedHex.row}, ${clickedHex.col}).`);
this.ui.showNotification(`Вы захватили гекс (${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>Гекс (${hoveredHex.row}, ${hoveredHex.col})</strong><br>`;
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}<br>`;
}
content += `<strong>Войска на гексе:</strong> ${hoveredHex.troops}<br>`;
// Информация о перемещающихся войсках
if (hoveredHex.incomingTroops.length > 0) {
const totalIncoming = hoveredHex.incomingTroops.reduce((sum, troop) => sum + troop.amount, 0);
content += `<strong>К вам идут войска:</strong> ${totalIncoming}<br>`;
}
// Информация об атакующих войсках
if (hoveredHex.isUnderAttack && hoveredHex.attackingTroops.length > 0) {
const totalAttacking = hoveredHex.attackingTroops.reduce((sum, troop) => sum + troop.amount, 0);
content += `<strong>На вас нападают войска:</strong> ${totalAttacking}<br>`;
}
// Урон войск
if (hoveredHex.owner) {
const troopLevel = hoveredHex.owner === 'player' ? this.castle.troopLevel : this.aiPlayer.castle.troopLevel;
const troopDamage = troopLevel * 10 * this.troopDamageMultiplier; // Учитываем мультипликатор урона
content += `<strong>Урон войск:</strong> ${troopDamage}<br>`;
}
content += `<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}).`);
this.ui.showNotification(`Форт построен на гексе (${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() {
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}`);
this.ui.showNotification(`Население выросло на ${newResidents}.`);
}, 10000);
// Поддержание войск и потребление еды
setInterval(() => {
const foodConsumption = this.castle.soldiers * 0.01;
if (this.resourceManager.get('food') >= foodConsumption) {
this.resourceManager.subtract('food', foodConsumption);
} else {
// Недостаточно еды, войска начинают умирать
const lostSoldiers = Math.ceil(this.castle.soldiers * 0.1);
this.castle.soldiers -= lostSoldiers;
this.ui.updateSoldiers(this.castle.soldiers);
this.ui.logEvent(`Из-за голода ${lostSoldiers} солдат умерло. Осталось войск: ${this.castle.soldiers}`);
// Уменьшаем войска на гексах
for (const hex of this.grid) {
if (hex.owner === 'player' && hex.troops > 0) {
const lostTroops = Math.min(hex.troops, lostSoldiers);
hex.troops -= lostTroops;
if (hex.troops <= 0) {
hex.troops = 0;
}
}
}
}
this.ui.updateFoodConsumption(foodConsumption);
}, 1000); // Каждую секунду
}
initMiniMap() {
this.miniMapInstance = new MiniMap(this.canvas, document.getElementById('miniMap'), this.grid, this);
}
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.ui.updateViewRectangle(); // Обновляем прямоугольник зоны видимости
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,
soldiers: this.castle.soldiers
},
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
})),
technologies: this.techTree.saveState()
};
localStorage.setItem('hexGameSave', JSON.stringify(gameState));
this.ui.logEvent('Игра сохранена.');
this.ui.showNotification('Игра сохранена.');
}
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.castle.soldiers = parsedState.castle.soldiers || 0;
this.ui.updateCastle(this.castle.level, this.castle.population);
this.ui.updateCastleHealth(this.castle.castleHealth);
this.ui.updateTroopLevel(this.castle.troopLevel);
this.ui.updateSoldiers(this.castle.soldiers);
}
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.techTree.loadState(parsedState.technologies);
this.ui.updateAllResources(this.resourceManager.getAll());
this.ui.logEvent('Игра загружена.');
this.ui.showNotification('Игра загружена.');
} else {
this.ui.displayAlert('Сохранения не найдены!');
}
}
battle(attackerTroops, defenderTroops, attackerLevel = 1, defenderLevel = 1) {
const attackerPower = attackerTroops * attackerLevel * this.troopDamageMultiplier;
const defenderPower = defenderTroops * defenderLevel;
if (attackerPower > defenderPower) {
const remainingTroops = Math.ceil((attackerPower - defenderPower) / (attackerLevel * this.troopDamageMultiplier));
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) {
captureTime = 10000;
} else if (toHex.hasFort) {
captureTime = 45000;
} else {
captureTime = 5000 * Math.ceil(Math.max(fromHex.troops, toHex.troops) / 10);
}
toHex.isUnderAttack = true;
toHex.startCaptureTimer(captureTime);
// Добавляем данные об атакующих войсках
const attackingTroop = {
amount: fromHex.troops,
arrivalTime: Date.now() + captureTime
};
toHex.attackingTroops.push(attackingTroop);
this.ui.logEvent(`Вы начали атаку на гекс (${toHex.row}, ${toHex.col}). Захват займет ${Math.round(captureTime / 1000)} сек.`);
this.ui.showNotification(`Атака на гекс (${toHex.row}, ${toHex.col}) начата.`);
setTimeout(() => {
const battleResult = this.battle(fromHex.troops, toHex.troops, this.castle.troopLevel, this.aiPlayer.castle.troopLevel);
// Удаляем данные об атакующих войсках
toHex.attackingTroops = toHex.attackingTroops.filter(troop => troop !== attackingTroop);
if (battleResult.winner === 'attacker') {
toHex.owner = 'player';
toHex.owned = true;
toHex.troops = battleResult.remainingTroops;
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.ui.logEvent(`Вы захватили гекс на (${toHex.row}, ${toHex.col}).`);
this.ui.showNotification(`Вы захватили гекс (${toHex.row}, ${toHex.col}).`);
if (toHex.isCastle) {
this.aiPlayer.castle.loseHealth(1000);
}
} else {
toHex.troops = battleResult.remainingDefenderTroops || 0;
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.ui.logEvent('Атака не удалась.');
this.ui.showNotification('Атака не удалась.');
}
}, 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('Вы выиграли! Все гексы противника захвачены.');
}
}
}
// Класс технологии и древа технологий
class Technology {
constructor(name, description, cost, effect) {
this.name = name;
this.description = description;
this.cost = cost;
this.effect = effect;
this.unlocked = false;
}
}
class TechTree {
constructor(ui, resourceManager, game) {
this.ui = ui;
this.resourceManager = resourceManager;
this.game = game;
this.technologies = [];
this.initTechnologies();
}
initTechnologies() {
this.technologies = [
// Первые 5 технологий
new Technology(
'Улучшение добычи дерева',
'Повышает добычу дерева на 20%',
{ wood: 100, gold: 50 },
() => {
const building = this.game.buildings.find(b => b.name === 'Лесопилка');
building.increment *= 1.2;
}
),
new Technology(
'Улучшение добычи железа',
'Повышает добычу железа на 20%',
{ iron: 100, gold: 50 },
() => {
const building = this.game.buildings.find(b => b.name === 'Железная Шахта');
building.increment *= 1.2;
}
),
new Technology(
'Улучшение фермы',
'Повышает добычу еды на 20%',
{ food: 100, gold: 50 },
() => {
const building = this.game.buildings.find(b => b.name === 'Ферма');
building.increment *= 1.2;
}
),
new Technology(
'Продвинутая военная подготовка',
'Повышает уровень войск на 1',
{ copper: 200, gold: 100 },
() => {
this.game.castle.upgradeTroops(this.resourceManager);
}
),
new Technology(
'Укрепление замка',
'Увеличивает здоровье замка на 200',
{ stone: 150, gold: 100 },
() => {
this.game.castle.castleHealth += 200;
this.ui.updateCastleHealth(this.game.castle.castleHealth);
}
),
// Новые 8 технологий
new Technology(
'Улучшенная обработка железа',
'Повышает добычу железа на 30%',
{ iron: 200, gold: 100 },
() => {
const building = this.game.buildings.find(b => b.name === 'Железная Шахта');
building.increment *= 1.3;
}
),
new Technology(
'Расширенное сельское хозяйство',
'Повышает добычу еды на 25%',
{ food: 200, wood: 100, gold: 100 },
() => {
const building = this.game.buildings.find(b => b.name === 'Ферма');
building.increment *= 1.25;
}
),
new Technology(
'Быстрый найм',
'Снижает стоимость найма войск на 15%',
{ gold: 300, copper: 150 },
() => {
this.game.troopCostMultiplier *= 0.85;
}
),
new Technology(
'Улучшенная логистика',
'Увеличивает скорость перемещения войск на 20%',
{ gold: 200, food: 150 },
() => {
this.game.troopMovementSpeedMultiplier *= 1.2;
}
),
new Technology(
'Продвинутая кузница',
'Увеличивает урон войск на 20%',
{ iron: 300, copper: 200, gold: 150 },
() => {
this.game.troopDamageMultiplier *= 1.2;
}
),
new Technology(
'Укрепление стен',
'Увеличивает здоровье замка на 300',
{ stone: 250, gold: 150 },
() => {
this.game.castle.castleHealth += 300;
this.ui.updateCastleHealth(this.game.castle.castleHealth);
}
),
new Technology(
'Оптимизация добычи меди',
'Повышает добычу меди на 25%',
{ copper: 150, gold: 100 },
() => {
const building = this.game.buildings.find(b => b.name === 'Медная Шахта');
building.increment *= 1.25;
}
),
new Technology(
'Экономия ресурсов',
'Снижает стоимость улучшений зданий на 15%',
{ gold: 250 },
() => {
for (const building of this.game.buildings) {
building.costAmount *= 0.85;
}
}
),
new Technology(
'Продвинутая разведка',
'Раскрывает больше информации о гексах противника',
{ gold: 200, food: 100 },
() => {
// Логика раскрытия дополнительной информации
}
),
new Technology(
'Улучшенная торговля',
'Снижает цены при торговле на 10%',
{ gold: 150, wood: 100 },
() => {
for (const resource in this.game.tradeManager.tradeRates) {
this.game.tradeManager.tradeRates[resource] *= 0.9;
}
}
)
// Еще 3 технологии при необходимости...
];
}
openTechTree() {
this.ui.techTreeContainer.innerHTML = '';
for (const tech of this.technologies) {
const techNode = document.createElement('div');
techNode.className = 'techNode';
if (tech.unlocked) {
techNode.classList.add('unlocked');
} else {
techNode.classList.add('locked');
}
techNode.innerHTML = `<h4>${tech.name}</h4><p>${tech.description}</p>`;
if (!tech.unlocked) {
const button = document.createElement('button');
button.innerText = 'Исследовать';
button.onclick = () => {
this.researchTechnology(tech);
};
techNode.appendChild(button);
}
this.ui.techTreeContainer.appendChild(techNode);
}
this.ui.showTechModal();
}
researchTechnology(tech) {
const canResearch = Object.keys(tech.cost).every(resource => this.resourceManager.get(resource) >= tech.cost[resource]);
if (canResearch) {
Object.keys(tech.cost).forEach(resource => {
this.resourceManager.subtract(resource, tech.cost[resource]);
});
tech.unlocked = true;
tech.effect();
this.ui.showNotification(`Технология ${tech.name} исследована!`);
this.openTechTree();
} else {
this.ui.displayAlert('Недостаточно ресурсов для исследования технологии!');
}
}
saveState() {
return this.technologies.map(tech => ({
name: tech.name,
unlocked: tech.unlocked
}));
}
loadState(savedTechnologies) {
for (const savedTech of savedTechnologies) {
const tech = this.technologies.find(t => t.name === savedTech.name);
if (tech) {
tech.unlocked = savedTech.unlocked;
if (tech.unlocked) {
tech.effect();
}
}
}
}
// Класс управления торговлей
class TradeManager {
constructor(ui, resourceManager) {
this.ui = ui;
this.resourceManager = resourceManager;
this.tradeRates = {
wood: 1,
iron: 2,
food: 1.5,
copper: 3,
gold: 5
};
this.tradeData = {};
}
openTradeWindow() {
const tradeTable = document.getElementById('tradeTable');
tradeTable.innerHTML = `
<tr>
<th>Ресурс</th>
<th>Имеется</th>
<th>Купить</th>
<th>Продать</th>
</tr>
`;
for (const resource in this.tradeRates) {
const row = document.createElement('tr');
row.innerHTML = `
<td>${this.ui.capitalize(resource)}</td>
<td>${Math.floor(this.resourceManager.get(resource))}</td>
<td><input type="number" id="buy_${resource}" min="0" value="0"></td>
<td><input type="number" id="sell_${resource}" min="0" value="0"></td>
`;
tradeTable.appendChild(row);
}
this.ui.showTradeModal();
}
confirmTrade() {
for (const resource in this.tradeRates) {
const buyAmount = parseInt(document.getElementById(`buy_${resource}`).value) || 0;
const sellAmount = parseInt(document.getElementById(`sell_${resource}`).value) || 0;
const goldCost = buyAmount * this.tradeRates[resource];
const goldGain = sellAmount * this.tradeRates[resource];
if (buyAmount > 0) {
if (this.resourceManager.get('gold') >= goldCost) {
this.resourceManager.subtract('gold', goldCost);
this.resourceManager.add(resource, buyAmount);
} else {
this.ui.displayAlert(`Недостаточно золота для покупки ${buyAmount} ${resource}!`);
}
}
if (sellAmount > 0) {
if (this.resourceManager.get(resource) >= sellAmount) {
this.resourceManager.subtract(resource, sellAmount);
this.resourceManager.add('gold', goldGain);
} else {
this.ui.displayAlert(`Недостаточно ${resource} для продажи ${sellAmount} единиц!`);
}
}
}
this.ui.hideTradeModal();
this.ui.showNotification('Торговля завершена.');
}
// Запуск игры
window.onload = () => {
const game = new Game();
};
Конечно! Я добавлю в базовые ресурсы население для бота, чтобы он не мог нанимать армию без населения, так же как и игрок. Также сбалансирую его логику.
Вот изменения, которые необходимо внести в код:
Добавить население в Castle бота:
Убедимся, что у замка бота есть свойство population. В классе Castle это уже предусмотрено:
class Castle {
constructor(hex, ui, owner) {
// ...
this.population = 10; // Начальное население
// ...
}
}
Рост населения бота:
В методе startResourceGeneration класса AIPlayer добавим рост населения:
class AIPlayer {
// ...
startResourceGeneration() {
// ...
setInterval(() => {
const newResidents = this.castle.level;
this.castle.population += newResidents;
}, 10000);
}
// ...
}
Реализовать метод найма войск для бота:
Добавим метод hireTroops в класс AIPlayer, который будет проверять наличие ресурсов и населения перед наймом войск:
class AIPlayer {
// ...
hireTroops(amount) {
const costGold = 50 * amount * this.game.troopCostMultiplier;
const costCopper = 20 * amount * this.game.troopCostMultiplier;
if (
this.resourceManager.get('gold') >= costGold &&
this.resourceManager.get('copper') >= costCopper &&
this.castle.population >= amount
) {
this.resourceManager.subtract('gold', costGold);
this.resourceManager.subtract('copper', costCopper);
this.castle.population -= amount;
this.castle.soldiers += amount;
this.game.ui.logEvent(`Бот нанял ${amount} войск.`);
}
}
// ...
}
Изменить логику бота для найма войск:
В методе considerUpgrades добавим логику для найма войск:
class AIPlayer {
// ...
considerUpgrades() {
// Существующая логика улучшений
// ...
// Логика найма войск
const desiredTroopCount = this.castle.level * 10;
if (this.castle.soldiers < desiredTroopCount) {
const amountToHire = desiredTroopCount - this.castle.soldiers;
this.hireTroops(amountToHire);
}
}
// ...
}
Изменить размещение войск в форте:
В методе buildFort изменим код, чтобы бот размещал войска в форте только при наличии достаточного количества солдат:
class AIPlayer {
// ...
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;
// Размещение войск
const desiredTroops = this.castle.level * 5 * this.castle.troopLevel;
const troopsToAssign = Math.min(desiredTroops, this.castle.soldiers);
if (troopsToAssign > 0) {
hex.troops = troopsToAssign;
this.castle.soldiers -= troopsToAssign;
this.game.ui.logEvent(`Бот построил форт и разместил ${troopsToAssign} войск на гексе (${hex.row}, ${hex.col}).`);
} else {
hex.troops = 0;
this.game.ui.logEvent(`Бот построил форт на гексе (${hex.row}, ${hex.col}), но недостаточно войск для размещения.`);
}
}
}
// ...
}
Добавить распределение войск по фортам:
Создадим метод distributeTroops, который будет распределять доступные войска по фортам:
class AIPlayer {
// ...
distributeTroops() {
const desiredTroopsPerFort = this.castle.level * 5 * this.castle.troopLevel;
for (const hex of this.hexes) {
if (hex.hasFort) {
const troopsNeeded = desiredTroopsPerFort - hex.troops;
if (troopsNeeded > 0 && this.castle.soldiers > 0) {
const troopsToAssign = Math.min(troopsNeeded, this.castle.soldiers);
hex.troops += troopsToAssign;
this.castle.soldiers -= troopsToAssign;
this.game.ui.logEvent(`Бот добавил ${troopsToAssign} войск на гекс (${hex.row}, ${hex.col}).`);
}
}
}
}
// ...
}
Вызовем этот метод после найма войск в considerUpgrades:
class AIPlayer {
// ...
considerUpgrades() {
// Существующая логика улучшений
// ...
// Логика найма войск
const desiredTroopCount = this.castle.level * 10;
if (this.castle.soldiers < desiredTroopCount) {
const amountToHire = desiredTroopCount - this.castle.soldiers;
this.hireTroops(amountToHire);
}
// Распределение войск
this.distributeTroops();
}
// ...
}
Добавить потребление еды ботом:
В методе startResourceGeneration добавим потребление еды войсками бота и логику их гибели при недостатке еды:
class AIPlayer {
// ...
startResourceGeneration() {
// Существующие интервалы
// ...
// Потребление еды войсками
setInterval(() => {
const foodConsumption = this.castle.soldiers * 0.01;
if (this.resourceManager.get('food') >= foodConsumption) {
this.resourceManager.subtract('food', foodConsumption);
} else {
// Недостаточно еды, войска начинают умирать
const lostSoldiers = Math.ceil(this.castle.soldiers * 0.1);
this.castle.soldiers -= lostSoldiers;
// Уменьшаем войска на гексах
for (const hex of this.hexes) {
if (hex.owner === 'bot' && hex.troops > 0) {
const lostTroops = Math.min(hex.troops, lostSoldiers);
hex.troops -= lostTroops;
if (hex.troops <= 0) {
hex.troops = 0;
}
}
}
this.game.ui.logEvent(`У бота ${lostSoldiers} солдат умерло от голода. Осталось войск: ${this.castle.soldiers}`);
}
}, 1000); // Каждую секунду
}
// ...
}
Обновить логику атаки бота:
Убедимся, что бот атакует только при наличии достаточного количества войск:
class AIPlayer {
// ...
considerAttack() {
for (const hex of this.hexes) {
if (hex.troops > 0) {
const neighbors = this.game.getNeighbors(hex);
for (const neighbor of neighbors) {
if (neighbor.owner === 'player') {
if (!neighbor.isUnderAttack) {
this.attackHex(hex, neighbor);
}
}
}
}
}
}
// ...
}
Учесть потери войск при сражениях:
В методе attackHex убедимся, что после сражения войска бота корректно уменьшаются:
class AIPlayer {
// ...
attackHex(fromHex, toHex) {
// ...
setTimeout(() => {
const battleResult = this.game.battle(fromHex.troops, toHex.troops, this.castle.troopLevel, this.game.castle.troopLevel);
// Удаляем данные об атакующих войсках
toHex.attackingTroops = toHex.attackingTroops.filter(troop => troop !== attackingTroop);
if (battleResult.winner === 'attacker') {
toHex.owner = 'bot';
toHex.owned = true;
toHex.troops = battleResult.remainingTroops;
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);
}
} else {
toHex.troops = battleResult.remainingDefenderTroops || 0;
fromHex.troops = 0;
toHex.isUnderAttack = false;
toHex.captureTimer = null;
toHex.captureTimeRemaining = 0;
this.game.ui.logEvent(`Бот не смог захватить гекс (${toHex.row}, ${toHex.col}).`);
}
}, captureTime);
}
// ...
}
Балансировка логики бота:
Теперь бот не может нанимать войска без населения и ограничен ресурсами, как и игрок. Это делает игру более сбалансированной.
Итоговый результат:
Мы добавили население в базовые ресурсы бота и изменили его логику так, чтобы он не мог нанимать армию без достаточного населения, аналогично игроку. Также были внесены изменения для балансировки его поведения в игре.
Copy first response
Not yet included in a published release.