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

Write a code of a space invaders like game with 8 bit graphics in JavaScript and html

  1. User

    Write a code of a space invaders like game with 8 bit graphics in JavaScript and html

  2. Assistant

    Sure! Below is an example of a simple Space Invaders-like game with 8-bit graphics using JavaScript and HTML. This game uses the HTML5 canvas element for rendering and basic 2D graphics. You'll be able to control the player ship using the arrow keys and shoot lasers to destroy the invading aliens.

    HTML Code (index.html)

    Create an index.html file and insert the following code:

    <!DOCTYPE html>
    <html>
    <head>
        <title>8-Bit Space Invaders</title>
        <style>
            canvas {
                background-color: black;
                display: block;
                margin: 0 auto;
                image-rendering: pixelated; /* Makes the graphics look 8-bit */
            }
            body {
                text-align: center;
                color: white;
                font-family: Arial, sans-serif;
            }
        </style>
    </head>
    <body>
        <h1>8-Bit Space Invaders</h1>
        <canvas id="gameCanvas" width="480" height="640"></canvas>
        <script src="game.js"></script>
    </body>
    </html>
    
    • Explanation: This HTML file sets up the page with a centered canvas element where the game will be rendered. The image-rendering: pixelated; CSS property is used to give the graphics an 8-bit pixelated look.

    JavaScript Code (game.js)

    Create a game.js file in the same directory and insert the following code:

    // game.js
    
    /** @type {HTMLCanvasElement} */
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    
    // Game settings
    const PLAYER_SPEED = 5;
    const BULLET_SPEED = 7;
    const INVADER_SPEED = 1;
    const INVADER_DROP_DISTANCE = 20;
    const INVADER_SHOOT_CHANCE = 0.001; // Chance per frame an invader shoots
    
    // Game variables
    let player;
    let bullets = [];
    let invaders = [];
    let invaderBullets = [];
    let gameOver = false;
    let score = 0;
    
    // Images for sprites
    const spriteSize = 32;
    const playerSprite = new Image();
    playerSprite.src = 'data:image/png;base64,...'; // Base64 image data for player sprite
    const invaderSprite = new Image();
    invaderSprite.src = 'data:image/png;base64,...'; // Base64 image data for invader sprite
    
    // Key press variables
    const keys = {};
    
    // Initialize game
    function init() {
        // Create player object
        player = {
            x: canvas.width / 2 - spriteSize / 2,
            y: canvas.height - spriteSize * 2,
            width: spriteSize,
            height: spriteSize,
            sprite: playerSprite
        };
    
        // Create invaders
        const rows = 5;
        const cols = 9;
        const spacing = 10;
        const offsetX = (canvas.width - (cols * (spriteSize + spacing) - spacing)) / 2;
        for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
                invaders.push({
                    x: offsetX + col * (spriteSize + spacing),
                    y: 50 + row * (spriteSize + spacing),
                    width: spriteSize,
                    height: spriteSize,
                    sprite: invaderSprite,
                    isAlive: true
                });
            }
        }
    
        // Event listeners
        document.addEventListener('keydown', (e) => keys[e.code] = true);
        document.addEventListener('keyup', (e) => keys[e.code] = false);
    
        // Start game loop
        requestAnimationFrame(gameLoop);
    }
    
    // Game loop
    function gameLoop() {
        update();
        draw();
    
        if (!gameOver) {
            requestAnimationFrame(gameLoop);
        } else {
            drawGameOver();
        }
    }
    
    // Update game state
    function update() {
        // Move player
        if (keys['ArrowRight'] && player.x + player.width < canvas.width) {
            player.x += PLAYER_SPEED;
        }
        if (keys['ArrowLeft'] && player.x > 0) {
            player.x -= PLAYER_SPEED;
        }
    
        // Player shooting
        if (keys['Space']) {
            shootBullet();
            keys['Space'] = false; // Prevent continuous shooting
        }
    
        // Move bullets
        bullets.forEach((bullet, index) => {
            bullet.y -= BULLET_SPEED;
            // Remove bullet if off-screen
            if (bullet.y + bullet.height < 0) {
                bullets.splice(index, 1);
            }
        });
    
        // Move invaders
        let changeDirection = false;
        invaders.forEach(invader => {
            if (invader.isAlive) {
                invader.x += INVADER_SPEED;
                // Check for edge collision
                if (invader.x + invader.width > canvas.width || invader.x < 0) {
                    changeDirection = true;
                }
                // Random shooting
                if (Math.random() < INVADER_SHOOT_CHANCE) {
                    invaderShoot(invader);
                }
            }
        });
    
        // Change invader direction and move down
        if (changeDirection) {
            INVADER_SPEED *= -1;
            invaders.forEach(invader => {
                invader.y += INVADER_DROP_DISTANCE;
            });
        }
    
        // Move invader bullets
        invaderBullets.forEach((bullet, index) => {
            bullet.y += BULLET_SPEED / 2;
            // Remove bullet if off-screen
            if (bullet.y > canvas.height) {
                invaderBullets.splice(index, 1);
            }
        });
    
        // Check for collisions
        checkCollisions();
    
        // Check for game over
        invaders.forEach(invader => {
            if (invader.isAlive && invader.y + invader.height >= player.y) {
                gameOver = true;
            }
        });
    }
    
    // Drawing functions
    function draw() {
        // Clear canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    
        // Draw player
        drawSprite(player);
    
        // Draw bullets
        bullets.forEach(bullet => drawRect(bullet, 'white'));
    
        // Draw invaders
        invaders.forEach(invader => {
            if (invader.isAlive) {
                drawSprite(invader);
            }
        });
    
        // Draw invader bullets
        invaderBullets.forEach(bullet => drawRect(bullet, 'red'));
    
        // Draw score
        ctx.font = '20px Arial';
        ctx.fillStyle = 'white';
        ctx.fillText(`Score: ${score}`, 10, 30);
    }
    
    function drawRect(obj, color) {
        ctx.fillStyle = color;
        ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
    }
    
    function drawSprite(obj) {
        ctx.drawImage(obj.sprite, obj.x, obj.y, obj.width, obj.height);
    }
    
    function drawGameOver() {
        ctx.font = '48px Arial';
        ctx.fillStyle = 'red';
        ctx.textAlign = 'center';
        ctx.fillText('GAME OVER', canvas.width / 2, canvas.height / 2);
    }
    
    // Helper functions
    function shootBullet() {
        bullets.push({
            x: player.x + player.width / 2 - 2,
            y: player.y,
            width: 4,
            height: 10
        });
    }
    
    function invaderShoot(invader) {
        invaderBullets.push({
            x: invader.x + invader.width / 2 - 2,
            y: invader.y + invader.height,
            width: 4,
            height: 10
        });
    }
    
    function checkCollisions() {
        // Player bullets and invaders
        bullets.forEach((bullet, bIndex) => {
            invaders.forEach((invader, iIndex) => {
                if (invader.isAlive && isColliding(bullet, invader)) {
                    invader.isAlive = false;
                    bullets.splice(bIndex, 1);
                    score += 10;
                }
            });
        });
    
        // Invader bullets and player
        invaderBullets.forEach((bullet, index) => {
            if (isColliding(bullet, player)) {
                gameOver = true;
            }
        });
    }
    
    function isColliding(a, b) {
        return a.x < b.x + b.width &&
            a.x + a.width > b.x &&
            a.y < b.y + b.height &&
            a.y + a.height > b.y;
    }
    
    // Start the game
    init();
    
    • Explanation:
      • Game Variables: Sets up constants for speeds and game elements.
      • init() Function: Initializes the player and invader objects and sets up event listeners.
      • Game Loop: Consists of update() and draw() functions, which run every frame.
      • update(): Handles the game logic, including player movement, bullet movement, invader movement, and collision detection.
      • draw(): Handles all the rendering of game objects on the canvas.
      • Collision Detection: The isColliding() function checks for collisions between rectangles.

    Adding Sprites

    The game uses sprites for the player and invaders. Since we can't load external images here, you can use placeholder images or simple shapes. Alternatively, you can create simple sprite images and load them.

    For example, to load an image from a URL:

    const playerSprite = new Image();
    playerSprite.src = 'player.png'; // Replace with the path to your image
    

    Make sure to place the image files in the same directory as your HTML and JavaScript files.

    Running the Game

    1. Create Files: Ensure you have the index.html and game.js files in the same directory.
    2. Add Sprite Images: If using external images, add player.png and invader.png to the same directory.
    3. Open the Game: Open index.html in a modern web browser like Chrome or Firefox.
    4. Controls:
      • Move Left: Left Arrow Key
      • Move Right: Right Arrow Key
      • Shoot: Space Bar

    Notes

    • Base64 Images: For simplicity, placeholder Base64 image data is used in the code. Replace 'data:image/png;base64,...' with actual Base64-encoded image data or load images from files.
    • Customization: Feel free to customize the sprites, speeds, and game mechanics to enhance the game.
    • Browser Compatibility: This game should work on most modern browsers that support the HTML5 canvas and JavaScript ES6 features.

    Sample Sprites (Optional)

    If you want to use simple colored rectangles instead of images, you can modify the drawSprite function:

    function drawSprite(obj) {
        ctx.fillStyle = 'white'; // Change color as needed
        ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
    }
    

    Enhancements

    • Add Levels: Increase the speed of invaders as the player progresses.
    • Lives System: Give the player multiple lives before the game is over.
    • Sound Effects: Use the Web Audio API to add sounds for shooting and explosions.
    • High Score Tracking: Store and display high scores using localStorage.

    Enjoy your retro-style Space Invaders game!