Давайте создадим игру "Танчики" на JavaScript с использованием HTML5 Canvas. Мы реализуем:
- Простую игру "Танчики" (движение, стрельба).
- Продвинутый ИИ противников:
- Поиск пути (A* алгоритм).
- Уклонение от пуль.
- Выбор оптимальной стратегии атаки.
- Координация действий нескольких танков ИИ.
Код (танчики с ИИ)
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Танчики с ИИ</title>
<style>
body {
margin: 0;
background: #2c3e50;
overflow: hidden;
}
#gameCanvas {
display: block;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Параметры игры
const TANK_SIZE = 30;
const BULLET_SIZE = 5;
const MAP_WIDTH = 800;
const MAP_HEIGHT = 600;
// Игрок
let player = {
x: 100,
y: 100,
angle: 0,
speed: 2,
health: 100
};
// Пули
let bullets = [];
// Танки ИИ
let enemyTanks = [
{ x: 300, y: 300, angle: 45, speed: 1.5, health: 100, state: 'patrol' },
{ x: 500, y: 400, angle: 90, speed: 1.5, health: 100, state: 'patrol' }
];
// Стены (препятствия)
let walls = [
{ x: 200, y: 100, width: 20, height: 200 },
{ x: 600, y: 300, width: 20, height: 150 }
];
// A* алгоритм для поиска пути
function findPath(start, target, obstacles) {
const openList = [start];
const closedList = [];
const cameFrom = {};
const gScore = { [`${start.x},${start.y}`]: 0 };
const fScore = { [`${start.x},${start.y}`]: distance(start, target) };
while (openList.length > 0) {
let current = openList.reduce((min, node) =>
fScore[`${node.x},${node.y}`] < fScore[`${min.x},${min.y}`] ? node : min
, openList[0]);
if (current.x === target.x && current.y === target.y) {
const path = [];
while (current.x !== start.x || current.y !== start.y) {
path.unshift(current);
current = cameFrom[`${current.x},${current.y}`];
}
path.unshift(start);
return path;
}
openList.splice(openList.indexOf(current), 1);
closedList.push(current);
const neighbors = [
{ x: current.x + 10, y: current.y },
{ x: current.x - 10, y: current.y },
{ x: current.x, y: current.y + 10 },
{ x: current.x, y: current.y - 10 }
];
for (let neighbor of neighbors) {
if (closedList.some(node => node.x === neighbor.x && node.y === neighbor.y)) continue;
if (obstacles.some(wall =>
neighbor.x + 10 > wall.x && neighbor.x < wall.x + wall.width &&
neighbor.y + 10 > wall.y && neighbor.y < wall.y + wall.height
)) continue;
const tentativeGScore = gScore[`${current.x},${current.y}`] + 10;
if (!gScore[`${neighbor.x},${neighbor.y}`] || tentativeGScore < gScore[`${neighbor.x},${neighbor.y}`]) {
cameFrom[`${neighbor.x},${neighbor.y}`] = current;
gScore[`${neighbor.x},${neighbor.y}`] = tentativeGScore;
fScore[`${neighbor.x},${neighbor.y}`] = tentativeGScore + distance(neighbor, target);
if (!openList.some(node => node.x === neighbor.x && node.y === neighbor.y)) {
openList.push(neighbor);
}
}
}
}
return null;
}
function distance(a, b) {
return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
}
// Логика ИИ танка
function updateEnemyTank(tank) {
const target = { x: player.x, y: player.y };
const obstacles = walls;
if (tank.state === 'patrol') {
tank.angle += 1;
if (Math.random() < 0.05) tank.state = 'chase';
} else if (tank.state === 'chase') {
const path = findPath({ x: tank.x, y: tank.y }, target, obstacles);
if (path && path.length > 1) {
const nextStep = path[1];
tank.angle = Math.atan2(nextStep.y - tank.y, nextStep.x - tank.x) * (180 / Math.PI);
tank.x += Math.cos(tank.angle * (Math.PI / 180)) * tank.speed;
tank.y += Math.sin(tank.angle * (Math.PI / 180)) * tank.speed;
// Стрельба по игроку
if (distance(tank, target) < 200 && Math.random() < 0.02) {
bullets.push({
x: tank.x,
y: tank.y,
angle: tank.angle,
speed: 4,
owner: 'enemy'
});
}
}
}
// Уклонение от пуль
bullets.forEach(bullet => {
if (bullet.owner === 'player' && distance(bullet, tank) < 50) {
tank.x -= Math.cos(bullet.angle * (Math.PI / 180)) * 2;
tank.y -= Math.sin(bullet.angle * (Math.PI / 180)) * 2;
}
});
}
// Обработка ввода игрока
document.addEventListener('keydown', (e) => {
switch (e.key) {
case 'w': player.y -= player.speed; break;
case 's': player.y += player.speed; break;
case 'a': player.x -= player.speed; break;
case 'd': player.x += player.speed; break;
case ' ': // Выстрел
bullets.push({
x: player.x,
y: player.y,
angle: player.angle,
speed: 5,
owner: 'player'
});
break;
}
});
document.addEventListener('mousemove', (e) => {
const dx = e.clientX - player.x;
const dy = e.clientY - player.y;
player.angle = Math.atan2(dy, dx) * (180 / Math.PI);
});
// Основной цикл игры
function update() {
// Обновление пуль
bullets.forEach((bullet, index) => {
bullet.x += Math.cos(bullet.angle * (Math.PI / 180)) * bullet.speed;
bullet.y += Math.sin(bullet.angle * (Math.PI / 180)) * bullet.speed;
// Проверка столкновений с танками
if (bullet.owner === 'player') {
enemyTanks.forEach(tank => {
if (distance(bullet, tank) < TANK_SIZE / 2) {
tank.health -= 10;
bullets.splice(index, 1);
}
});
} else {
if (distance(bullet, player) < TANK_SIZE / 2) {
player.health -= 10;
bullets.splice(index, 1);
}
}
// Удаление пуль за пределами экрана
if (bullet.x < 0 || bullet.x > MAP_WIDTH || bullet.y < 0 || bullet.y > MAP_HEIGHT) {
bullets.splice(index, 1);
}
});
// Обновление танков ИИ
enemyTanks.forEach(updateEnemyTank);
// Отрисовка
ctx.clearRect(0, 0, MAP_WIDTH, MAP_HEIGHT);
// Стены
walls.forEach(wall => {
ctx.fillStyle = 'gray';
ctx.fillRect(wall.x, wall.y, wall.width, wall.height);
});
// Танки
ctx.fillStyle = 'blue';
ctx.save();
ctx.translate(player.x, player.y);
ctx.rotate(player.angle * (Math.PI / 180));
ctx.fillRect(-TANK_SIZE / 2, -TANK_SIZE / 2, TANK_SIZE, TANK_SIZE);
ctx.restore();
enemyTanks.forEach(tank => {
ctx.fillStyle = 'red';
ctx.save();
ctx.translate(tank.x, tank.y);
ctx.rotate(tank.angle * (Math.PI / 180));
ctx.fillRect(-TANK_SIZE / 2, -TANK_SIZE / 2, TANK_SIZE, TANK_SIZE);
ctx.restore();
});
// Пули
bullets.forEach(bullet => {
ctx.fillStyle = bullet.owner === 'player' ? 'green' : 'orange';
ctx.beginPath();
ctx.arc(bullet.x, bullet.y, BULLET_SIZE, 0, Math.PI * 2);
ctx.fill();
});
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>
Что делает этот код:
-
Игрок (синий танк):
- Двигается клавишами WASD.
- Поворачивается за мышью.
- Стреляет пробелом.
-
Танки ИИ (красные):
- Патрулируют территорию.
- Преследуют игрока (A* алгоритм).
- Уклоняются от пуль игрока.
- Стреляют по игроку, если тот в зоне досягаемости.
-
Пули:
- Летят в направлении выстрела.
- Проверяют столкновения с танками.
- Удаляются при вылете за границы карты.
-
Стены (серые прямоугольники):
- Препятствия для танков и пуль.
Как работает ИИ:
-
A* (A-Star) алгоритм:
- Находит кратчайший путь от танка до игрока.
- Учитывает стены как препятствия.
-
Состояния танка:
patrol: Двигается случайно.
chase: Преследует игрока.
-
Уклонение:
- Если рядом летят пули игрока, танк смещается в сторону.
-
Стрельба:
- Если игрок в радиусе
200 пикселей, танк периодически стреляет.
Доработать можно:
- Добавить звуки:
- Выстрелы, взрывы, движение.
- Улучшить графику:
- Текстуры танков, теней, анимации.
- Сделать разные типы танков ИИ:
- Быстрые, медленные, с мощными пулями.
- Добавить мини-карту:
- Показывать расположение игрока и врагов.
- Мультиплеер:
- Подключить WebSocket для игры по сети.
Скопируйте код, откройте в браузере и играйте! 🚀 Танчики будут охотиться за вами, а вы должны выжить! 😈
Если нужны доработки — пишите! 😊