Отличная и амбициозная концепция! Создать полную игру "Хроно-Инженер" с процедурной генерацией, сложными квантовыми эффектами и социальными элементами в одном HTML-файле — это огромная задача. Однако, я могу реализовать базовую механику, демонстрирующую управление временем и движение частиц, что станет прочной основой для дальнейшего развития.
Мы сосредоточимся на:
- Визуальном стиле: Минималистичный неон.
- Основной механике: Сетка, частицы, размещение зон времени (ускорение, замедление, обращение, барьеры).
- Игровых элементах: Частица, цель.
- Простой головоломке: Провести частицу к цели.
Вот код игры в одном HTML-файле:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Хроно-Инженер: Основы Времени</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #030612; /* Глубокий синий */
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
font-family: 'Consolas', monospace;
color: #E0E0FF; /* Светлый неоновый цвет */
user-select: none; /* Запретить выделение текста */
}
#game-container {
display: flex;
flex-direction: column;
align-items: center;
background-color: #050A1A; /* Чуть светлее фон для контейнера */
border: 2px solid #6600FF; /* Пурпурная рамка */
box-shadow: 0 0 15px rgba(102, 0, 255, 0.7); /* Неоновая тень */
padding: 20px;
border-radius: 10px;
}
canvas {
background-color: #030612; /* Фон холста */
border: 1px solid #00FFFF; /* Бирюзовая рамка */
box-shadow: 0 0 10px rgba(0, 255, 255, 0.5); /* Неоновая тень */
display: block;
margin-bottom: 20px;
}
#game-ui {
display: flex;
width: 100%;
justify-content: space-between;
margin-bottom: 15px;
font-size: 1.2em;
text-shadow: 0 0 5px #00FFFF;
}
#tool-palette {
display: flex;
gap: 10px;
margin-top: 15px;
}
.tool-button {
padding: 10px 15px;
background-color: #1A0538; /* Темно-пурпурный */
color: #E0E0FF;
border: 1px solid #9933FF; /* Светло-пурпурный */
border-radius: 5px;
cursor: pointer;
transition: all 0.2s ease;
font-size: 1em;
text-shadow: 0 0 5px #9933FF;
box-shadow: 0 0 8px rgba(153, 51, 255, 0.4);
}
.tool-button:hover {
background-color: #2D0850;
border-color: #CC66FF;
box-shadow: 0 0 15px rgba(204, 102, 255, 0.6);
transform: translateY(-2px);
}
.tool-button.active {
background-color: #4D0A80;
border-color: #FF99FF;
box-shadow: 0 0 20px rgba(255, 153, 255, 0.8);
transform: scale(1.05);
}
#instructions {
margin-top: 20px;
font-size: 0.9em;
color: #B0B0CC;
text-align: center;
line-height: 1.4;
}
#instructions strong {
color: #00FFFF;
text-shadow: 0 0 5px #00FFFF;
}
#reset-button {
margin-top: 20px;
padding: 10px 20px;
background-color: #330000; /* Темно-красный */
color: #FF8080;
border: 1px solid #FF0000;
border-radius: 5px;
cursor: pointer;
transition: all 0.2s ease;
font-size: 1em;
text-shadow: 0 0 5px #FF0000;
box-shadow: 0 0 8px rgba(255, 0, 0, 0.4);
}
#reset-button:hover {
background-color: #550000;
border-color: #FF3333;
box-shadow: 0 0 15px rgba(255, 51, 51, 0.6);
}
</style>
</head>
<body>
<div id="game-container">
<div id="game-ui">
<span id="level-display">Уровень: 1</span>
<span id="score-display">Счёт: 0</span>
</div>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<div id="tool-palette">
<button class="tool-button" id="tool-normal" data-tool="NORMAL">Пустота</button>
<button class="tool-button" id="tool-accel" data-tool="ACCEL">Ускорение</button>
<button class="tool-button" id="tool-slow" data-tool="SLOW">Замедление</button>
<button class="tool-button" id="tool-reverse" data-tool="REVERSE">Обращение</button>
<button class="tool-button" id="tool-barrier" data-tool="BARRIER">Барьер</button>
</div>
<button id="reset-button">Сбросить Уровень</button>
<div id="instructions">
<strong>Цель:</strong> Провести частицу (маленький фиолетовый круг) к цели (большой бирюзовый круг).<br>
<strong>Управление:</strong> Выберите инструмент и кликните на сетке, чтобы применить эффект. Повторный клик на ячейке с потоком изменяет его направление.
</div>
</div>
<script>
// --- Константы и настройки игры ---
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const levelDisplay = document.getElementById('level-display');
const scoreDisplay = document.getElementById('score-display');
const toolButtons = document.querySelectorAll('.tool-button');
const resetButton = document.getElementById('reset-button');
const GRID_SIZE = 20; // 20x20 ячеек
const CELL_SIZE = canvas.width / GRID_SIZE; // Размер одной ячейки в пикселях
const TIME_EFFECTS = {
NORMAL: { color: 'rgba(0, 0, 0, 0.0)', effect: 1.0, shadow: 'rgba(0, 0, 0, 0)' }, // Прозрачный, без эффекта
ACCEL: { color: '#00FF00', effect: 1.5, shadow: 'rgba(0, 255, 0, 0.7)' }, // Зеленый поток
SLOW: { color: '#0000FF', effect: 0.5, shadow: 'rgba(0, 0, 255, 0.7)' }, // Синий поток
REVERSE: { color: '#FF0000', effect: -1.0, shadow: 'rgba(255, 0, 0, 0.7)' }, // Красный поток
BARRIER: { color: '#FFD700', effect: 0.0, shadow: 'rgba(255, 215, 0, 0.7)' } // Золотой барьер
};
const DIRECTIONS = {
NONE: null,
UP: { dx: 0, dy: -1, angle: -Math.PI / 2 },
DOWN: { dx: 0, dy: 1, angle: Math.PI / 2 },
LEFT: { dx: -1, dy: 0, angle: Math.PI },
RIGHT: { dx: 1, dy: 0, angle: 0 }
};
const DIRECTION_ORDER = [DIRECTIONS.RIGHT, DIRECTIONS.DOWN, DIRECTIONS.LEFT, DIRECTIONS.UP, DIRECTIONS.NONE];
let gameGrid = []; // Сетка, хранящая типы временных эффектов
let currentTool = 'NORMAL';
let level = 1;
let score = 0;
let particle;
let target;
let startTime;
let isLevelComplete = false;
// --- Класс частицы ---
class Particle {
constructor(x, y, radius, color, speed) {
this.x = x * CELL_SIZE + CELL_SIZE / 2;
this.y = y * CELL_SIZE + CELL_SIZE / 2;
this.radius = radius;
this.color = color;
this.baseSpeed = speed;
this.vx = speed; // Начальная скорость по X
this.vy = 0; // Начальная скорость по Y
this.trail = [];
this.trailMaxLength = 50; // Длина следа
this.resetPoint = { x: this.x, y: this.y, vx: this.vx, vy: this.vy };
}
update() {
if (isLevelComplete) return;
// Добавить текущую позицию в след
this.trail.push({ x: this.x, y: this.y });
if (this.trail.length > this.trailMaxLength) {
this.trail.shift();
}
const gridX = Math.floor(this.x / CELL_SIZE);
const gridY = Math.floor(this.y / CELL_SIZE);
let cellEffect = TIME_EFFECTS.NORMAL.effect;
let cellDirection = DIRECTIONS.NONE;
if (gridX >= 0 && gridX < GRID_SIZE && gridY >= 0 && gridY < GRID_SIZE) {
const cell = gameGrid[gridY][gridX];
if (cell) {
cellEffect = TIME_EFFECTS[cell.type].effect;
cellDirection = DIRECTIONS[cell.direction];
if (cell.type === 'BARRIER') {
this.reset(); // Сброс при столкновении с барьером
return;
}
}
}
// Применить эффект скорости
let currentSpeedX = this.vx;
let currentSpeedY = this.vy;
if (cellDirection !== DIRECTIONS.NONE) {
// Если есть направленный поток, частица движется по его направлению
currentSpeedX = cellDirection.dx * this.baseSpeed;
currentSpeedY = cellDirection.dy * this.baseSpeed;
} else {
// Иначе, просто масштабируем текущую скорость
currentSpeedX *= Math.abs(cellEffect);
currentSpeedY *= Math.abs(cellEffect);
}
if (cellEffect < 0) { // Обращение времени
this.vx = -currentSpeedX;
this.vy = -currentSpeedY;
} else {
this.vx = currentSpeedX * cellEffect;
this.vy = currentSpeedY * cellEffect;
}
// Проверить, не слишком ли маленькая скорость, чтобы избежать застревания
if (Math.abs(this.vx) < 0.01 && Math.abs(this.vy) < 0.01) {
this.vx = this.baseSpeed; // Задать минимальную скорость
this.vy = 0;
}
this.x += this.vx;
this.y += this.vy;
// Проверка границ холста
if (this.x < 0 || this.x > canvas.width || this.y < 0 || this.y > canvas.height) {
this.reset();
}
}
draw() {
// Рисование следа
ctx.save();
ctx.shadowBlur = 10;
ctx.shadowColor = this.color;
for (let i = 0; i < this.trail.length; i++) {
const p = this.trail[i];
const alpha = i / this.trailMaxLength;
ctx.fillStyle = `rgba(150, 0, 255, ${alpha * 0.7})`; // Пурпурный след
ctx.beginPath();
ctx.arc(p.x, p.y, this.radius * (i / this.trailMaxLength * 0.5 + 0.5), 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
// Рисование самой частицы
ctx.save();
ctx.shadowBlur = 15;
ctx.shadowColor = this.color;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
reset() {
this.x = this.resetPoint.x;
this.y = this.resetPoint.y;
this.vx = this.resetPoint.vx;
this.vy = this.resetPoint.vy;
this.trail = [];
// Возможно, уменьшить счёт или увеличить "попытки"
}
}
// --- Уровни ---
const levels = [
// Уровень 1: Простой мост
{
start: { x: 1, y: 1 },
target: { x: 18, y: 10 },
initialGrid: [
// Можно задать начальные ячейки, но для простоты начнем с пустой
],
instructions: "Направьте частицу к цели. Попробуйте использовать 'Ускорение'."
},
// Уровень 2: Изгиб пути
{
start: { x: 1, y: 1 },
target: { x: 1, y: 18 },
initialGrid: [
{ x: 5, y: 1, type: 'ACCEL', direction: 'DOWN' },
{ x: 5, y: 5, type: 'ACCEL', direction: 'RIGHT' },
],
instructions: "Используйте комбинации потоков, чтобы изменить направление частицы."
},
// Уровень 3: Барьеры и обход
{
start: { x: 1, y: 10 },
target: { x: 18, y: 10 },
initialGrid: [
{ x: 8, y: 9, type: 'BARRIER' },
{ x: 8, y: 10, type: 'BARRIER' },
{ x: 8, y: 11, type: 'BARRIER' },
{ x: 9, y: 9, type: 'BARRIER' },
{ x: 9, y: 11, type: 'BARRIER' },
{ x: 10, y: 9, type: 'BARRIER' },
{ x: 10, y: 10, type: 'BARRIER' },
{ x: 10, y: 11, type: 'BARRIER' },
],
instructions: "Барьеры блокируют частицу. Создайте обходной путь."
},
// Уровень 4: Обращение времени
{
start: { x: 1, y: 1 },
target: { x: 1, y: 5 },
initialGrid: [
{ x: 10, y: 2, type: 'ACCEL', direction: 'RIGHT' },
{ x: 18, y: 2, type: 'REVERSE', direction: 'NONE' }, // Просто реверс
{ x: 10, y: 3, type: 'BARRIER' }, // Создать стену
{ x: 11, y: 3, type: 'BARRIER' },
{ x: 12, y: 3, type: 'BARRIER' },
{ x: 13, y: 3, type: 'BARRIER' },
{ x: 14, y: 3, type: 'BARRIER' },
{ x: 15, y: 3, type: 'BARRIER' },
{ x: 16, y: 3, type: 'BARRIER' },
],
instructions: "Используйте 'Обращение времени', чтобы частица пошла назад."
},
// Уровень 5: Комбинированный путь
{
start: { x: 1, y: 10 },
target: { x: 18, y: 18 },
initialGrid: [
{ x: 5, y: 10, type: 'ACCEL', direction: 'RIGHT' },
{ x: 10, y: 10, type: 'SLOW', direction: 'DOWN' },
{ x: 10, y: 15, type: 'ACCEL', direction: 'RIGHT' },
],
instructions: "Сочетайте различные эффекты для сложного пути."
}
// Здесь можно добавлять больше уровней
];
function loadLevel(levelNum) {
level = levelNum;
isLevelComplete = false;
levelDisplay.textContent = `Уровень: ${level}`;
scoreDisplay.textContent = `Счёт: ${score}`;
document.getElementById('instructions').innerHTML = levels[level - 1].instructions;
// Инициализация сетки
gameGrid = Array(GRID_SIZE).fill(null).map(() =>
Array(GRID_SIZE).fill(null).map(() => ({ type: 'NORMAL', direction: 'NONE' }))
);
// Размещение начальных элементов уровня
const currentLevelData = levels[level - 1];
particle = new Particle(currentLevelData.start.x, currentLevelData.start.y, 8, '#9900FF', 0.5); // Фиолетовая частица
particle.resetPoint = {
x: currentLevelData.start.x * CELL_SIZE + CELL_SIZE / 2,
y: currentLevelData.start.y * CELL_SIZE + CELL_SIZE / 2,
vx: 0.5, vy: 0 // Возвращаем к начальной скорости
};
particle.reset(); // Сброс частицы в начальную позицию
target = {
x: currentLevelData.target.x * CELL_SIZE + CELL_SIZE / 2,
y: currentLevelData.target.y * CELL_SIZE + CELL_SIZE / 2,
radius: CELL_SIZE / 2 * 0.8, // Цель чуть меньше ячейки
color: '#00FFFF' // Бирюзовая цель
};
// Применение начальных элементов сетки уровня
currentLevelData.initialGrid.forEach(item => {
if (item.x >= 0 && item.x < GRID_SIZE && item.y >= 0 && item.y < GRID_SIZE) {
gameGrid[item.y][item.x] = { type: item.type, direction: item.direction || 'NONE' };
}
});
}
// --- Рисование ---
function drawGrid() {
ctx.strokeStyle = 'rgba(0, 255, 255, 0.1)'; // Полупрозрачный бирюзовый
ctx.lineWidth = 0.5;
for (let i = 0; i <= GRID_SIZE; i++) {
ctx.beginPath();
ctx.moveTo(i * CELL_SIZE, 0);
ctx.lineTo(i * CELL_SIZE, canvas.height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i * CELL_SIZE);
ctx.lineTo(canvas.width, i * CELL_SIZE);
ctx.stroke();
}
}
function drawTimeGridEffects() {
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const cell = gameGrid[y][x];
const effect = TIME_EFFECTS[cell.type];
if (effect.type === 'NORMAL') continue; // Не рисовать пустые ячейки
ctx.save();
ctx.shadowBlur = 10;
ctx.shadowColor = effect.shadow;
// Рисуем фон ячейки
ctx.fillStyle = effect.color + '50'; // Полупрозрачный цвет эффекта
ctx.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
// Рисуем стрелку направления, если есть
const direction = DIRECTIONS[cell.direction];
if (direction !== DIRECTIONS.NONE && cell.type !== 'BARRIER') {
const centerX = x * CELL_SIZE + CELL_SIZE / 2;
const centerY = y * CELL_SIZE + CELL_SIZE / 2;
const arrowSize = CELL_SIZE * 0.3;
ctx.translate(centerX, centerY);
ctx.rotate(direction.angle);
ctx.strokeStyle = effect.color;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(-arrowSize, 0);
ctx.lineTo(arrowSize, 0);
ctx.lineTo(arrowSize * 0.7, -arrowSize * 0.3);
ctx.moveTo(arrowSize, 0);
ctx.lineTo(arrowSize * 0.7, arrowSize * 0.3);
ctx.stroke();
ctx.restore(); // Важно восстановить после translate/rotate
} else {
ctx.restore(); // Восстановить, если не было translate/rotate
}
}
}
}
function drawTarget() {
ctx.save();
ctx.shadowBlur = 20;
ctx.shadowColor = target.color;
ctx.fillStyle = target.color;
ctx.beginPath();
ctx.arc(target.x, target.y, target.radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
function gameDraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Очистить холст
drawGrid();
drawTimeGridEffects();
drawTarget();
particle.draw();
}
// --- Игровая логика ---
function gameUpdate() {
if (isLevelComplete) return;
particle.update();
// Проверка попадания в цель
const distSq = (particle.x - target.x)**2 + (particle.y - target.y)**2;
if (distSq < (particle.radius + target.radius)**2) {
isLevelComplete = true;
score += 100 + Math.floor((performance.now() - startTime) / 1000); // Бонус за время
scoreDisplay.textContent = `Счёт: ${score}`;
setTimeout(() => {
alert(`Уровень ${level} завершен!`);
level++;
if (level <= levels.length) {
loadLevel(level);
} else {
alert("Поздравляем! Вы прошли все доступные уровни!");
level = 1; // Начать заново
score = 0;
loadLevel(level);
}
startTime = performance.now(); // Сброс времени для нового уровня
}, 500);
}
}
// --- Главный игровой цикл ---
let lastTime = 0;
function gameLoop(currentTime) {
requestAnimationFrame(gameLoop);
const deltaTime = currentTime - lastTime;
// Обновлять только если прошло достаточно времени (ограничиваем FPS для стабильности)
if (deltaTime > 1000 / 60) { // Около 60 FPS
gameUpdate();
gameDraw();
lastTime = currentTime;
}
}
// --- Обработчики событий ---
canvas.addEventListener('click', (event) => {
if (isLevelComplete) return;
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
const gridX = Math.floor(mouseX / CELL_SIZE);
const gridY = Math.floor(mouseY / CELL_SIZE);
if (gridX >= 0 && gridX < GRID_SIZE && gridY >= 0 && gridY < GRID_SIZE) {
const currentCell = gameGrid[gridY][gridX];
if (currentTool === 'NORMAL') {
currentCell.type = 'NORMAL';
currentCell.direction = 'NONE';
} else if (currentTool === 'BARRIER') {
currentCell.type = 'BARRIER';
currentCell.direction = 'NONE';
} else {
// Если выбран инструмент потока
if (currentCell.type === currentTool) {
// Если уже этот тип, переключаем направление
let currentDirIndex = DIRECTION_ORDER.indexOf(DIRECTIONS[currentCell.direction]);
currentDirIndex = (currentDirIndex + 1) % DIRECTION_ORDER.length;
currentCell.direction = Object.keys(DIRECTIONS).find(key => DIRECTIONS[key] === DIRECTION_ORDER[currentDirIndex]);
} else {
// Иначе, устанавливаем новый тип и начальное направление (по умолчанию RIGHT)
currentCell.type = currentTool;
currentCell.direction = 'RIGHT';
}
}
particle.reset(); // Сбросить частицу после изменения сетки
}
});
toolButtons.forEach(button => {
button.addEventListener('click', () => {
toolButtons.forEach(btn => btn.classList.remove('active'));
button.classList.add('active');
currentTool = button.dataset.tool;
});
});
resetButton.addEventListener('click', () => {
loadLevel(level); // Перезагрузить текущий уровень
startTime = performance.now();
});
// --- Инициализация игры ---
function initGame() {
loadLevel(1); // Загружаем первый уровень
startTime = performance.now(); // Засекаем время начала уровня
document.getElementById('tool-normal').click(); // Активируем инструмент "Пустота" по умолчанию
gameLoop(0); // Запускаем игровой цикл
}
initGame();
</script>
</body>
</html>