Breakout Game with Vanilla JavaScript

Breakout Game with Vanilla JavaScript
Code Snippet:2D Breakout Game with Vanilla JavaScript
Author: Khaled Ahmed Younes
Published: January 20, 2024
Last Updated: January 22, 2024
Downloads: 443
License: MIT
Edit Code online: View on CodePen
Read More

This code creates a “Breakout Game” using Vanilla JavaScript. It renders a canvas with bricks, a ball, and a paddle. The ball bounces off the walls, bricks, and the paddle, with the aim of breaking the bricks. The paddle can be controlled using the keyboard or mouse to prevent the ball from falling off the screen.

The game tracks the score and lives, ending when the player loses all lives. It also includes a pause functionality triggered by pressing the ‘Esc’ key. Additionally, there’s an option to enable autoplay.

How to Create a Breakout Game With Vanilla Javascript

1. First of all, load the Bootstrap CSS by adding the following CDN link into the head tag of your HTML document.

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>

2. Create the HTML code to set up the game canvas and other elements.

<canvas id="myCanvas" width="480" height="320"></canvas>
<div class="autoplay-toggle">
  <input id="autoplay" type="checkbox" name="autoplay" value="Autoplay"> Enable Autoplay?<br>
</div>
<p><strong>Press 'Esc' to pause the game</strong></p>

3. To make your game visually appealing, add CSS styles to your HTML. Create a separate CSS file and link it to your HTML file or include the styles in a <style> block within the HTML file. It styles the game canvas, paddle, bricks, and other elements. You can customize it to match your preferences.

* {
    margin: 0;
    padding: 0;
}

canvas {    
    background-color: #eee;
    display: block;
    margin: 20px auto;
}
#lose-message {
    font-size: 2em;
    text-align: center;
    margin: 10px;
    color: red;
    font-weight: bold;
    font-family: sans-serif;
    display: none;
}

.autoplay-toggle {
    display: inline-block;
    position: relative;
    left: 50%;
    margin-top: 10px;
    transform: translate(-50%, 0);
}

p {
  text-align: center;
}

4. Finally, it’s time to add the JavaScript code that powers the Breakout game. Copy and paste the following JavaScript code into a separate .js file and link it to your HTML file using the <script> tag. Ensure the script tag is placed just before the closing </body> tag.

// Canvas related variables
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

// Game related variables
var lives = 3;
var gameOver = false;
var paused = false;
var score = 0;
var autoplayToggle = document.getElementById("autoplay");
autoplayToggle.checked = false;

// Ball relates variables
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 1.5;
var dy = -1.5;
var ballRadius = 10;
var maxSpeed = 3.5;
var speedMultiplier = 1;

// Paddle related variables
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var paddleY = canvas.height - (paddleHeight + 5);
var rightPressed = false;
var leftPressed = false;
var paddleSpeed = 7;

// Brick related variables
var brickRowCount = 3;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var bricks = [];
for (c = 0; c < brickColumnCount; c++) {
    bricks[c] = [];
    for (r = 0; r < brickRowCount; r++) {
        bricks[c][r] = {
            x: 0,
            y: 0,
            status: 2
        };
    }
}

