Below is the updated code with the requested features:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>История развития электроники</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #eef0f3;
margin: 0;
padding: 0;
}
#game-container {
width: 1000px;
margin: 0 auto;
padding: 20px;
}
#tech-tree {
position: relative;
width: 100%;
height: 800px;
background-color: #ffffff;
border: 1px solid #ccc;
overflow: auto;
}
.tech-node {
position: absolute;
width: 120px;
text-align: center;
padding: 10px;
background-color: #dddddd;
border: 1px solid #aaa;
border-radius: 8px;
cursor: pointer;
}
.tech-node.unlocked {
background-color: #a0d468;
}
.tech-node.locked {
background-color: #dddddd;
}
.tech-node img {
max-width: 100%;
height: auto;
}
.tech-node p {
margin: 5px 0 0;
}
/* Линии между узлами */
.tech-line {
position: absolute;
width: 2px;
background-color: #333;
}
#resource-panel {
margin-top: 20px;
}
#build-processor {
margin-top: 20px;
}
#build-processor label {
display: block;
margin-top: 10px;
}
#build-processor input {
width: 100px;
}
#processor-result {
margin-top: 20px;
padding: 10px;
border: 1px solid #aaa;
background-color: #f7f7f7;
}
</style>
</head>
<body>
<div id="game-container">
<h1>История развития электроники</h1>
<div id="resource-panel">
<p>Ресурсы: <span id="resources">100</span></p>
<p>Время: <span id="timer">5:00</span></p>
</div>
<div id="tech-tree">
<!-- Узлы древа технологий будут добавлены здесь динамически -->
</div>
<div id="build-processor" style="display: none;">
<h2>Сборка собственного процессора</h2>
<form id="processor-form">
<label for="memory">Память (в килобайтах):</label>
<input type="number" id="memory" name="memory" min="1"><br>
<label for="cores">Количество ядер:</label>
<input type="number" id="cores" name="cores" min="1"><br>
<label for="clockSpeed">Тактовая частота (МГц):</label>
<input type="number" id="clockSpeed" name="clockSpeed" min="1"><br><br>
<button type="button" id="build-processor-button">Собрать процессор</button>
</form>
<div id="processor-result"></div>
</div>
</div>
<script>
// Данные технологий
const technologies = [
{
id: 1,
name: "Вакуумные лампы",
year: 1940,
prerequisites: [],
unlocked: true,
x: 50,
y: 50,
image: "https://static.auction.ru/offer_images/cmn8/2019/06/24/06/big/2/2WwcLhYGkKJ/lampa_6n3p_e_dvojnoj_miniatjurnyj_triod_povyshennoj_dolgovechnosti.jpg", // URL на изображение вакуумных ламп
cost: 10,
description: "Позволяет создавать первые электронные устройства."
},
{
id: 2,
name: "Транзисторы",
year: 1947,
prerequisites: [1],
unlocked: false,
x: 250,
y: 150,
image: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Transistor_KSY72.jpg/440px-Transistor_KSY72.jpg", // URL на изображение транзистора
cost: 20,
description: "Уменьшает размер и увеличивает эффективность устройств."
},
{
id: 3,
name: "Интегральные схемы",
year: 1958,
prerequisites: [2],
unlocked: false,
x: 450,
y: 250,
image: "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0e/Integrated_Circuit.jpg/320px-Integrated_Circuit.jpg", // URL на изображение интегральной схемы
cost: 30,
description: "Позволяет создавать сложные электронные системы."
},
{
id: 4,
name: "Микропроцессоры",
year: 1971,
prerequisites: [3],
unlocked: false,
x: 650,
y: 350,
image: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Intel_C4004.jpg/800px-Intel_C4004.jpg", // URL на изображение микропроцессора Intel 4004
cost: 40,
description: "Сердце компьютеров, выполняет вычислительные операции."
},
{
id: 5,
name: "Персональные компьютеры",
year: 1980,
prerequisites: [4],
unlocked: false,
x: 850,
y: 450,
image: "https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/IBM_PC_5150.jpg/640px-IBM_PC_5150.jpg", // URL на изображение IBM PC
cost: 50,
description: "Компьютеры становятся доступными для массового использования."
},
{
id: 6,
name: "Графические процессоры (GPU)",
year: 1999,
prerequisites: [5],
unlocked: false,
x: 1050,
y: 550,
image: "https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/ATI_Radeon_9800_Graphic_Card.jpg/640px-ATI_Radeon_9800_Graphic_Card.jpg", // URL на изображение GPU (ATI Radeon)
cost: 60,
description: "Используются для рендеринга графики и задач машинного обучения."
},
{
id: 7,
name: "Квантовые процессоры",
year: 2020,
prerequisites: [6],
unlocked: false,
x: 1250,
y: 650,
image: "https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/IBM_Q_system.jpg/800px-IBM_Q_system.jpg", // URL на изображение квантового процессора
cost: 100,
description: "Квантовые процессоры открывают новые возможности в вычислениях."
},
// Добавьте другие технологии по мере необходимости
];
// Переменные игры
let resources = 100;
// Таймер
let totalTime = 300; // Время в секундах (5 минут)
let timerInterval;
// Инициализация игры
function initGame() {
updateResources();
updateTimerDisplay();
renderTechTree();
startTimer();
startResourceGeneration();
}
// Обновление панели ресурсов
function updateResources() {
document.getElementById('resources').innerText = Math.floor(resources);
}
// Отрисовка древа технологий
function renderTechTree() {
const techTree = document.getElementById('tech-tree');
techTree.innerHTML = '';
// Сначала отрисуем линии между узлами
technologies.forEach(tech => {
tech.prerequisites.forEach(prereqId => {
const prereqTech = technologies.find(t => t.id === prereqId);
drawLine(prereqTech, tech);
});
});
// Затем отрисуем сами узлы
technologies.forEach(tech => {
const techNode = document.createElement('div');
techNode.classList.add('tech-node');
techNode.classList.add(tech.unlocked ? 'unlocked' : 'locked');
techNode.style.left = tech.x + 'px';
techNode.style.top = tech.y + 'px';
// Добавляем изображение технологии
const img = document.createElement('img');
img.src = tech.image;
img.alt = tech.name;
techNode.appendChild(img);
// Название технологии
const name = document.createElement('p');
name.innerText = tech.name;
techNode.appendChild(name);
// Обработчик клика по узлу
techNode.addEventListener('click', () => {
if (canUnlock(tech)) {
unlockTech(tech);
} else {
alert('Невозможно исследовать эту технологию. Проверьте требования и ресурсы.');
}
});
techTree.appendChild(techNode);
});
// Проверка, нужно ли показать секцию сборки процессора
const buildProcessorSection = document.getElementById('build-processor');
const microprocessorsTech = technologies.find(t => t.id === 4);
if (microprocessorsTech.unlocked) {
buildProcessorSection.style.display = 'block';
}
}
// Проверка возможности исследования технологии
function canUnlock(tech) {
if (tech.unlocked) return false;
// Проверяем, исследованы ли все необходимые технологии
for (let prereqId of tech.prerequisites) {
const prereqTech = technologies.find(t => t.id === prereqId);
if (!prereqTech.unlocked) return false;
}
// Проверяем, достаточно ли ресурсов
if (resources < tech.cost) return false;
return true;
}
// Разблокировка технологии
function unlockTech(tech) {
resources -= tech.cost;
tech.unlocked = true;
updateResources();
renderTechTree();
alert(`Вы исследовали технологию: ${tech.name}\n${tech.description}`);
}
// Функция для отрисовки линии между технологиями
function drawLine(startTech, endTech) {
const techTree = document.getElementById('tech-tree');
const line = document.createElement('div');
line.classList.add('tech-line');
// Вычисляем координаты
const x1 = startTech.x + 60; // 60 - половина ширины узла
const y1 = startTech.y + 60; // 60 - половина высоты узла
const x2 = endTech.x + 60;
const y2 = endTech.y + 60;
const length = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
// Устанавливаем стиль линии
line.style.left = x1 + 'px';
line.style.top = y1 + 'px';
line.style.width = length + 'px';
line.style.transformOrigin = '0 0';
const angle = Math.atan2(y2 - y1, x2 - x1) * (180 / Math.PI);
line.style.transform = `rotate(${angle}deg)`;
techTree.appendChild(line);
}
// Запуск таймера
function startTimer() {
timerInterval = setInterval(() => {
totalTime--;
updateTimerDisplay();
if (totalTime <= 0) {
clearInterval(timerInterval);
endGame();
}
}, 1000);
}
// Обновление отображения таймера
function updateTimerDisplay() {
const minutes = Math.floor(totalTime / 60);
const seconds = totalTime % 60;
document.getElementById('timer').innerText = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
}
// Генерация ресурсов со временем
function startResourceGeneration() {
setInterval(() => {
resources += 1; // Добавляем 1 ресурс каждую секунду
updateResources();
}, 1000);
}
// Обработка конца игры
function endGame() {
alert('Время вышло! Игра закончена.');
// Здесь можно добавить логику окончания игры, например, заблокировать дальнейшие действия
// Например, отключить кнопки или перенаправить на другую страницу
document.getElementById('build-processor-button').disabled = true;
}
// Обработчик сборки процессора
document.getElementById('build-processor-button').addEventListener('click', () => {
const memory = parseInt(document.getElementById('memory').value) || 0;
const cores = parseInt(document.getElementById('cores').value) || 0;
const clockSpeed = parseInt(document.getElementById('clockSpeed').value) || 0;
if (memory <= 0 || cores <= 0 || clockSpeed <= 0) {
alert('Пожалуйста, заполните все поля корректными значениями.');
return;
}
// Вычисляем производительность процессора (упрощенно)
const performance = (memory * 0.1) + (cores * clockSpeed);
const resultDiv = document.getElementById('processor-result');
resultDiv.innerHTML = `<p>Вы создали процессор с производительностью: ${performance.toFixed(2)}</p>`;
// Можно добавить затрату ресурсов на создание процессора
const processorCost = memory * 0.05 + cores * clockSpeed * 0.01;
if (resources >= processorCost) {
resources -= processorCost;
updateResources();
resultDiv.innerHTML += `<p>Стоимость создания: ${processorCost.toFixed(2)} ресурсов.</p>`;
} else {
alert('Недостаточно ресурсов для создания этого процессора.');
resultDiv.innerHTML = '';
}
});
// Запуск игры
document.addEventListener('DOMContentLoaded', initGame);
</script>
</body>
</html>
This code includes the following updates:
Resource Generation Over Time: Resources now increase by 1 every second.
Timer Implementation: A countdown timer of 5 minutes is displayed at the top. When the time runs out, the game ends.
Build Your Own Processor Section: After unlocking the "Микропроцессоры" technology, a new section appears where you can build your own processor by specifying memory, number of cores, and clock speed.
Processor Building Mechanics: When you input the specifications and click the "Собрать процессор" button, it calculates the performance and deducts the cost from your resources.
Feel free to adjust the parameters and values to better suit your game design.