JSFiddle - React, Tailwind, and code Playground

by falldeaf

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Asteroids Style Game</title>
    <style>
        canvas {
            display: block;
            background: #000;
        }
        #score {
            color: white;
            position: absolute;
            top: 10px;
            left: 10px;
        }
    </style>
</head>
<body>
    <div id="score">Score: 0</div>
    <canvas id="gameCanvas"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.17.1/matter.min.js"></script>
    <script src="game.js"></script>
</body>
</html>

JavaScript

// Matter.js module aliases
const Engine = Matter.Engine,
      Render = Matter.Render,
      World = Matter.World,
      Bodies = Matter.Bodies,
      Body = Matter.Body,
      Events = Matter.Events,
      Composite = Matter.Composite;

// Create an engine
const engine = Engine.create();
engine.world.gravity.y = 0; // Turn off gravity

// Create a renderer
const render = Render.create({
    element: document.body,
    canvas: document.getElementById('gameCanvas'),
    engine: engine,
    options: {
        width: 800,
        height: 600,
        wireframes: false,
        background: '#000'
    }
});

// Create the ship (an arrow shape)
const ship = Bodies.fromVertices(400, 300, [
    { x: 0, y: -20 },   // Nose
    { x: 15, y: 20 },   // Right wing
    { x: 0, y: 10 },    // Center bottom
    { x: -15, y: 20 }   // Left wing
], {
    render: {
        fillStyle: 'white'
    }
});
Body.setInertia(ship, Infinity);

// Create cave walls
const caveSegments = [];
const caveWidth = 800;
const caveHeight = 600;
const segmentWidth = 50;
const amplitude = 100;
const frequency = 0.05;

for (let x = 0; x < caveWidth; x += segmentWidth) {
    const y = caveHeight / 2 + Math.sin(x * frequency) * amplitude;
    caveSegments.push(Bodies.rectangle(x, y, segmentWidth, 20, { isStatic: true, render: { fillStyle: 'gray' } }));
    caveSegments.push(Bodies.rectangle(x, y + 200, segmentWidth, 20, { isStatic: true, render: { fillStyle: 'gray' } }));
}

// Add all bodies to the world
World.add(engine.world, [ship, ...caveSegments]);

// Add controls
document.addEventListener('keydown', (event) => {
    switch (event.code) {
        case 'ArrowUp':
            const forceMagnitude = 0.001;
            const angle = ship.angle;
            const force = {
                x: Math.cos(angle) * forceMagnitude,
                y: Math.sin(angle) * forceMagnitude
            };
            Body.applyForce(ship, ship.position, force);
            break;
        case 'ArrowLeft':
           ...