function draw() {    
    if (!paused) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        if (autoplayToggle.checked) {
            autoPlay();
        }
        drawPaddle();
        drawBricks();
        drawBall();
        collisionDetection();
        drawScore();
        drawLives();

        x += dx;
        y += dy;
    }
    if (x + dx > (canvas.width - ballRadius) || x + dx < ballRadius) {
        dx = -dx;
    }
    if (y + dy < ballRadius) {
        dy = -dy;
    } else if (y + dy > (canvas.height - (2 * ballRadius))) {

        if (x > paddleX && x < paddleX + paddleWidth) {
            dy = -dy;
            if (Math.abs(dx) < maxSpeed && Math.abs(dy) < maxSpeed) {
                dx *= speedMultiplier;
                dy *= speedMultiplier;

                console.log(dx);
            }
        } else {
            lives--;
            if (!lives) {
                alert("GAME OVER");
                document.location.reload();
            } else {
                x = canvas.width / 2;
                y = canvas.height - 30;
                dx = 2;
                dy = -2;
                paddleX = (canvas.width - paddleWidth) / 2;
            }

        }

    }

    if (lives <= 0) {
        loseMessage.style.display = "block";
    }
    
    requestAnimationFrame(draw);
}

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
    ctx.fillStyle = '#0095DD';
    ctx.fill();
    ctx.closePath();


}

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, paddleY, paddleWidth, paddleHeight);
    ctx.fillStyle = "#00FFFF";
    ctx.fill();
    ctx.closePath();

    if (rightPressed) {
        if (paddleX + paddleSpeed < canvas.width - paddleWidth) {
            paddleX += paddleSpeed;
        }
    } else if (leftPressed) {
        if (paddleX - paddleSpeed > 0) {
            paddleX -= paddleSpeed;
        }
    }
}

function autoPlay() {
    var newX = x - (paddleWidth / 2);

    if (newX >= 0 && newX <= canvas.width - paddleWidth) {
        paddleX = newX;
    }
}

function drawBricks() {
    for (c = 0; c < brickColumnCount; c++) {
        for (r = 0; r < brickRowCount; r++) {
            if (bricks[c][r].status > 0) {
                var brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
                var brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
                bricks[c][r].x = brickX;
                bricks[c][r].y = brickY;
                ctx.beginPath();
                ctx.rect(brickX, brickY, brickWidth, brickHeight);
                ctx.fillStyle = bricks[c][r].status == 2 ? "#ddd000" : "#dd1e00";
                ctx.fill();
                ctx.closePath();
            }
        }
    }
}

function collisionDetection() {
    for (c = 0; c < brickColumnCount; c++) {
        for (r = 0; r < brickRowCount; r++) {
            var b = bricks[c][r];
            if (b.status != 0) {
                if (x > b.x && x < b.x + brickWidth && y - ballRadius > b.y && y - ballRadius < b.y + brickHeight) {
                    dy = -dy;
                    b.status--;

                    if (b.status == 0) {
                        dy = -dy;
                        score++;

                        if (score == brickRowCount * brickColumnCount) {
                            alert("YOU WIN, CONGRATULATIONS!");
                            document.location.reload();
                        }
                    }
                }
            }
        }
    }
}

function drawScore() {
    ctx.font = "16px Arial";
    ctx.fillStyle = "#0095DD";
    ctx.fillText("Score: " + score, 8, 20);
}

function drawLives() {
    ctx.font = "16px Arial";
    ctx.fillStyle = "#0095DD";
    ctx.fillText("Lives: " + lives, canvas.width - 65, 20);
}

function keyDownHandler(e) {
    if (e.keyCode == 39 || e.keyCode == 68) {
        rightPressed = true;
    } else if (e.keyCode == 37 || e.keyCode == 65) {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if (e.keyCode == 39 || e.keyCode == 68) {
        rightPressed = false;
    } else if (e.keyCode == 37 || e.keyCode == 65) {
        leftPressed = false;
    }
}

function pauseKeyPress(e) {
    if (e.keyCode == 27) {
        paused = !paused;
        console.log(paused);
    }
}

function mouseMoveHandler(e) {
    var relativeX = e.clientX - canvas.offsetLeft;
    if (relativeX > 0 && relativeX < canvas.width) {
        var newPaddleX = relativeX - paddleWidth / 2;

        if (newPaddleX >= 0 && newPaddleX + paddleWidth <= canvas.width) {
            paddleX = newPaddleX;
        }
    }
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("keyup", pauseKeyPress, false);
document.addEventListener("mousemove", mouseMoveHandler, false);
//setInterval(draw, 10);
draw();

That’s all! hopefully, you have successfully created a Breakout Game with Vanilla JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X