Вот простой 2D-игра "Танки" на JavaScript с использованием HTML5 Canvas. Я добавил продвинутый ИИ для вражеских танков, который использует:
- A алгоритм* для поиска пути к игроку, избегая препятствий.
- Finite State Machine (FSM) для управления поведением: патрулирование, преследование, стрельба и уклонение.
- Предсказание действий: ИИ анализирует траекторию пуль и пытается уклониться.
Игра включает:
- Игровое поле с препятствиями (стены).
- Танк игрока (управление клавиатурой).
- Несколько вражеских танков с ИИ.
- Систему стрельбы и столкновений.
- Счет, здоровье и конец игры.
Сохраните код в файл tanks_game.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: #222; /* Темный фон */
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
color: #fff;
font-family: sans-serif;
}
canvas {
border: 2px solid #fff;
}
#ui {
position: absolute;
top: 10px;
left: 10px;
font-size: 16px;
}
#gameOver {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.8);
padding: 20px;
border-radius: 10px;
text-align: center;
display: none;
}
</style>
</head>
<body>
<div id="ui">Здоровье: <span id="health">100</span> | Счет: <span id="score">0</span></div>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<div id="gameOver">
<h2>Конец игры!</h2>
<p>Ваш счет: <span id="finalScore">0</span></p>
<button onclick="restartGame()">Играть снова</button>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const healthSpan = document.getElementById('health');
const scoreSpan = document.getElementById('score');
const finalScoreSpan = document.getElementById('finalScore');
// Константы
const TILE_SIZE = 40;
const MAP_WIDTH = canvas.width / TILE_SIZE;
const MAP_HEIGHT = canvas.height / TILE_SIZE;
const PLAYER_SPEED = 2;
const TANK_SPEED = 1.5;
const BULLET_SPEED = 5;
const FIRE_RATE = 500; // ms между выстрелами
// Карта (0 - пусто, 1 - стена)
const map = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1],
[1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],
[1,0,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1],
[1,0,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1],
[1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],
[1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
].map(row => row.slice(0, MAP_WIDTH)); // Обрезаем до размера холста
// Классы
class Tank {
constructor(x, y, color, isPlayer = false) {
this.x = x;
this.y = y;
this.width = TILE_SIZE * 0.8;
this.height = TILE_SIZE * 0.8;
this.angle = 0; // В радианах
this.speed = isPlayer ? PLAYER_SPEED : TANK_SPEED;
this.health = 100;
this.color = color;
this.isPlayer = isPlayer;
this.lastFire = 0;
}
draw() {
ctx.save();
ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
ctx.rotate(this.angle);
ctx.fillStyle = this.color;
ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
ctx.restore();
}
move(dx, dy) {
const newX = this.x + dx;
const newY = this.y + dy;
if (!checkCollision(newX, newY, this.width, this.height)) {
this.x = newX;
this.y = newY;
}
}
shoot() {
const now = Date.now();
if (now - this.lastFire > FIRE_RATE) {
this.lastFire = now;
return new Bullet(this.x + this.width / 2, this.y + this.height / 2, this.angle);
}
return null;
}
}
class Bullet {
constructor(x, y, angle) {
this.x = x;
this.y = y;
this.radius = 5;
this.speed = BULLET_SPEED;
this.angle = angle;
this.dx = Math.cos(angle) * this.speed;
this.dy = Math.sin(angle) * this.speed;
}
update() {
this.x += this.dx;
this.y += this.dy;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
}
}
// ИИ танк
class AITank extends Tank {
constructor(x, y) {
super(x, y, 'orange');
this.state = 'patrol'; // patrol, chase, shoot, evade
this.path = [];
this.target = null;
}
update(player, bullets) {
if (this.state === 'patrol') {
this.patrol();
if (this.distanceTo(player) < 200) this.state = 'chase';
} else if (this.state === 'chase') {
this.chase(player);
if (this.canShoot(player)) this.state = 'shoot';
if (this.needsEvade(bullets)) this.state = 'evade';
} else if (this.state === 'shoot') {
const bullet = this.shoot();
if (bullet) this.state = 'chase';
} else if (this.state === 'evade') {
this.evade(bullets);
if (!this.needsEvade(bullets)) this.state = 'chase';
}
}
distanceTo(target) {
return Math.hypot(this.x - target.x, this.y - target.y);
}
canShoot(target) {
return this.distanceTo(target) < 150 && Math.abs(this.angleTo(target) - this.angle) < 0.1;
}
angleTo(target) {
return Math.atan2(target.y - this.y, target.x - this.x);
}
patrol() {
this.angle += 0.01; // Случайное движение
this.move(Math.cos(this.angle) * this.speed, Math.sin(this.angle) * this.speed);
}
chase(player) {
this.angle = this.angleTo(player);
this.path = aStar(this, player); // Получаем путь
if (this.path.length > 0) {
const next = this.path[0];
this.angle = Math.atan2(next.y - this.y, next.x - this.x);
this.move(Math.cos(this.angle) * this.speed, Math.sin(this.angle) * this.speed);
}
}
needsEvade(bullets) {
for (let bullet of bullets) {
if (this.willHit(bullet)) return true;
}
return false;
}
willHit(bullet) {
const dx = bullet.x - this.x;
const dy = bullet.y - this.y;
const distance = Math.hypot(dx, dy);
const bulletAngle = Math.atan2(bullet.dy, bullet.dx);
const angleDiff = Math.abs(bulletAngle - this.angleTo({x: bullet.x + bullet.dx * 10, y: bullet.y + bullet.dy * 10}));
return distance < 100 && angleDiff < 0.5;
}
evade(bullets) {
for (let bullet of bullets) {
if (this.willHit(bullet)) {
this.angle += Math.PI / 2; // Поворот в сторону
this.move(Math.cos(this.angle) * this.speed, Math.sin(this.angle) * this.speed);
}
}
}
}
// A* алгоритм
function aStar(start, end) {
const grid = generateGrid();
const openSet = [grid[Math.floor(start.y / TILE_SIZE)][Math.floor(start.x / TILE_SIZE)]];
const cameFrom = {};
const gScore = Array(MAP_HEIGHT).fill().map(() => Array(MAP_WIDTH).fill(Infinity));
gScore[Math.floor(start.y / TILE_SIZE)][Math.floor(start.x / TILE_SIZE)] = 0;
const fScore = Array(MAP_HEIGHT).fill().map(() => Array(MAP_WIDTH).fill(Infinity));
fScore[Math.floor(start.y / TILE_SIZE)][Math.floor(start.x / TILE_SIZE)] = heuristic(start, end);
while (openSet.length > 0) {
openSet.sort((a, b) => fScore[a.y][a.x] - fScore[b.y][b.x]);
const current = openSet.shift();
if (current.x === Math.floor(end.x / TILE_SIZE) && current.y === Math.floor(end.y / TILE_SIZE)) {
return reconstructPath(cameFrom, current);
}
const neighbors = getNeighbors(current);
for (let neighbor of neighbors) {
const tentativeGScore = gScore[current.y][current.x] + 1;
if (tentativeGScore < gScore[neighbor.y][neighbor.x]) {
cameFrom[`${neighbor.y}-${neighbor.x}`] = current;
gScore[neighbor.y][neighbor.x] = tentativeGScore;
fScore[neighbor.y][neighbor.x] = gScore[neighbor.y][neighbor.x] + heuristic(neighbor, end);
if (!openSet.some(cell => cell.x === neighbor.x && cell.y === neighbor.y)) {
openSet.push(neighbor);
}
}
}
}
return []; // Нет пути
}
function generateGrid() {
return map.map((row, y) => row.map((cell, x) => ({x, y, walkable: cell === 0})));
}
function getNeighbors(cell) {
const neighbors = [];
const directions = [[0, -1], [0, 1], [-1, 0], [1, 0]];
for (let [dx, dy] of directions) {
const nx = cell.x + dx;
const ny = cell.y + dy;
if (nx >= 0 && nx < MAP_WIDTH && ny >= 0 && ny < MAP_HEIGHT && map[ny][nx] === 0) {
neighbors.push({x: nx, y: ny});
}
}
return neighbors;
}
function heuristic(a, b) {
return Math.abs(a.x - Math.floor(b.x / TILE_SIZE)) + Math.abs(a.y - Math.floor(b.y / TILE_SIZE));
}
function reconstructPath(cameFrom, current) {
const path = [{x: current.x * TILE_SIZE + TILE_SIZE / 2, y: current.y * TILE_SIZE + TILE_SIZE / 2}];
while (cameFrom[`${current.y}-${current.x}`]) {
current = cameFrom[`${current.y}-${current.x}`];
path.unshift({x: current.x * TILE_SIZE + TILE_SIZE / 2, y: current.y * TILE_SIZE + TILE_SIZE / 2});
}
return path;
}
function checkCollision(x, y, width, height) {
const left = Math.floor(x / TILE_SIZE);
const right = Math.floor((x + width) / TILE_SIZE);
const top = Math.floor(y / TILE_SIZE);
const bottom = Math.floor((y + height) / TILE_SIZE);
for (let i = top; i <= bottom; i++) {
for (let j = left; j <= right; j++) {
if (i >= 0 && i < MAP_HEIGHT && j >= 0 && j < MAP_WIDTH && map[i][j] === 1) return true;
}
}
return false;
}
// Игра
const player = new Tank(100, 100, 'blue', true);
const aiTanks = [new AITank(600, 500), new AITank(400, 300)];
const bullets = [];
function update() {
if (player.health <= 0) {
gameOver();
return;
}
player.draw();
aiTanks.forEach(ai => {
ai.update(player, bullets);
ai.draw();
const bullet = ai.shoot();
if (bullet) bullets.push(bullet);
});
bullets.forEach((bullet, index) => {
bullet.update();
bullet.draw();
// Столкновение с игроком
if (Math.hypot(bullet.x - player.x - player.width / 2, bullet.y - player.y - player.height / 2) < bullet.radius + player.width / 2) {
player.health -= 10;
healthSpan.textContent = player.health;
bullets.splice(index, 1);
}
// Удаление пуль за пределами экрана
if (bullet.x < 0 || bullet.x > canvas.width || bullet.y < 0 || bullet.y > canvas.height) bullets.splice(index, 1);
});
scoreSpan.textContent = bullets.length + aiTanks.filter(tank => tank.health <= 0).length * 10;
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Рисуем карту
for (let y = 0; y < MAP_HEIGHT; y++) {
for (let x = 0; x < MAP_WIDTH; x++) {
if (map[y][x] === 1) {
ctx.fillStyle = '#555';
ctx.fillRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
}
update();
requestAnimationFrame(gameLoop);
}
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp') player.move(0, -player.speed);
if (e.key === 'ArrowDown') player.move(0, player.speed);
if (e.key === 'ArrowLeft') { player.angle -= 0.1; player.move(-player.speed, 0); }
if (e.key === 'ArrowRight') { player.angle += 0.1; player.move(player.speed, 0); }
if (e.key === ' ') {
const bullet = player.shoot();
if (bullet) bullets.push(bullet);
}
});
function gameOver() {
finalScoreSpan.textContent = scoreSpan.textContent;
document.getElementById('gameOver').style.display = 'block';
}
function restartGame() {
player.health = 100;
healthSpan.textContent = 100;
player.x = 100;
player.y = 100;
aiTanks.forEach(ai => { ai.health = 100; ai.x = Math.random() * canvas.width; ai.y = Math.random() * canvas.height; });
bullets.length = 0;
document.getElementById('gameOver').style.display = 'none';
}
gameLoop();
</script>
</body>
</html>
Как это работает:
- Игрок: Управляется клавишами (стрелки для движения и поворота, пробел для стрельбы).
- Вражеские танки: Используют A* для преследования, FSM для состояний, и простое предсказание для уклонения.
- Столкновения: Проверяются с картой и пулями.
- A:* Генерирует путь на основе сетки карты.
- UI: Отображает здоровье, счет и сообщение о конце игры.
Улучшения:
- Графика: Добавьте спрайты для танков и пуль.
- Звуки: Добавьте звуковые эффекты.
- Мультиплеер: Сделайте онлайн-версию.
- Оптимизация: A* может быть медленным; кэшируйте пути.
- Баланс: Настройте параметры ИИ для сложности.
Это базовая версия; для полноценной игры потребуется больше времени и ресурсов! 😊