<!DOCTYPE html>
<html>
<head>
<title>Cosmic Vanguard</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
background-color: #111;
border: 1px solid #222;
}
#highScoreContainer {
position: absolute;
top: 10px;
left: 10px;
color: white;
font-family: sans-serif;
}
#scoreContainer {
position: absolute;
top: 10px;
right: 10px;
color: white;
font-family: sans-serif;
}
#gameOverScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
color: white;
font-family: sans-serif;
display: none; /* Hidden by default */
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 10;
}
#gameOverScreen button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
font-size: 16px;
margin-top: 20px;
}
#startScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
color: white;
font-family: sans-serif;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 10;
}
#startScreen button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
font-size: 16px;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="startScreen">
<h1>Cosmic Vanguard</h1>
<p>Use arrow keys to move, spacebar to shoot.</p>
<button onclick="startGame()">Start Game</button>
</div>
<div id="gameOverScreen">
<h1>Game Over</h1>
<p id="finalScore">Score: 0</p>
<button onclick="restartGame()">Restart</button>
</div>
<div id="highScoreContainer">High Score: <span id="highScore">0</span></div>
<div id="scoreContainer">Score: <span id="currentScore">0</span></div>
<canvas id="gameCanvas"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const highScoreDisplay = document.getElementById('highScore');
const scoreDisplay = document.getElementById('currentScore');
const gameOverScreen = document.getElementById('gameOverScreen');
const finalScoreDisplay = document.getElementById('finalScore');
const startScreen = document.getElementById('startScreen');
let gameRunning = false;
// Canvas dimensions (responsive)
let canvasWidth = window.innerWidth * 0.8;
let canvasHeight = window.innerHeight * 0.8;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// Game variables
let player;
let enemies = [];
let playerProjectiles = [];
let enemyProjectiles = [];
let shields = [];
let powerUps = [];
let score = 0;
let highScore = localStorage.getItem('highScore') || 0;
let gameFrame = 0;
let keys = {}; // Track pressed keys
let lives = 3;
let level = 1;
let boss = null; // The boss enemy
let backgroundStars = [];
highScoreDisplay.textContent = highScore;
// Adjust canvas size on window resize
window.addEventListener('resize', () => {
canvasWidth = window.innerWidth * 0.8;
canvasHeight = window.innerHeight * 0.8;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
//Reinitialize objects on resize
initializeGame();
});
// Helper functions
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
// Input handling
document.addEventListener('keydown', (e) => {
keys[e.key] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.key] = false;
});
// Player class
class Player {
constructor() {
this.x = canvasWidth / 2;
this.y = canvasHeight - 50;
this.width = 30;
this.height = 30;
this.speed = 5;
this.isInvincible = false;
this.invincibleTimer = 0;
this.color = 'white';
this.lives = 3;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x - this.width/2, this.y - this.height/2, this.width, this.height);
if(this.isInvincible){
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 2;
ctx.strokeRect(this.x - this.width/2 - 2, this.y - this.height/2 - 2, this.width + 4, this.height + 4);
}
}
update() {
if (keys['ArrowLeft'] || keys['a']) {
this.x -= this.speed;
}
if (keys['ArrowRight'] || keys['d']) {
this.x += this.speed;
}
// Keep player within bounds
this.x = Math.max(this.width/2, Math.min(canvasWidth - this.width/2, this.x));
}
shoot() {
const projectile = new Projectile(this.x, this.y - this.height/2, -1);
playerProjectiles.push(projectile);
}
}
// Enemy classes
class Enemy {
constructor(x, y, type) {
this.x = x;
this.y = y;
this.width = 25;
this.height = 25;
this.speedX = 1 + level * 0.1; // Initial horizontal speed
this.speedY = 0.05; // Vertical speed
this.type = type;
this.health = 1;
this.color = 'red';
switch(type) {
case 'basic':
this.health = 1;
this.color = 'red';
break;
case 'fast':
this.health = 1;
this.speedX = 2 + level * 0.2;
this.color = 'yellow';
break;
case 'strong':
this.health = 3;
this.speedX = 0.7 + level * 0.07;
this.color = 'blue';
break;
}
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x - this.width/2, this.y - this.height/2, this.width, this.height);
}
update() {
this.x += this.speedX;
this.y += this.speedY;
// Reverse direction at edges
if (this.x + this.width/2 > canvasWidth || this.x - this.width/2 < 0) {
this.speedX *= -1;
this.y += 10; // Move down when changing direction
}
}
shoot() {
const projectile = new Projectile(this.x, this.y + this.height/2, 1);
enemyProjectiles.push(projectile);
}
}
class Boss {
constructor() {
this.x = canvasWidth / 2;
this.y = 50;
this.width = 75;
this.height = 75;
this.health = 20 + level * 5;
this.color = 'purple';
this.speedX = 0.5 + level * 0.1;
this.phase = 1; //Different attack patterns
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x - this.width / 2, this.y - this.height / 2, this.width, this.height);
}
update() {
// Simple movement for now
this.x += this.speedX;
if (this.x + this.width / 2 > canvasWidth || this.x - this.width / 2 < 0) {
this.speedX *= -1;
}
// Attack pattern based on phase
if (this.phase === 1 && gameFrame % 60 === 0) {
// Rapid fire
this.shoot();
} else if (this.phase === 2 && gameFrame % 120 === 0) {
// Spread shot
for (let i = -1; i <= 1; i++) {
const projectile = new Projectile(this.x, this.y + this.height / 2, 1);
projectile.speedX = i * 1.5;
enemyProjectiles.push(projectile);
}
}
if (this.health <= (20 + level * 5)/2){
this.phase = 2;
this.color = 'orange';
}
}
shoot() {
const projectile = new Projectile(this.x, this.y + this.height / 2, 1);
enemyProjectiles.push(projectile);
}
}
// Projectile class
class Projectile {
constructor(x, y, direction) {
this.x = x;
this.y = y;
this.width = 5;
this.height = 15;
this.speedY = 7 * direction;
this.speedX = 0; // Allow for sideways movement in the future.
this.color = 'lime'; //player projectile color
if(direction === 1){
this.color = 'red'; //enemy projectile color
}
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x - this.width/2, this.y - this.height/2, this.width, this.height);
}
update() {
this.y += this.speedY;
this.x += this.speedX;
}
}
// Shield class
class Shield {
constructor(x, y) {
this.x = x;
this.y = y;
this.width = 60;
this.height = 20;
this.health = 5;
this.color = 'green';
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x - this.width/2, this.y - this.height/2, this.width, this.height);
}
update() {
//Shield color degrades with health
if(this.health <= 2) {
this.color = 'red';
}
}
}
// Power-up class
class PowerUp {
constructor(x, y, type) {
this.x = x;
this.y = y;
this.width = 20;
this.height = 20;
this.type = type;
this.color = 'cyan';
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x - this.width/2, this.y - this.height/2, this.width, this.height);
}
update() {
this.y += 2; // Move down the screen
}
}
// Background star class
class Star {
constructor() {
this.x = Math.random() * canvasWidth;
this.y = Math.random() * canvasHeight;
this.size = Math.random() * 2;
this.speed = Math.random() * 0.5;
}
draw() {
ctx.fillStyle = 'white';
ctx.fillRect(this.x, this.y, this.size, this.size);
}
update() {
this.y += this.speed;
if (this.y > canvasHeight) {
this.y = 0;
this.x = Math.random() * canvasWidth;
}
}
}
// Collision detection function
function collision(a, b) {
return !(
a.x - a.width/2 > b.x + b.width/2 ||
a.x + a.width/2 < b.x - b.width/2 ||
a.y - a.height/2 > b.y + b.height/2 ||
a.y + a.height/2 < b.y - b.height/2
);
}
// Game functions
function createEnemies() {
const enemyCount = 5 + level * 2; //Increase with levels
const enemyTypes = ['basic', 'fast', 'strong'];
for (let i = 0; i < enemyCount; i++) {
const x = randomNumber(25, canvasWidth - 25);
const y = randomNumber(50, 150);
const type = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];
enemies.push(new Enemy(x, y, type));
}
}
function createShields() {
const shieldCount = 4;
const spacing = canvasWidth / (shieldCount + 1);
for (let i = 1; i <= shieldCount; i++) {
const x = spacing * i;
const y = canvasHeight - 150;
shields.push(new Shield(x, y));
}
}
function createBackgroundStars() {
for (let i = 0; i < 100; i++) {
backgroundStars.push(new Star());
}
}
function spawnPowerUp() {
if (Math.random() < 0.1) { // 10% chance to spawn a power-up
const x = randomNumber(20, canvasWidth - 20);
const y = 20;
powerUps.push(new PowerUp(x, y, 'health')); // For now just health
}
}
function initializeGame() {
player = new Player();
enemies = [];
playerProjectiles = [];
enemyProjectiles = [];
shields = [];
powerUps = [];
score = 0;
lives = 3;
level = 1;
boss = null;
gameFrame = 0;
keys = {};
createEnemies();
createShields();
createBackgroundStars();
scoreDisplay.textContent = score;
}
// Game loop
function animate() {
if(!gameRunning) return;
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// Draw and update background stars
backgroundStars.forEach(star => {
star.draw();
star.update();
});
// Player update and draw
player.update();
player.draw();
if (keys[' '] && gameFrame % 10 === 0) { // Limit fire rate
player.shoot();
}
// Enemies update and draw
if (enemies.length === 0 && !boss) {
level++;
if (level % 3 === 0) {
boss = new Boss(); // Spawn a boss every few levels
} else {
createEnemies();
}
}
if (boss) {
boss.update();
boss.draw();
if (gameFrame % 100 === 0){
boss.shoot();
}
} else {
enemies.forEach(enemy => {
enemy.update();
enemy.draw();
if (Math.random() < 0.005){
enemy.shoot();
}
});
}
// Projectiles update and draw
playerProjectiles.forEach((projectile, index) => {
projectile.update();
projectile.draw();
// Remove projectile if it goes off screen
if (projectile.y < 0) {
playerProjectiles.splice(index, 1);
}
});
enemyProjectiles.forEach((projectile, index) => {
projectile.update();
projectile.draw();
// Remove projectile if it goes off screen
if (projectile.y > canvasHeight) {
enemyProjectiles.splice(index, 1);
}
});
// Shields update and draw
shields.forEach(shield => {
shield.update();
shield.draw();
});
//Powerups update and draw
powerUps.forEach((powerUp, index) => {
powerUp.update();
powerUp.draw();
if (powerUp.y > canvasHeight) {
powerUps.splice(index, 1);
}
});
// Collision detection
playerProjectiles.forEach((projectile, projectileIndex) => {
// Enemy collision
if (boss){
if (collision(projectile, boss)){
boss.health--;
playerProjectiles.splice(projectileIndex, 1);
if (boss.health <= 0){
boss = null;
score += 500;
scoreDisplay.textContent = score;
}
}
} else {
enemies.forEach((enemy, enemyIndex) => {
if (collision(projectile, enemy)) {
enemy.health--;
playerProjectiles.splice(projectileIndex, 1);
if (enemy.health <= 0) {
enemies.splice(enemyIndex, 1);
score += 100;
scoreDisplay.textContent = score;
spawnPowerUp(); //Chance of powerup on enemy death
}
}
});
}
// Shield collision
shields.forEach((shield, shieldIndex) => {
if (collision(projectile, shield)) {
shield.health--;
playerProjectiles.splice(projectileIndex, 1);
if (shield.health <= 0) {
shields.splice(shieldIndex, 1);
}
}
});
});
enemyProjectiles.forEach((projectile, projectileIndex) => {
// Player collision
if (collision(projectile, player)) {
if(!player.isInvincible){
lives--;
player.isInvincible = true;
player.invincibleTimer = 120; //2 seconds of invincibility
enemyProjectiles.splice(projectileIndex, 1);
}
if (lives <= 0) {
gameOver();
}
}
// Shield collision
shields.forEach((shield, shieldIndex) => {
if (collision(projectile, shield)) {
shield.health--;
enemyProjectiles.splice(projectileIndex, 1);
if (shield.health <= 0) {
shields.splice(shieldIndex, 1);
}
}
});
});
powerUps.forEach((powerUp, powerUpIndex) => {
if (collision(powerUp, player)) {
if (powerUp.type === 'health') {
lives = Math.min(3, lives + 1); //Cap lives at 3;
}
powerUps.splice(powerUpIndex, 1);
}
});
if (player.isInvincible) {
player.invincibleTimer--;
if (player.invincibleTimer <= 0) {
player.isInvincible = false;
}
}
gameFrame++;
}
function gameOver() {
gameRunning = false;
gameOverScreen.style.display = 'flex';
finalScoreDisplay.textContent = `Score: ${score}`;
if (score > highScore) {
highScore = score;
localStorage.setItem('highScore', highScore);
highScoreDisplay.textContent = highScore;
}
}
function restartGame() {
gameOverScreen.style.display = 'none';
initializeGame();
gameRunning = true;
animate();
}
function startGame() {
startScreen.style.display = 'none';
initializeGame();
gameRunning = true;
animate();
}
// Start the game loop
//animate(); //start after pressing start button
</script>
</body>
</html>