Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Space Shooter Game</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background-color: #000;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            font-family: Arial, sans-serif;
        }
        canvas {
            border: 2px solid #fff;
            background-color: #000;
        }
        #game-container {
            position: relative;
        }
        #score-display {
            position: absolute;
            top: 10px;
            left: 10px;
            color: white;
            font-size: 20px;
        }
        #game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 40px;
            text-align: center;
            display: none;
        }
        button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 10px 2px;
            cursor: pointer;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div id="game-container">
    <canvas id="gameCanvas" width="600" height="400"></canvas>
    <div id="score-display">Score: 0</div>
    <div id="game-over">
        <h2>Game Over</h2>
        <p>Your Score: <span id="final-score">0</span></p>
        <button id="restart-button">Play Again</button>
    </div>
</div>

<script>
    // Game setup
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const scoreDisplay = document.getElementById('score-display');
    const gameOverScreen = document.getElementById('game-over');
    const finalScoreDisplay = document.getElementById('final-score');
    const restartButton = document.getElementById('restart-button');

    // Game variables
    let score = 0;
    let gameOver = false;
    let animationId;

    // Player setup
    const player = {
        x: canvas.width / 2,
        y: canvas.height - 50,
        width: 30,
        height: 30,
        color: '#00FF00',
        speed: 5,
        shooting: false,
        shootingCooldown: 0
    };

    // Keys state
    const keys = {
        ArrowLeft: false,
        ArrowRight: false,
        ArrowUp: false,
        ArrowDown: false,
        Space: false
    };

    // Projectiles array
    let projectiles = [];

    // Enemies array
    let enemies = [];

    // Particles array (for explosions)
    let particles = [];

    // Game functions
    function drawPlayer() {
        ctx.fillStyle = player.color;
        ctx.fillRect(player.x - player.width / 2, player.y - player.height / 2, player.width, player.height);

        // Draw a gun on top of the player
        ctx.fillStyle = '#AAAAAA';
        ctx.fillRect(player.x - 3, player.y - player.height / 2 - 10, 6, 10);
    }

    function movePlayer() {
        if (keys.ArrowLeft && player.x > player.width / 2) {
            player.x -= player.speed;
        }
        if (keys.ArrowRight && player.x < canvas.width - player.width / 2) {
            player.x += player.speed;
        }
        if (keys.ArrowUp && player.y > player.height / 2) {
            player.y -= player.speed;
        }
        if (keys.ArrowDown && player.y < canvas.height - player.height / 2) {
            player.y += player.speed;
        }

        // Handle shooting
        if (keys.Space && player.shootingCooldown <= 0) {
            projectiles.push({
                x: player.x,
                y: player.y - player.height / 2,
                radius: 3,
                color: '#FFFF00',
                speed: 8
            });
            player.shootingCooldown = 10; // Set cooldown to prevent rapid fire
        }

        // Reduce shooting cooldown
        if (player.shootingCooldown > 0) {
            player.shootingCooldown--;
        }
    }

    function drawProjectiles() {
        projectiles.forEach(projectile => {
            ctx.beginPath();
            ctx.arc(projectile.x, projectile.y, projectile.radius, 0, Math.PI * 2);
            ctx.fillStyle = projectile.color;
            ctx.fill();
            ctx.closePath();
        });
    }

    function moveProjectiles() {
        projectiles.forEach((projectile, index) => {
            projectile.y -= projectile.speed;

            // Remove projectiles that are off screen
            if (projectile.y + projectile.radius < 0) {
                projectiles.splice(index, 1);
            }
        });
    }

    function createEnemy() {
        const radius = Math.random() * 20 + 10;
        const x = Math.random() * (canvas.width - radius * 2) + radius;
        const speed = Math.random() * 2 + 1;

        enemies.push({
            x: x,
            y: -radius,
            radius: radius,
            color: `hsl(${Math.random() * 360}, 50%, 50%)`,
            speed: speed
        });
    }

    function drawEnemies() {
        enemies.forEach(enemy => {
            ctx.beginPath();
            ctx.arc(enemy.x, enemy.y, enemy.radius, 0, Math.PI * 2);
            ctx.fillStyle = enemy.color;
            ctx.fill();
            ctx.closePath();
        });
    }

    function moveEnemies() {
        enemies.forEach((enemy, index) => {
            enemy.y += enemy.speed;

            // Check if enemy hit the bottom
            if (enemy.y - enemy.radius > canvas.height) {
                enemies.splice(index, 1);
                score -= 10;
                if (score < 0) score = 0;
                updateScore();
            }

            // Check collision with player
            const dist = Math.hypot(player.x - enemy.x, player.y - enemy.y);
            if (dist - enemy.radius - player.width / 2 < 0) {
                // Game over
                endGame();
            }

            // Check collision with projectiles
            projectiles.forEach((projectile, projectileIndex) => {
                const dist = Math.hypot(projectile.x - enemy.x, projectile.y - enemy.y);

                // If projectile hits enemy
                if (dist - enemy.radius - projectile.radius < 0) {
                    // Create explosion
                    for (let i = 0; i < enemy.radius; i++) {
                        particles.push({
                            x: enemy.x,
                            y: enemy.y,
                            radius: Math.random() * 2,
                            color: enemy.color,
                            velocity: {
                                x: (Math.random() - 0.5) * 8,
                                y: (Math.random() - 0.5) * 8
                            },
                            alpha: 1
                        });
                    }

                    // Remove enemy and projectile
                    enemies.splice(index, 1);
                    projectiles.splice(projectileIndex, 1);

                    // Increase score
                    score += Math.floor(enemy.radius);
                    updateScore();
                }
            });
        });
    }

    function drawParticles() {
        particles.forEach((particle, index) => {
            if (particle.alpha <= 0) {
                particles.splice(index, 1);
                return;
            }

            ctx.save();
            ctx.globalAlpha = particle.alpha;
            ctx.beginPath();
            ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
            ctx.fillStyle = particle.color;
            ctx.fill();
            ctx.restore();
        });
    }

    function moveParticles() {
        particles.forEach(particle => {
            particle.x += particle.velocity.x;
            particle.y += particle.velocity.y;
            particle.alpha -= 0.01;
        });
    }

    function updateScore() {
        scoreDisplay.textContent = `Score: ${score}`;
    }

    function endGame() {
        gameOver = true;
        finalScoreDisplay.textContent = score;
        gameOverScreen.style.display = 'block';
        cancelAnimationFrame(animationId);
    }

    // Game loop
    function gameLoop() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        drawPlayer();
        movePlayer();

        drawProjectiles();
        moveProjectiles();

        drawEnemies();
        moveEnemies();

        drawParticles();
        moveParticles();

        // Randomly spawn enemies
        if (Math.random() < 0.02) {
            createEnemy();
        }

        // Continue the game loop
        if (!gameOver) {
            animationId = requestAnimationFrame(gameLoop);
        }
    }

    // Key event listeners
    document.addEventListener('keydown', (event) => {
        if (event.key === 'ArrowLeft') keys.ArrowLeft = true;
        if (event.key === 'ArrowRight') keys.ArrowRight = true;
        if (event.key === 'ArrowUp') keys.ArrowUp = true;
        if (event.key === 'ArrowDown') keys.ArrowDown = true;
        if (event.key === ' ') keys.Space = true;
    });

    document.addEventListener('keyup', (event) => {
        if (event.key === 'ArrowLeft') keys.ArrowLeft = false;
        if (event.key === 'ArrowRight') keys.ArrowRight = false;
        if (event.key === 'ArrowUp') keys.ArrowUp = false;
        if (event.key === 'ArrowDown') keys.ArrowDown = false;
        if (event.key === ' ') keys.Space = false;
    });

    // Restart button listener
    restartButton.addEventListener('click', () => {
        // Reset game variables
        score = 0;
        updateScore();
        gameOver = false;
        gameOverScreen.style.display = 'none';

        // Reset player position
        player.x = canvas.width / 2;
        player.y = canvas.height - 50;

        // Clear arrays
        projectiles = [];
        enemies = [];
        particles = [];

        // Start the game again
        gameLoop();
    });

    // Start the game
    gameLoop();
</script>
</body>
</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console