o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Напиши игру на javascript таурдефенс
- User
Напиши игру на javascript таурдефенс
- Assistant
Напиши игру на javascript таурдефенс
Конечно! Давайте создадим простую игру типа Tower Defense на JavaScript. Мы будем использовать HTML5 Canvas для рисования игровых элементов. Этот пример будет базовым, но вы сможете расширить и улучшить его по своему усмотрению.
Создайте HTML-файл и добавьте в него элемент <canvas>:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Tower Defense Game</title>
<style>
canvas {
border: 1px solid #000;
background-color: #eee;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script src="game.js"></script>
</body>
</html>
Создайте файл game.js и добавьте основной код игры.
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Параметры игры
const game = {
width: canvas.width,
height: canvas.height,
towers: [],
enemies: [],
bullets: [],
money: 100,
lives: 10,
enemySpawnInterval: 2000,
lastEnemySpawn: 0
};
// Класс Башни
class Tower {
constructor(x, y) {
this.x = x;
this.y = y;
this.range = 100;
this.fireRate = 1000; // Периодичность выстрелов в мс
this.lastShotTime = 0;
}
draw() {
ctx.fillStyle = 'blue';
ctx.fillRect(this.x - 15, this.y - 15, 30, 30);
}
update(deltaTime) {
if (Date.now() - this.lastShotTime > this.fireRate) {
const target = this.findTarget();
if (target) {
this.shoot(target);
this.lastShotTime = Date.now();
}
}
}
findTarget() {
return game.enemies.find(enemy => {
const dist = Math.hypot(enemy.x - this.x, enemy.y - this.y);
return dist <= this.range;
});
}
shoot(target) {
game.bullets.push(new Bullet(this.x, this.y, target));
}
}
// Класс Врага
class Enemy {
constructor(path) {
this.path = path;
this.currentPoint = 0;
this.x = path[0].x;
this.y = path[0].y;
this.speed = 50; // пикселей в секунду
this.health = 100;
}
draw() {
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(this.x, this.y, 15, 0, Math.PI * 2);
ctx.fill();
}
update(deltaTime) {
const targetPoint = this.path[this.currentPoint + 1];
if (targetPoint) {
const dx = targetPoint.x - this.x;
const dy = targetPoint.y - this.y;
const dist = Math.hypot(dx, dy);
const moveDist = this.speed * (deltaTime / 1000);
if (moveDist >= dist) {
this.x = targetPoint.x;
this.y = targetPoint.y;
this.currentPoint++;
} else {
this.x += dx / dist * moveDist;
this.y += dy / dist * moveDist;
}
} else {
// Враг достиг конца пути
game.lives--;
this.markedForDeletion = true;
}
}
}
// Класс Пули
class Bullet {
constructor(x, y, target) {
this.x = x;
this.y = y;
this.target = target;
this.speed = 300;
}
draw() {
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, Math.PI * 2);
ctx.fill();
}
update(deltaTime) {
const dx = this.target.x - this.x;
const dy = this.target.y - this.y;
const dist = Math.hypot(dx, dy);
const moveDist = this.speed * (deltaTime / 1000);
if (dist <= moveDist) {
// Пуля достигает цели
this.target.health -= 50;
this.markedForDeletion = true;
if (this.target.health <= 0) {
this.target.markedForDeletion = true;
game.money += 10;
}
} else {
this.x += dx / dist * moveDist;
this.y += dy / dist * moveDist;
}
}
}
// Путь движения врагов
const enemyPath = [
{ x: 0, y: 300 },
{ x: 800, y: 300 }
];
// Главный цикл игры
let lastTime = 0;
function gameLoop(timestamp) {
const deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.clearRect(0, 0, game.width, game.height);
// Обновление и рисование башен
game.towers.forEach(tower => {
tower.update(deltaTime);
tower.draw();
});
// Спавн врагов
if (Date.now() - game.lastEnemySpawn > game.enemySpawnInterval) {
game.enemies.push(new Enemy(enemyPath));
game.lastEnemySpawn = Date.now();
}
// Обновление и рисование врагов
game.enemies.forEach(enemy => {
enemy.update(deltaTime);
enemy.draw();
});
// Обновление и рисование пуль
game.bullets.forEach(bullet => {
bullet.update(deltaTime);
bullet.draw();
});
// Удаление объектов, отмеченных для удаления
game.enemies = game.enemies.filter(enemy => !enemy.markedForDeletion);
game.bullets = game.bullets.filter(bullet => !bullet.markedForDeletion);
// Отображение оставшихся жизней и денег
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText(`Lives: ${game.lives}`, 10, 20);
ctx.fillText(`Money: $${game.money}`, 10, 40);
if (game.lives > 0) {
requestAnimationFrame(gameLoop);
} else {
ctx.fillStyle = 'black';
ctx.font = '50px Arial';
ctx.fillText('Game Over', game.width / 2 - 100, game.height / 2);
}
}
// Обработка установки башен по клику
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
if (game.money >= 50) {
game.towers.push(new Tower(x, y));
game.money -= 50;
}
});
requestAnimationFrame(gameLoop);
Tower: представляет башню, которая стреляет по врагам в пределах своего радиуса действия.Enemy: враги, которые движутся по заданному пути.Bullet: пули, которые выпускают башни при стрельбе.gameLoop обновляет состояние игры и перерисовывает все элементы на каждом кадре.enemyPath.Этот базовый пример должен помочь вам начать разработку своей игры Tower Defense на JavaScript. Вы можете расширить функционал, добавляя новые возможности и улучшения по своему вкусу. Удачи в разработке!
Not yet included in a published release.