JAVASCRIPT ARCADE GAME PROJECT ARCHITECTURE: CANVAS RENDERING, GAME LOOP & COLLISION DETECTION

Master building interactive 2D arcade games: HTML5 Canvas rendering context, `requestAnimationFrame` game loop timing, keyboard input polling, bounding-box collision detection algorithms, and state management.

📌 What is the Arcade Game Project?

The Arcade Game Project demonstrates the fundamentals of game development in JavaScript using the HTML5 API. Moving away from standard DOM element manipulation, canvas games render graphics programmatically inside a high-performance render loop powered by requestAnimationFrame. This project covers real-time keyboard event polling, entity velocity physics, boundary constraint clamping, and Axis-Aligned Bounding Box (AABB) collision detection.

Live Interactive Arcade Game: "Cyber Dodger"
Test the live arcade game below! Click Start Game to begin, use the Left and Right Arrow Keys (or A / D keys) to dodge incoming red data blocks, and click Stop Game to pause at any time.
Score: 0 High Score: 0
Controls: [←] [→] Arrow Keys or [A] [D] to Move
1. HTML Canvas Markup (`index.html`)
The HTML structure features a responsive element, heads-up display (HUD), and interactive Start/Stop action buttons for explicit game session control.
HTML (index.html)



    
    
    Cyber Dodger Arcade Game
    


    
Score: 0 High Score: 0
2. Game Engine & Physics Loop (`game.js`)
The JavaScript game engine handles explicit start/stop state toggles, frame updates, obstacle spawning, collision detection, and smooth rendering loops.
JavaScript (game.js)
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('scoreDisplay');
const highScoreDisplay = document.getElementById('highScoreDisplay');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');

// Game State Variables
let score = 0;
let highScore = localStorage.getItem('arcade_highscore') || 0;
let isGameRunning = false;
let isGameOver = false;
let gameFrames = 0;
let animationFrameId = null;

highScoreDisplay.textContent = `High Score: ${highScore}`;

// Player Entity
const player = {
    x: canvas.width / 2 - 20,
    y: canvas.height - 50,
    width: 40,
    height: 40,
    speed: 7,
    color: '#3b82f6'
};

// Obstacles Array
let obstacles = [];

// Input Polling Listeners
const keys = {};
window.addEventListener('keydown', (e) => {
    keys[e.code] = true;
});
window.addEventListener('keyup', (e) => {
    keys[e.code] = false;
});

// Spawn Obstacles
function spawnObstacle() {
    const width = Math.floor(Math.random() * 50) + 30;
    const x = Math.random() * (canvas.width - width);
    const speed = Math.random() * 3 + 3;
    obstacles.push({ x: x, y: -40, width: width, height: 25, speed: speed });
}

// AABB Collision Detection Algorithm
function checkCollision(rect1, rect2) {
    return (
        rect1.x < rect2.x + rect2.width &&
        rect1.x + rect1.width > rect2.x &&
        rect1.y < rect2.y + rect2.height &&
        rect1.y + rect1.height > rect2.y
    );
}

// Start Game Session
function startGame() {
    if (isGameRunning) return;
    if (isGameOver) {
        score = 0;
        gameFrames = 0;
        obstacles = [];
        isGameOver = false;
        player.x = canvas.width / 2 - 20;
    }
    isGameRunning = true;
    startBtn.textContent = 'Resuming...';
    startBtn.disabled = true;
    stopBtn.disabled = false;
    loop();
}

// Stop / Pause Game Session
function stopGame() {
    if (!isGameRunning) return;
    isGameRunning = false;
    cancelAnimationFrame(animationFrameId);
    startBtn.textContent = 'Resume Game';
    startBtn.disabled = false;
    stopBtn.disabled = true;

    ctx.fillStyle = 'rgba(15, 23, 42, 0.75)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#ffffff';
    ctx.font = 'bold 28px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('GAME PAUSED', canvas.width / 2, canvas.height / 2);
}

// Update Game Physics
function update() {
    if (!isGameRunning || isGameOver) return;

    gameFrames++;
    score = Math.floor(gameFrames / 30); // Clean score increment rate
    scoreDisplay.textContent = `Score: ${score}`;

    if ((keys['ArrowLeft'] || keys['KeyA']) && player.x > 0) {
        player.x -= player.speed;
    }
    if ((keys['ArrowRight'] || keys['KeyD']) && player.x < canvas.width - player.width) {
        player.x += player.speed;
    }

    if (gameFrames % 45 === 0) {
        spawnObstacle();
    }

    for (let i = obstacles.length - 1; i >= 0; i--) {
        obstacles[i].y += obstacles[i].speed;

        if (checkCollision(player, obstacles[i])) {
            isGameRunning = false;
            isGameOver = true;
            startBtn.textContent = 'Play Again';
            startBtn.disabled = false;
            stopBtn.disabled = true;

            if (score > highScore) {
                highScore = score;
                localStorage.setItem('arcade_highscore', highScore);
                highScoreDisplay.textContent = `High Score: ${highScore}`;
            }
        }

        if (obstacles[i].y > canvas.height) {
            obstacles.splice(i, 1);
        }
    }
}

// Render Graphics to Canvas
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = player.color;
    ctx.fillRect(player.x, player.y, player.width, player.height);
    ctx.strokeStyle = '#93c5fd';
    ctx.lineWidth = 2;
    ctx.strokeRect(player.x, player.y, player.width, player.height);

    ctx.fillStyle = '#ef4444';
    obstacles.forEach(obs => {
        ctx.fillRect(obs.x, obs.y, obs.width, obs.height);
        ctx.strokeStyle = '#fca5a5';
        ctx.strokeRect(obs.x, obs.y, obs.width, obs.height);
    });

    if (isGameOver) {
        ctx.fillStyle = 'rgba(15, 23, 42, 0.85)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.fillStyle = '#ffffff';
        ctx.font = 'bold 32px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('GAME OVER', canvas.width / 2, canvas.height / 2 - 20);

        ctx.fillStyle = '#94a3b8';
        ctx.font = '16px Arial';
        ctx.fillText('Click "Play Again" to Restart', canvas.width / 2, canvas.height / 2 + 25);
    }
}

// Main Game Loop
function loop() {
    update();
    draw();
    if (isGameRunning) {
        animationFrameId = requestAnimationFrame(loop);
    }
}

draw();
ctx.fillStyle = '#94a3b8';
ctx.font = '18px Arial';
ctx.textAlign = 'center';
ctx.fillText('Click "Start Game" to Begin', canvas.width / 2, canvas.height / 2);

startBtn.addEventListener('click', startGame);
stopBtn.addEventListener('click', stopGame);
stopBtn.disabled = true;