Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

build me a space invader game in javascript

  1. User

    build me a space invader game in javascript

  2. Assistant

    Certainly! Let's build a simple Space Invaders game using JavaScript and HTML5 Canvas. This game will feature a player-controlled spaceship that can move left and right and shoot bullets to destroy descending invaders.


    Overview

    • Technologies Used: HTML5, CSS, JavaScript
    • Game Features:
      • Player spaceship that can move left and right.
      • Invaders that move horizontally and descend.
      • Bullets that the player can fire to destroy invaders.
      • Basic collision detection between bullets and invaders.

    Step 1: Set Up the HTML Structure

    Create an index.html file with the following content:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Space Invaders Game</title>
        <style>
            body {
                background-color: #000;
                margin: 0;
                overflow: hidden;
            }
            #gameCanvas {
                display: block;
                margin: 0 auto;
                background-color: #000;
                border: 1px solid #fff;
            }
        </style>
    </head>
    <body>
        <canvas id="gameCanvas" width="800" height="600"></canvas>
        <script src="main.js"></script>
    </body>
    </html>
    

    Explanation:

    • We set up the basic HTML document with a <canvas> element where the game will be rendered.
    • The canvas has an id of gameCanvas and dimensions of 800x600 pixels.
    • We include a link to main.js, which will contain our game logic.
    • Basic styles are applied to center the canvas and set the background colors.

    Step 2: Write the Game Logic in JavaScript

    Create a main.js file and add the following code:

    // Get the canvas and context
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    
    // Define game constants
    const canvasWidth = canvas.width;
    const canvasHeight = canvas.height;
    
    // Player properties
    const playerWidth = 50;
    const playerHeight = 20;
    let playerX = (canvasWidth - playerWidth) / 2;
    const playerY = canvasHeight - playerHeight - 10;
    const playerSpeed = 7;
    
    // Bullet properties
    const bulletWidth = 5;
    const bulletHeight = 10;
    const bulletSpeed = 10;
    let bullets = [];
    
    // Invader properties
    const invaderRowCount = 4;
    const invaderColumnCount = 8;
    const invaderWidth = 40;
    const invaderHeight = 20;
    const invaderPadding = 20;
    const invaderOffsetTop = 50;
    const invaderOffsetLeft = 50;
    let invaders = [];
    let invaderSpeed = 1;
    let invaderDirection = 1; // 1 for right, -1 for left
    
    // Keyboard controls
    let rightPressed = false;
    let leftPressed = false;
    let spacePressed = false;
    
    // Initialize invaders
    function initInvaders() {
        for (let row = 0; row < invaderRowCount; row++) {
            invaders[row] = [];
            for (let col = 0; col < invaderColumnCount; col++) {
                const x = invaderOffsetLeft + col * (invaderWidth + invaderPadding);
                const y = invaderOffsetTop + row * (invaderHeight + invaderPadding);
                invaders[row][col] = { x, y, status: 1 };
            }
        }
    }
    initInvaders();
    
    // Event listeners for keyboard input
    document.addEventListener('keydown', keyDownHandler);
    document.addEventListener('keyup', keyUpHandler);
    
    function keyDownHandler(e) {
        if (e.key === 'ArrowRight' || e.key === 'Right') {
            rightPressed = true;
        }
        if (e.key === 'ArrowLeft' || e.key === 'Left') {
            leftPressed = true;
        }
        if (e.key === ' ' || e.key === 'Spacebar') {
            spacePressed = true;
        }
    }
    
    function keyUpHandler(e) {
        if (e.key === 'ArrowRight' || e.key === 'Right') {
            rightPressed = false;
        }
        if (e.key === 'ArrowLeft' || e.key === 'Left') {
            leftPressed = false;
        }
        if (e.key === ' ' || e.key === 'Spacebar') {
            spacePressed = false;
            fireBullet();
        }
    }
    
    // Draw player spaceship
    function drawPlayer() {
        ctx.fillStyle = '#00ff00'; // Green color
        ctx.fillRect(playerX, playerY, playerWidth, playerHeight);
    }
    
    // Move player spaceship
    function movePlayer() {
        if (rightPressed && playerX < canvasWidth - playerWidth) {
            playerX += playerSpeed;
        }
        if (leftPressed && playerX > 0) {
            playerX -= playerSpeed;
        }
    }
    
    // Fire a bullet
    function fireBullet() {
        bullets.push({
            x: playerX + playerWidth / 2 - bulletWidth / 2,
            y: playerY,
            width: bulletWidth,
            height: bulletHeight,
            speed: bulletSpeed,
        });
    }
    
    // Draw bullets
    function drawBullets() {
        ctx.fillStyle = '#ffff00'; // Yellow color
        bullets.forEach((bullet, index) => {
            ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
            bullet.y -= bullet.speed;
            // Remove bullets that go off-screen
            if (bullet.y + bullet.height < 0) {
                bullets.splice(index, 1);
            }
        });
    }
    
    // Draw invaders
    function drawInvaders() {
        invaders.forEach(row => {
            row.forEach(invader => {
                if (invader.status === 1) {
                    ctx.fillStyle = '#ff0000'; // Red color
                    ctx.fillRect(invader.x, invader.y, invaderWidth, invaderHeight);
                }
            });
        });
    }
    
    // Move invaders
    function moveInvaders() {
        let edgeReached = false;
        invaders.forEach(row => {
            row.forEach(invader => {
                if (invader.status === 1) {
                    invader.x += invaderSpeed * invaderDirection;
                    if (invader.x + invaderWidth > canvasWidth || invader.x < 0) {
                        edgeReached = true;
                    }
                }
            });
        });
        if (edgeReached) {
            invaderDirection *= -1;
            invaders.forEach(row => {
                row.forEach(invader => {
                    invader.y += invaderHeight;
                });
            });
        }
    }
    
    // Collision detection
    function collisionDetection() {
        bullets.forEach((bullet, bIndex) => {
            invaders.forEach(row => {
                row.forEach((invader, iIndex) => {
                    if (invader.status === 1) {
                        if (
                            bullet.x < invader.x + invaderWidth &&
                            bullet.x + bullet.width > invader.x &&
                            bullet.y < invader.y + invaderHeight &&
                            bullet.y + bullet.height > invader.y
                        ) {
                            invader.status = 0;
                            bullets.splice(bIndex, 1);
                        }
                    }
                });
            });
        });
    }
    
    // Check for game over condition
    function checkGameOver() {
        for (let row of invaders) {
            for (let invader of row) {
                if (invader.status === 1 && invader.y + invaderHeight >= playerY) {
                    alert('Game Over!');
                    document.location.reload();
                    return;
                }
            }
        }
    }
    
    // The main draw function
    function draw() {
        ctx.clearRect(0, 0, canvasWidth, canvasHeight); // Clear the canvas
        drawPlayer();
        drawBullets();
        drawInvaders();
        movePlayer();
        moveInvaders();
        collisionDetection();
        checkGameOver();
    
        requestAnimationFrame(draw);
    }
    
    // Start the game loop
    draw();
    

    Explanation:

    • Game Initialization:
      • Canvas and Context: We get the canvas element and its drawing context.
      • Game Constants: Define dimensions and properties for the player, bullets, and invaders.
      • Invaders Initialization: We create a 2D array to store invaders and initialize their positions.
    • Player Controls:
      • Keyboard Events: We add event listeners for keydown and keyup to track player input.
      • Movement Functions: Move the player ship based on key presses.
    • Game Objects Rendering:
      • Drawing Functions: Separate functions to draw the player, bullets, and invaders.
      • Movement Functions: Functions to move bullets upward and invaders horizontally.
    • Game Mechanics:
      • Bullet Firing: Players can fire bullets by pressing the spacebar.
      • Collision Detection: We check for collisions between bullets and invaders and update their statuses.
      • Invader Movement: Invaders move horizontally and change direction when they hit the canvas edges.
      • Game Over Check: The game checks if any invaders have reached the player's level.
    • Game Loop:
      • Draw Function: Clears the canvas and redraws all game objects. Uses requestAnimationFrame for smooth animation.

    Step 3: Run the Game

    1. Set Up the Project Folder:

      • Create a new folder for the game project.
      • Place the index.html and main.js files inside this folder.
    2. Open the Game in a Web Browser:

      • Open the index.html file in your preferred web browser (e.g., Chrome, Firefox, Edge).
      • You should see the game canvas displayed.
    3. Gameplay Controls:

      • Move Left: Press the Left Arrow key.
      • Move Right: Press the Right Arrow key.
      • Fire Bullet: Press the Spacebar key.

    Enhancements and Customizations

    Now that you have a basic Space Invaders game, you can enhance it with additional features:

    • Scoring System:

      • Add a variable to keep track of the player's score.
      • Display the score on the canvas or on the page.
    • Levels and Difficulty:

      • Increase the invader speed after clearing all invaders.
      • Add more rows or columns of invaders for higher levels.
    • Player Lives:

      • Implement a lives system where the player has multiple chances before the game is over.
      • Display the number of remaining lives.
    • Sound Effects:

      • Incorporate sounds for shooting, invader movements, and explosions.
    • Graphics and Animations:

      • Replace rectangles with images for the player and invaders.
      • Add explosion animations when invaders are hit.
    • Mobile Controls:

      • Add touch controls to make the game playable on mobile devices.

    Conclusion

    You've successfully created a basic Space Invaders game using JavaScript and HTML5 Canvas! This project is a great starting point to learn about game development. Feel free to modify and expand the game to add your own unique features.


    Happy Coding!