asteroid / index.html
bebechien's picture
Upload index.html
da4045e verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project Supernova</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');
body {
background-color: #000;
color: #0f0;
font-family: 'Orbitron', sans-serif;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
canvas {
background-color: #0a0a0a;
border: 2px solid #0ff;
box-shadow: 0 0 20px #0ff;
cursor: crosshair;
}
.ui-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
background-color: rgba(0, 0, 0, 0.7);
color: #0ff;
text-align: center;
}
.ui-overlay h1 {
font-size: 4rem;
text-shadow: 0 0 15px #0ff;
margin-bottom: 1rem;
}
.ui-overlay p {
font-size: 1.2rem;
margin-bottom: 2rem;
}
.ui-button {
background-color: transparent;
border: 2px solid #0ff;
color: #0ff;
padding: 1rem 2rem;
font-family: 'Orbitron', sans-serif;
font-size: 1.2rem;
text-transform: uppercase;
cursor: pointer;
transition: all 0.3s ease;
margin: 0.5rem;
box-shadow: 0 0 10px #0ff inset;
}
.ui-button:hover {
background-color: #0ff;
color: #000;
box-shadow: 0 0 20px #0ff;
}
#hud {
position: absolute;
top: 20px;
width: 100%;
padding: 0 40px;
box-sizing: border-box;
display: flex;
justify-content: space-between;
font-size: 1.5rem;
text-shadow: 0 0 5px #fff;
pointer-events: none;
}
#player-hud {
color: #0ff;
}
#ai-hud {
color: #f0f;
}
#timer-hud {
color: #fff;
}
</style>
</head>
<body>
<div id="hud" class="hidden">
<div id="player-hud">Player: 0 | Lives: 3</div>
<div id="timer-hud">3:00</div>
<div id="ai-hud">Rival: 0 | Lives: 3</div>
</div>
<div id="menu" class="ui-overlay">
<h1 class="text-6xl font-bold">PROJECT SUPERNOVA</h1>
<p class="text-xl">An AI has challenged you to a duel amidst the asteroids.</p>
<div>
<button id="easy-btn" class="ui-button">Easy</button>
<button id="medium-btn" class="ui-button">Medium</button>
<button id="hard-btn" class="ui-button">Hard</button>
</div>
</div>
<div id="game-over" class="ui-overlay hidden">
<h1 id="winner-text" class="text-6xl font-bold"></h1>
<p id="final-scores" class="text-xl"></p>
<button id="play-again-btn" class="ui-button">Play Again</button>
</div>
<canvas id="gameCanvas"></canvas>
<script type="module">
// --- Game Setup ---
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const menu = document.getElementById('menu');
const gameOverScreen = document.getElementById('game-over');
const hud = document.getElementById('hud');
let game;
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// --- Utility Classes & Functions ---
class Vector {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
add(v) { return new Vector(this.x + v.x, this.y + v.y); }
subtract(v) { return new Vector(this.x - v.x, this.y - v.y); }
multiply(s) { return new Vector(this.x * s, this.y * s); }
get magnitude() { return Math.sqrt(this.x ** 2 + this.y ** 2); }
get angle() { return Math.atan2(this.y, this.x); }
normalize() {
const mag = this.magnitude;
return mag === 0 ? new Vector() : new Vector(this.x / mag, this.y / mag);
}
static fromAngle(angle, magnitude = 1) {
return new Vector(magnitude * Math.cos(angle), magnitude * Math.sin(angle));
}
}
function isColliding(obj1, obj2) {
const dist = obj1.pos.subtract(obj2.pos).magnitude;
return dist < obj1.radius + obj2.radius;
}
function wrapEdges(obj) {
if (obj.pos.x < -obj.radius) obj.pos.x = canvas.width + obj.radius;
if (obj.pos.x > canvas.width + obj.radius) obj.pos.x = -obj.radius;
if (obj.pos.y < -obj.radius) obj.pos.y = canvas.height + obj.radius;
if (obj.pos.y > canvas.height + obj.radius) obj.pos.y = -obj.radius;
}
// --- Game Object Classes ---
// Base class for Player and AI
class Ship {
constructor(x, y, color, name) {
this.name = name;
this.pos = new Vector(x, y);
this.vel = new Vector();
this.angle = -Math.PI / 2; // Point up
this.radius = 15;
this.color = color;
this.isThrusting = false;
this.rotation = 0;
this.lives = 3;
this.score = 0;
this.isInvincible = false;
this.invincibilityTimer = 0;
this.shootCooldown = 0;
}
draw() {
ctx.save();
ctx.translate(this.pos.x, this.pos.y);
ctx.rotate(this.angle);
if (this.isInvincible && Math.floor(Date.now() / 100) % 2) {
ctx.strokeStyle = '#fff';
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
} else {
ctx.strokeStyle = this.color;
ctx.fillStyle = 'rgba(10, 10, 10, 0.5)';
}
// Ship body
ctx.shadowColor = this.color;
ctx.shadowBlur = 15;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(15, 0);
ctx.lineTo(-10, -10);
ctx.lineTo(-10, 10);
ctx.closePath();
ctx.stroke();
ctx.fill();
// Thrust flame
if (this.isThrusting && Math.random() > 0.2) {
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.moveTo(-10, 0);
ctx.lineTo(-18 - Math.random() * 5, 5);
ctx.lineTo(-18 - Math.random() * 5, -5);
ctx.closePath();
ctx.fill();
}
ctx.restore();
}
update() {
this.angle += this.rotation;
if (this.isThrusting) {
const force = Vector.fromAngle(this.angle, 0.1);
this.vel = this.vel.add(force);
}
// Apply friction
this.vel = this.vel.multiply(0.99);
if (this.vel.magnitude > 5) {
this.vel = this.vel.normalize().multiply(5);
}
this.pos = this.pos.add(this.vel);
wrapEdges(this);
if (this.shootCooldown > 0) this.shootCooldown--;
if (this.isInvincible) {
this.invincibilityTimer--;
if (this.invincibilityTimer <= 0) {
this.isInvincible = false;
}
}
}
shoot() {
if (this.shootCooldown === 0) {
const bulletVel = Vector.fromAngle(this.angle, 7).add(this.vel);
const bulletPos = this.pos.add(Vector.fromAngle(this.angle, 15));
game.bullets.push(new Bullet(bulletPos.x, bulletPos.y, bulletVel, this.color, this.name));
this.shootCooldown = 15; // Cooldown frames
}
}
hit() {
if (this.isInvincible) return;
this.lives--;
game.createExplosion(this.pos, this.color, 40);
if (this.lives > 0) {
this.resetPosition();
} else {
game.handlePlayerDeath(this);
}
}
resetPosition() {
this.pos = new Vector(Math.random() * canvas.width, Math.random() * canvas.height);
this.vel = new Vector();
this.isInvincible = true;
this.invincibilityTimer = 180; // 3 seconds
}
}
class Player extends Ship {
constructor(x, y) {
super(x, y, '#0ff', 'Player');
this.keys = {};
this.setupControls();
}
setupControls() {
window.addEventListener('keydown', (e) => this.keys[e.code] = true);
window.addEventListener('keyup', (e) => this.keys[e.code] = false);
}
update() {
this.rotation = 0;
if (this.keys['KeyA'] || this.keys['ArrowLeft']) this.rotation = -0.05;
if (this.keys['KeyD'] || this.keys['ArrowRight']) this.rotation = 0.05;
this.isThrusting = this.keys['KeyW'] || this.keys['ArrowUp'];
if (this.keys['Space']) {
this.shoot();
}
super.update();
}
}
class AI extends Ship {
constructor(x, y, difficulty) {
super(x, y, '#f0f', 'Rival');
this.difficulty = difficulty;
this.state = 'HUNTING_ASTEROID';
this.target = null;
this.stateTimer = 0;
this.setupDifficulty();
}
setupDifficulty() {
switch(this.difficulty) {
case 'easy':
this.accuracy = 0.3; this.aggression = 0.1; this.reactionTime = 30;
break;
case 'hard':
this.accuracy = 0.9; this.aggression = 0.6; this.reactionTime = 5;
break;
case 'medium':
default:
this.accuracy = 0.6; this.aggression = 0.3; this.reactionTime = 15;
break;
}
}
update() {
this.stateTimer--;
if (this.stateTimer <= 0) {
this.chooseNewState();
}
this.executeState();
super.update();
}
chooseNewState() {
this.stateTimer = Math.random() * 120 + 60; // 1-3 seconds
const dangerousObject = this.findClosestThreat();
if (dangerousObject) {
this.state = 'AVOIDING_DANGER';
this.target = dangerousObject;
return;
}
if (Math.random() < this.aggression || (game.player && game.player.score > this.score + 1000)) {
this.state = 'ATTACKING_PLAYER';
this.target = game.player;
} else {
this.state = 'HUNTING_ASTEROID';
this.target = this.findClosestAsteroid();
}
}
executeState() {
if (!this.target) {
this.isThrusting = false;
this.rotation = 0;
return;
}
let targetPos = this.target.pos;
// Lead the target
if (this.target.vel) {
const timeToIntercept = this.pos.subtract(this.target.pos).magnitude / 7; // 7 is bullet speed
targetPos = this.target.pos.add(this.target.vel.multiply(timeToIntercept * (this.accuracy * 20)));
}
const vectorToTarget = targetPos.subtract(this.pos);
const desiredAngle = vectorToTarget.angle;
let angleDiff = desiredAngle - this.angle;
// Normalize angle difference
while (angleDiff < -Math.PI) angleDiff += 2 * Math.PI;
while (angleDiff > Math.PI) angleDiff -= 2 * Math.PI;
if (this.state === 'AVOIDING_DANGER') {
// Turn away from the threat
angleDiff += Math.PI;
}
// Rotation
this.rotation = Math.sign(angleDiff) * 0.05;
if(Math.abs(angleDiff) < 0.1) this.rotation = 0;
// Thrusting
const shouldThrust = this.state === 'AVOIDING_DANGER' || vectorToTarget.magnitude > 100;
this.isThrusting = (Math.abs(angleDiff) < Math.PI / 2) && shouldThrust;
// Shooting
if (this.state !== 'AVOIDING_DANGER' && Math.abs(angleDiff) < 0.2 && Math.random() < this.accuracy) {
this.shoot();
}
}
findClosestThreat() {
let closestDist = Infinity;
let closestThreat = null;
const checkRadius = 150;
for (const asteroid of game.asteroids) {
const dist = this.pos.subtract(asteroid.pos).magnitude;
if (dist < checkRadius && dist < closestDist) {
closestDist = dist;
closestThreat = asteroid;
}
}
return closestThreat;
}
findClosestAsteroid() {
let closestDist = Infinity;
let closestAsteroid = null;
for (const asteroid of game.asteroids) {
const dist = this.pos.subtract(asteroid.pos).magnitude;
if (dist < closestDist) {
closestDist = dist;
closestAsteroid = asteroid;
}
}
return closestAsteroid;
}
}
class Asteroid {
constructor(x, y, radius) {
this.pos = new Vector(x, y);
this.radius = radius;
this.vel = Vector.fromAngle(Math.random() * Math.PI * 2, Math.random() * 2 + 0.5);
this.angle = 0;
this.rotationSpeed = (Math.random() - 0.5) * 0.02;
this.shape = [];
const numVertices = Math.floor(Math.random() * 5) + 7;
for (let i = 0; i < numVertices; i++) {
const angle = (i / numVertices) * Math.PI * 2;
const r = this.radius * (Math.random() * 0.4 + 0.8);
this.shape.push(new Vector(Math.cos(angle) * r, Math.sin(angle) * r));
}
}
draw() {
ctx.save();
ctx.translate(this.pos.x, this.pos.y);
ctx.rotate(this.angle);
ctx.strokeStyle = '#fff';
ctx.shadowColor = '#fff';
ctx.shadowBlur = 5;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(this.shape[0].x, this.shape[0].y);
for (let i = 1; i < this.shape.length; i++) {
ctx.lineTo(this.shape[i].x, this.shape[i].y);
}
ctx.closePath();
ctx.stroke();
ctx.restore();
}
update() {
this.pos = this.pos.add(this.vel);
this.angle += this.rotationSpeed;
wrapEdges(this);
}
breakApart() {
game.createExplosion(this.pos, '#fff', Math.floor(this.radius / 2));
if (this.radius > 30) {
for (let i = 0; i < 2; i++) {
game.asteroids.push(new Asteroid(this.pos.x, this.pos.y, this.radius / 2));
}
} else if (this.radius > 15) {
for (let i = 0; i < 2; i++) {
game.asteroids.push(new Asteroid(this.pos.x, this.pos.y, this.radius / 2));
}
}
}
}
class Bullet {
constructor(x, y, vel, color, owner) {
this.pos = new Vector(x, y);
this.vel = vel;
this.radius = 3;
this.color = color;
this.lifespan = 80; // frames
this.owner = owner;
}
draw() {
ctx.fillStyle = this.color;
ctx.shadowColor = this.color;
ctx.shadowBlur = 10;
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
update() {
this.pos = this.pos.add(this.vel);
this.lifespan--;
}
}
class Particle {
constructor(x, y, color) {
this.pos = new Vector(x, y);
this.vel = Vector.fromAngle(Math.random() * Math.PI * 2, Math.random() * 3);
this.radius = Math.random() * 2 + 1;
this.color = color;
this.lifespan = 50;
this.alpha = 1;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
update() {
this.pos = this.pos.add(this.vel);
this.vel = this.vel.multiply(0.98);
this.lifespan--;
this.alpha = this.lifespan / 50;
}
}
// --- Main Game Class ---
class Game {
constructor(difficulty) {
this.difficulty = difficulty;
this.player = new Player(canvas.width / 4, canvas.height / 2);
this.ai = new AI(canvas.width * 3 / 4, canvas.height / 2, this.difficulty);
this.asteroids = [];
this.bullets = [];
this.particles = [];
this.isGameOver = false;
this.roundTime = 180 * 1000; // 3 minutes in ms
this.startTime = Date.now();
this.winner = null;
this.initAsteroids(8);
}
initAsteroids(count) {
for (let i = 0; i < count; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
// Ensure asteroids don't spawn on top of ships
const playerDist = new Vector(x, y).subtract(this.player.pos).magnitude;
const aiDist = new Vector(x, y).subtract(this.ai.pos).magnitude;
if(playerDist < 100 || aiDist < 100) {
i--;
continue;
}
this.asteroids.push(new Asteroid(x, y, 40));
}
}
update() {
if (this.isGameOver) return;
// Update all objects
this.player.update();
this.ai.update();
this.asteroids.forEach(a => a.update());
this.bullets.forEach(b => b.update());
this.particles.forEach(p => p.update());
// Filter out dead objects
this.bullets = this.bullets.filter(b => b.lifespan > 0);
this.particles = this.particles.filter(p => p.lifespan > 0);
// Check collisions
this.handleCollisions();
// Check for more asteroids
if (this.asteroids.length < 5) {
this.initAsteroids(3);
}
// Check game end conditions
const elapsedTime = Date.now() - this.startTime;
if (elapsedTime >= this.roundTime) {
this.endGameByTime();
}
}
draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.shadowBlur = 0; // Reset shadow for background
ctx.fillStyle = 'rgba(0,0,0,0.9)'; // Slight fade effect
ctx.fillRect(0, 0, canvas.width, canvas.height);
this.player.draw();
this.ai.draw();
this.asteroids.forEach(a => a.draw());
this.bullets.forEach(b => b.draw());
this.particles.forEach(p => p.draw());
this.updateHUD();
}
updateHUD() {
document.getElementById('player-hud').innerText = `Player: ${this.player.score} | Lives: ${this.player.lives}`;
document.getElementById('ai-hud').innerText = `Rival: ${this.ai.score} | Lives: ${this.ai.lives}`;
const remainingTime = Math.max(0, this.roundTime - (Date.now() - this.startTime));
const minutes = Math.floor(remainingTime / 60000);
const seconds = Math.floor((remainingTime % 60000) / 1000).toString().padStart(2, '0');
document.getElementById('timer-hud').innerText = `${minutes}:${seconds}`;
}
handleCollisions() {
// Bullets vs Asteroids
for (let i = this.bullets.length - 1; i >= 0; i--) {
const bullet = this.bullets[i];
for (let j = this.asteroids.length - 1; j >= 0; j--) {
const asteroid = this.asteroids[j];
if (isColliding(bullet, asteroid)) {
this.bullets.splice(i, 1);
let points = 0;
if (asteroid.radius > 30) points = 20;
else if (asteroid.radius > 15) points = 50;
else points = 100;
if (bullet.owner === 'Player') this.player.score += points;
else if (bullet.owner === 'Rival') this.ai.score += points;
asteroid.breakApart();
this.asteroids.splice(j, 1);
break;
}
}
}
// Ships vs Asteroids
[this.player, this.ai].forEach(ship => {
for (const asteroid of this.asteroids) {
if (isColliding(ship, asteroid)) {
ship.hit();
}
}
});
// Bullets vs Ships
for (let i = this.bullets.length - 1; i >= 0; i--) {
const bullet = this.bullets[i];
if (bullet.owner !== 'Player' && isColliding(bullet, this.player)) {
this.player.hit();
this.ai.score += 500;
this.bullets.splice(i, 1);
continue;
}
if (bullet.owner !== 'Rival' && isColliding(bullet, this.ai)) {
this.ai.hit();
this.player.score += 500;
this.bullets.splice(i, 1);
continue;
}
}
}
createExplosion(pos, color, count) {
for(let i=0; i < count; i++) {
this.particles.push(new Particle(pos.x, pos.y, color));
}
}
handlePlayerDeath(ship) {
if (ship === this.player && this.ai.lives > 0) {
this.endGame(this.ai);
} else if (ship === this.ai && this.player.lives > 0) {
this.endGame(this.player);
} else {
// This handles simultaneous death
this.endGameByTime();
}
}
endGameByTime() {
if (this.player.score > this.ai.score) {
this.endGame(this.player);
} else if (this.ai.score > this.player.score) {
this.endGame(this.ai);
} else {
this.endGame(null); // Draw
}
}
endGame(winner) {
if (this.isGameOver) return;
this.isGameOver = true;
this.winner = winner;
const winnerText = document.getElementById('winner-text');
if (winner) {
winnerText.innerText = `${winner.name} Wins!`;
winnerText.style.color = winner.color;
} else {
winnerText.innerText = 'Draw!';
winnerText.style.color = '#fff';
}
document.getElementById('final-scores').innerText = `Final Score: ${this.player.score} (Player) vs ${this.ai.score} (Rival)`;
gameOverScreen.classList.remove('hidden');
hud.classList.add('hidden');
}
}
// --- Main Loop ---
let animationFrameId;
function gameLoop() {
game.update();
game.draw();
animationFrameId = requestAnimationFrame(gameLoop);
}
function startGame(difficulty) {
menu.classList.add('hidden');
gameOverScreen.classList.add('hidden');
hud.classList.remove('hidden');
game = new Game(difficulty);
if (animationFrameId) cancelAnimationFrame(animationFrameId);
gameLoop();
}
// --- Event Listeners ---
document.getElementById('easy-btn').onclick = () => startGame('easy');
document.getElementById('medium-btn').onclick = () => startGame('medium');
document.getElementById('hard-btn').onclick = () => startGame('hard');
document.getElementById('play-again-btn').onclick = () => {
gameOverScreen.classList.add('hidden');
menu.classList.remove('hidden');
};
</script>
</body>
</html>