<!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 {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background-color: #222;
font-family: 'Arial', sans-serif;
color: #eee;
overflow: hidden; /* Prevent scrollbars */
}
#game-container {
position: relative;
width: 800px;
height: 600px;
border: 5px solid #555;
background-color: #333;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.7);
overflow: hidden; /* Keep game elements inside */
}
#game-canvas {
display: block;
background-color: #1a1a1a;
position: absolute;
top: 0;
left: 0;
}
#ui-container {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
display: flex;
justify-content: space-between;
align-items: flex-start;
font-size: 1.2em;
z-index: 10;
pointer-events: none; /* Allow clicks to pass through to canvas */
}
#health-bar-container {
width: 200px;
height: 20px;
background-color: #555;
border: 1px solid #777;
border-radius: 5px;
overflow: hidden;
box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.5);
position: relative;
}
#health-bar {
width: 100%;
height: 100%;
background-color: #4CAF50; /* Green */
transition: width 0.2s ease-out;
}
#health-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-weight: bold;
font-size: 0.9em;
text-shadow: 1px 1px 2px black;
}
#game-over-screen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #eee;
font-size: 2em;
text-align: center;
z-index: 20;
opacity: 0;
visibility: hidden;
transition: opacity 0.5s ease;
}
#game-over-screen.active {
opacity: 1;
visibility: visible;
}
#restart-button {
padding: 15px 30px;
font-size: 1.2em;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin-top: 20px;
transition: background-color 0.3s ease, transform 0.1s ease;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}
#restart-button:hover {
background-color: #0056b3;
transform: translateY(-2px);
}
#restart-button:active {
background-color: #00408f;
transform: translateY(0);
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="game-canvas" width="800" height="600"></canvas>
<div id="ui-container">
<div>Время: <span id="time-display">0.00</span>s</div>
<div id="health-bar-container">
<div id="health-bar"></div>
<span id="health-text">100 HP</span>
</div>
<div>Врагов уничтожено: <span id="score-display">0</span></div>
</div>
<div id="game-over-screen">
<h1>ИГРА ОКОНЧЕНА!</h1>
<p>Вы продержались: <span id="final-time">0.00</span> секунд</p>
<p>Врагов уничтожено: <span id="final-score">0</span></p>
<button id="restart-button">Начать заново</button>
</div>
</div>
<script>
// === Настройки игры ===
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
const PLAYER_SIZE = 30;
const PLAYER_SPEED = 200; // px/sec
const ENEMY_SIZE = 25;
let ENEMY_SPEED = 100; // px/sec, initial
const ENEMY_DAMAGE = 10;
const ENEMY_SPAWN_INTERVAL_MIN = 3000; // ms
const ENEMY_SPAWN_INTERVAL_MAX = 5000; // ms
const BONUS_SIZE = 20;
const BONUS_SPAWN_INTERVAL_MIN = 8000; // ms
const BONUS_SPAWN_INTERVAL_MAX = 12000; // ms
const HEALTH_BONUS_AMOUNT = 25;
const SLOW_MOTION_DURATION = 5000; // ms
const INVULNERABILITY_DURATION = 3000; // ms
const DAMAGE_BLINK_DURATION = 200; // ms
const DIFFICULTY_INCREASE_INTERVAL = 15000; // ms
const DIFFICULTY_ENEMY_SPEED_INCREASE_PERCENT = 0.05; // 5%
const DIFFICULTY_ENEMY_SPAWN_RATE_DECREASE_PERCENT = 0.05; // 5%
// === Игровые элементы DOM ===
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const timeDisplay = document.getElementById('time-display');
const healthBar = document.getElementById('health-bar');
const healthText = document.getElementById('health-text');
const scoreDisplay = document.getElementById('score-display');
const gameOverScreen = document.getElementById('game-over-screen');
const finalTimeDisplay = document.getElementById('final-time');
const finalScoreDisplay = document.getElementById('final-score');
const restartButton = document.getElementById('restart-button');
// === Переменные состояния игры ===
let gameRunning = false;
let lastFrameTime = 0;
let gameTime = 0; // ms
let enemies = [];
let bonuses = [];
let keysPressed = {};
let player = {
x: CANVAS_WIDTH / 2 - PLAYER_SIZE / 2,
y: CANVAS_HEIGHT / 2 - PLAYER_SIZE / 2,
dx: 0,
dy: 0,
size: PLAYER_SIZE,
color: 'lightgreen',
hp: 100,
isInvulnerable: false,
invulnerableTimer: 0,
isBlinking: false,
blinkTimer: 0
};
let enemySpawnTimer = 0;
let nextEnemySpawnTime = 0;
let bonusSpawnTimer = 0;
let nextBonusSpawnTime = 0;
let destroyedEnemiesCount = 0;
let slowMotionActive = false;
let slowMotionTimer = 0;
let difficultyTimer = 0;
// === Инициализация игры ===
function initGame() {
// Сброс всех переменных
gameRunning = true;
lastFrameTime = 0;
gameTime = 0;
enemies = [];
bonuses = [];
keysPressed = {};
player = {
x: CANVAS_WIDTH / 2 - PLAYER_SIZE / 2,
y: CANVAS_HEIGHT / 2 - PLAYER_SIZE / 2,
dx: 0,
dy: 0,
size: PLAYER_SIZE,
color: 'lightgreen',
hp: 100,
isInvulnerable: false,
invulnerableTimer: 0,
isBlinking: false,
blinkTimer: 0
};
ENEMY_SPEED = 100; // Reset speed
enemySpawnTimer = 0;
nextEnemySpawnTime = getRandomSpawnTime(ENEMY_SPAWN_INTERVAL_MIN, ENEMY_SPAWN_INTERVAL_MAX);
bonusSpawnTimer = 0;
nextBonusSpawnTime = getRandomSpawnTime(BONUS_SPAWN_INTERVAL_MIN, BONUS_SPAWN_INTERVAL_MAX);
destroyedEnemiesCount = 0;
slowMotionActive = false;
slowMotionTimer = 0;
difficultyTimer = 0;
// Скрытие экрана Game Over
gameOverScreen.classList.remove('active');
// Обновление UI
updateUI();
// Запуск игрового цикла
requestAnimationFrame(gameLoop);
}
// === Игровой цикл ===
function gameLoop(timestamp) {
if (!lastFrameTime) lastFrameTime = timestamp;
const deltaTime = timestamp - lastFrameTime; // Время в миллисекундах с последнего кадра
lastFrameTime = timestamp;
if (gameRunning) {
gameTime += deltaTime;
difficultyTimer += deltaTime;
updatePlayer(deltaTime);
updateEnemies(deltaTime);
updateBonuses(deltaTime);
handleSpawns(deltaTime);
checkCollisions();
handleTimers(deltaTime);
updateDifficulty();
updateUI();
if (player.hp <= 0) {
endGame();
}
}
drawGame();
requestAnimationFrame(gameLoop);
}
// === Обновление игровых объектов ===
function updatePlayer(deltaTime) {
const playerSpeed = PLAYER_SPEED * (deltaTime / 1000); // Скорость в px за кадр
player.dx = 0;
player.dy = 0;
if (keysPressed['KeyW']) player.dy = -playerSpeed;
if (keysPressed['KeyS']) player.dy = playerSpeed;
if (keysPressed['KeyA']) player.dx = -playerSpeed;
if (keysPressed['KeyD']) player.dx = playerSpeed;
// Нормализация диагонального движения
if (player.dx !== 0 && player.dy !== 0) {
const magnitude = Math.sqrt(player.dx * player.dx + player.dy * player.dy);
player.dx = (player.dx / magnitude) * playerSpeed;
player.dy = (player.dy / magnitude) * playerSpeed;
}
player.x += player.dx;
player.y += player.dy;
// Ограничение игрока в пределах поля
player.x = Math.max(0, Math.min(CANVAS_WIDTH - player.size, player.x));
player.y = Math.max(0, Math.min(CANVAS_HEIGHT - player.size, player.y));
// Обновление таймера мигания
if (player.isBlinking) {
player.blinkTimer -= deltaTime;
if (player.blinkTimer <= 0) {
player.isBlinking = false;
}
}
}
function updateEnemies(deltaTime) {
const currentEnemySpeed = ENEMY_SPEED * (slowMotionActive ? 0.5 : 1); // Замедление врагов
for (let i = enemies.length - 1; i >= 0; i--) {
const enemy = enemies[i];
const enemyMovement = currentEnemySpeed * (deltaTime / 1000);
if (enemy.direction === 'horizontal') {
enemy.x += enemy.dx * enemyMovement;
if (enemy.x <= 0 || enemy.x + enemy.size >= CANVAS_WIDTH) {
enemy.dx *= -1; // Отскок от границ
enemy.x = Math.max(0, Math.min(CANVAS_WIDTH - enemy.size, enemy.x)); // Коррекция положения
}
} else { // vertical
enemy.y += enemy.dy * enemyMovement;
if (enemy.y <= 0 || enemy.y + enemy.size >= CANVAS_HEIGHT) {
enemy.dy *= -1; // Отскок от границ
enemy.y = Math.max(0, Math.min(CANVAS_HEIGHT - enemy.size, enemy.y)); // Коррекция положения
}
}
}
}
function updateBonuses(deltaTime) {
// Бонусы не движутся, но если нужно, можно добавить логику исчезновения через время
}
function handleSpawns(deltaTime) {
enemySpawnTimer += deltaTime;
if (enemySpawnTimer >= nextEnemySpawnTime) {
spawnEnemy();
enemySpawnTimer = 0;
nextEnemySpawnTime = getRandomSpawnTime(ENEMY_SPAWN_INTERVAL_MIN, ENEMY_SPAWN_INTERVAL_MAX);
}
bonusSpawnTimer += deltaTime;
if (bonusSpawnTimer >= nextBonusSpawnTime) {
spawnBonus();
bonusSpawnTimer = 0;
nextBonusSpawnTime = getRandomSpawnTime(BONUS_SPAWN_INTERVAL_MIN, BONUS_SPAWN_INTERVAL_MAX);
}
}
function handleTimers(deltaTime) {
if (player.isInvulnerable) {
player.invulnerableTimer -= deltaTime;
if (player.invulnerableTimer <= 0) {
player.isInvulnerable = false;
}
}
if (slowMotionActive) {
slowMotionTimer -= deltaTime;
if (slowMotionTimer <= 0) {
slowMotionActive = false;
}
}
}
function updateDifficulty() {
if (difficultyTimer >= DIFFICULTY_INCREASE_INTERVAL) {
ENEMY_SPEED *= (1 + DIFFICULTY_ENEMY_SPEED_INCREASE_PERCENT);
// Можно также уменьшить интервал спавна, но это уже делается динамически
console.log(`Difficulty increased! Enemy speed: ${ENEMY_SPEED.toFixed(2)}`);
difficultyTimer = 0;
}
}
// === Спавн объектов ===
function getRandomSpawnTime(min, max) {
// Уменьшаем интервал спавна врагов с течением времени (увеличиваем скорость спавна)
let currentMin = min;
let currentMax = max;
const timePassedInMinutes = gameTime / 60000;
const difficultyFactor = 1 - Math.min(0.7, timePassedInMinutes * DIFFICULTY_ENEMY_SPAWN_RATE_DECREASE_PERCENT * 10); // Уменьшаем до 70% от начального интервала
if (min === ENEMY_SPAWN_INTERVAL_MIN) {
currentMin = Math.max(500, min * difficultyFactor); // Min 0.5 sec
currentMax = Math.max(1000, max * difficultyFactor); // Min 1 sec
}
return Math.random() * (currentMax - currentMin) + currentMin;
}
function spawnEnemy() {
const x = Math.random() * (CANVAS_WIDTH - ENEMY_SIZE);
const y = Math.random() * (CANVAS_HEIGHT - ENEMY_SIZE);
const direction = Math.random() < 0.5 ? 'horizontal' : 'vertical';
const dx = Math.random() < 0.5 ? 1 : -1; // -1 for left/up, 1 for right/down
const dy = Math.random() < 0.5 ? 1 : -1;
enemies.push({ x, y, dx, dy, size: ENEMY_SIZE, color: 'red', direction });
}
function spawnBonus() {
const x = Math.random() * (CANVAS_WIDTH - BONUS_SIZE);
const y = Math.random() * (CANVAS_HEIGHT - BONUS_SIZE);
const bonusTypes = ['health', 'slow', 'invulnerable', 'clear'];
const type = bonusTypes[Math.floor(Math.random() * bonusTypes.length)];
let color;
switch (type) {
case 'health': color = 'green'; break;
case 'slow': color = 'blue'; break;
case 'invulnerable': color = 'gold'; break;
case 'clear': color = 'purple'; break;
}
bonuses.push({ x, y, size: BONUS_SIZE, type, color });
}
// === Обработка столкновений ===
function checkCollision(obj1, obj2) {
return obj1.x < obj2.x + obj2.size &&
obj1.x + obj1.size > obj2.x &&
obj1.y < obj2.y + obj2.size &&
obj1.y + obj1.size > obj2.y;
}
function checkCollisions() {
// Игрок и враги
if (!player.isInvulnerable) {
for (let i = enemies.length - 1; i >= 0; i--) {
const enemy = enemies[i];
if (checkCollision(player, enemy)) {
player.hp -= ENEMY_DAMAGE;
player.isBlinking = true;
player.blinkTimer = DAMAGE_BLINK_DURATION;
// Можно удалить врага после столкновения или дать ему остаться
// enemies.splice(i, 1);
break; // Игрок получает урон только от одного врага за кадр
}
}
}
// Игрок и бонусы
for (let i = bonuses.length - 1; i >= 0; i--) {
const bonus = bonuses[i];
if (checkCollision(player, bonus)) {
applyBonus(bonus.type);
bonuses.splice(i, 1); // Удаляем бонус после подбора
}
}
}
function applyBonus(type) {
switch (type) {
case 'health':
player.hp = Math.min(100, player.hp + HEALTH_BONUS_AMOUNT);
console.log(`Bonus: Health +${HEALTH_BONUS_AMOUNT}`);
break;
case 'slow':
slowMotionActive = true;
slowMotionTimer = SLOW_MOTION_DURATION;
console.log(`Bonus: Slow Motion for ${SLOW_MOTION_DURATION / 1000}s`);
break;
case 'invulnerable':
player.isInvulnerable = true;
player.invulnerableTimer = INVULNERABILITY_DURATION;
console.log(`Bonus: Invulnerable for ${INVULNERABILITY_DURATION / 1000}s`);
break;
case 'clear':
destroyedEnemiesCount += enemies.length;
enemies = []; // Удаляем всех врагов
console.log('Bonus: All enemies cleared!');
break;
}
}
// === Отрисовка ===
function drawGame() {
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); // Очистка canvas
// Отрисовка игрока
ctx.save();
if (player.isInvulnerable) {
// Эффект неуязвимости: прозрачность
ctx.globalAlpha = 0.5 + 0.2 * Math.sin(gameTime / 100); // Пульсирующая прозрачность
} else if (player.isBlinking) {
// Эффект мигания при уроне
ctx.globalAlpha = (Math.floor(player.blinkTimer / 50) % 2 === 0) ? 0.2 : 1;
}
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.size, player.size);
ctx.restore(); // Восстанавливаем прозрачность по умолчанию
// Отрисовка врагов
enemies.forEach(enemy => {
ctx.fillStyle = enemy.color;
ctx.fillRect(enemy.x, enemy.y, enemy.size, enemy.size);
});
// Отрисовка бонусов (круги)
bonuses.forEach(bonus => {
ctx.fillStyle = bonus.color;
ctx.beginPath();
ctx.arc(bonus.x + bonus.size / 2, bonus.y + bonus.size / 2, bonus.size / 2, 0, Math.PI * 2);
ctx.fill();
});
}
// === Обновление UI ===
function updateUI() {
timeDisplay.textContent = (gameTime / 1000).toFixed(2);
healthBar.style.width = player.hp + '%';
healthBar.style.backgroundColor = player.hp > 60 ? '#4CAF50' : player.hp > 30 ? '#FFC107' : '#F44336'; // Цвет в зависимости от HP
healthText.textContent = `${player.hp} HP`;
scoreDisplay.textContent = destroyedEnemiesCount;
}
// === Завершение игры ===
function endGame() {
gameRunning = false;
gameOverScreen.classList.add('active');
finalTimeDisplay.textContent = (gameTime / 1000).toFixed(2);
finalScoreDisplay.textContent = destroyedEnemiesCount;
}
// === Обработчики событий ===
document.addEventListener('keydown', (e) => {
keysPressed[e.code] = true;
});
document.addEventListener('keyup', (e) => {
keysPressed[e.code] = false;
});
restartButton.addEventListener('click', () => {
initGame();
});
// === Запуск игры при загрузке ===
window.onload = initGame;
</script>
</body>
</html>