Creating a game over screen for a basic HTML/JS game

share link

by Abdul Rawoof A R dot icon Updated: Feb 5, 2024

technology logo
technology logo

Guide Kit Guide Kit  

Brick Breaking is a Breakout clone in which the player must smash a wall of bricks by deflecting a bouncing ball with a paddle.


Beginners and whoever looking to create a simple game over a screen using basic HTML/JS can utilize this code snippet with simple steps.


Using JavaScript and HTML we're creating a simple game over screen which is fun to watch the bouncing ball off the bricks and return to the paddle. But the game doesn't have any progression or goals. It will be great from the gameplay point of view to be able to lose. The logic behind the game is losing in the breakdown is simple. The main logic of the game is, if we miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over. The HTML file is very simple to create basic game applications as well as it is one of the easiest front-end programming languages to master also we can't be able to create a game only using HTML. For that, JavaScript is required to make different games. The element which is mainly used for creating games in HTML is the "<canvas>" element. Using HTML, CSS, and JavaScript we make the game looks pretty much good.


Here is an example of how you can create a game over screen for a basic HTML/JS game:

Fig 1: Preview of the output that you will get on running this code from your IDE.

Code

//var interval = setInterval(draw, 10);
let gameOver = false;
var canvas = document.getElementById("myCanvas");       //Variables for the canvas, ball, paddle, keys, and bricks
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
var downPressed = false;
var brickRowCount = 3;
var brickColumnCount = 5;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var bricks = [];
for (var c = 0; c < brickColumnCount; c++) {
    bricks[c] = [];
    for (var r = 0; r < brickRowCount; r++) {
        bricks[c][r] = { x: 0, y: 0, status: 1 };
    }
}

document.addEventListener("keydown", keyDownHandler, false);     //Listening for pressed keys
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
    if (e.code == "ArrowRight") {       //If key is pressed
        rightPressed = true;
    }
    if (e.code == 'ArrowLeft') {
        leftPressed = true;
    }
    else if (e.code == 'ArrowDown') {
        downPressed = true;
        console.log('down')
    }
}
function keyUpHandler(e) {
    if (e.code == "ArrowRight") {     //If key is up
        rightPressed = false;
    }
    if (e.code == 'ArrowLeft') {
        leftPressed = false;
    }
    else if (e.code == 'ArrowDown') {
        downPressed = false;
    }
}

function collisionDetection() {
    for (var c = 0; c < brickColumnCount; c++) {
        for (var r = 0; r < brickRowCount; r++) {
            var b = bricks[c][r];
            if (b.status == 1) {
                if (x > b.x && x < b.x + brickWidth && y > b.y && y < b.y + brickHeight) {
                    dy = -dy;
                    b.status = 0;
                    score++;
                    if (score == brickRowCount * brickColumnCount) {
                        gameOver = true;
                    }
                }
            }
        }
    }
}

function drawDeath() {
    ctx.font = "20px Courier New";
    ctx.textAlign = 'center';
    ctx.fillStyle = "#000000";
    ctx.fillText("HAHA YU LOOZD (pres doun arouw tu x-it)", canvas.width/2, canvas.height/2);
    if (downPressed == true)
    document.location.reload();
}

function drawScore() {
    ctx.font = "16px Courier New";
    ctx.fillStyle = "#0E17E8";
    ctx.fillText("Scores is: " + score, 8, 20);
}

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI * 2);   //Drawing the Ball
    ctx.fillStyle = "#32CD32";
    ctx.fill();
    ctx.closePath();
}

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);  //Drawing the Paddle
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}


function drawBricks() {
    let randomNumber;
    for (var c = 0; c < brickColumnCount; c++) {
        for (var r = 0; r < brickRowCount; r++) {
            if (bricks[c][r].status == 1) {
                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);
                if (randomNumber == 1)
                    ctx.fillStyle = "#0095DD";

                if (randomNumber == 2)
                    ctx.fillStyle = "#FF0000";

                if (randomNumber == 3)
                    ctx.fillStyle = "#FF8A00";

                if (randomNumber == 4)
                    ctx.fillStyle = "0100FF";

                ctx.fill()
                ctx.closePath();
            }
        }
    }
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);                 //Clears the screen after each motion
    drawBall();
    drawPaddle();
    drawBricks();
    drawScore();
    collisionDetection();

    //dx = dx + (Math.floor(Math.random() * 5 - 2));
    var cx = dx + (Math.floor(Math.random() * 5 - 2));

    if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {         //Bounces the ball
        dx = -dx;
    }

    if (y + dy < ballRadius) {
        dy = -dy;
    } else if (y + dy > canvas.height - ballRadius) {
        if (x > paddleX && x < paddleX + paddleWidth) {                 //Paddle Collision features
            dy = -dy;
            dx = cx;
        }
        else {
            gameOver = true;
            setInterval(drawDeath, 10) //Death Detecti 
        }
    }

    if (rightPressed && paddleX < canvas.width - paddleWidth) {             //Paddle Controls
        paddleX += 7;
    }
    else if (leftPressed && paddleX > 0) {
        paddleX -= 7;
    }

    x += dx;
    y += dy;

    if (!gameOver) requestAnimationFrame(draw)
    
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Bad Gramarrs</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        canvas {
            background: #eee;
            display: block;
            margin: 0 auto;
        }


        #main {
            display: none;
        }

        #newGame, #creditBtn, #backBtn {
            text-align: center;
            vertical-align: middle;
            border: 2px solid goldenrod;
            border-radius: 7px;
            background-color: gold;
            color: orangeRed;
            font-size: 32px;
            font-weight: bold;
            font-family: "Courier New";
            width: 5em;
            margin: 5px auto;
        }

        #theHead {
            text-align: center;
            margin: unset;
            color: orange;
            font-size: 2em;
            font-family: "Courier New";
        }

        #credits {
            text-align: center;
            margin: unset;
            color: orange;
            font-size: 2em;
            font-family: "Courier New";
            display: none;
            background-color: inherit;
        }

        #backBtn {
            display: none;
        }
    </style>
</head>
<body>
    <div id="theHead">Bad Gramarrs</div>
    <div id="newGame" onclick="runGame()" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'">Strt Gaem</div>
    <div id="creditBtn" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'" onclick="showCredits()">Credets</div>
    <div id="credits">Bad Gramarrs: Maed buy mi</div>
    <div id="backBtn" onmouseover="this.style.backgroundColor = 'goldenrod'" onmouseout="this.style.backgroundColor = 'gold'" onclick="goBack()">Back</div>
    <div id="main">
    <canvas id="myCanvas" width="480" height="320"></canvas>
    </div>
    <script src="atari.js"></script>
   
    <script>
        var runGame = function () {
            document.getElementById("newGame").style.display = "none";
            document.getElementById("theHead").style.display = "none";

            document.getElementById("credits").style.display = "none";
            document.getElementById("main").style.display = "block";
            document.getElementById("creditBtn").style.display = "none";
            randomNumber = Math.floor(Math.random() * 4 + 1);
            draw();
        };

        var showCredits = function () {
            document.getElementById("theHead").style.display = "none";
            document.getElementById("creditBtn").style.display = "none";
            document.getElementById("newGame").style.display = "none";
            document.getElementById("credits").style.display = "block";
            document.getElementById("backBtn").style.display = "block";
        };

        var goBack = function () {
            document.getElementById("backBtn").style.display = "none";
            document.getElementById("credits").style.display = "none";
            document.getElementById("theHead").style.display = "block";
            document.getElementById("newGame").style.display = "block";
            document.getElementById("creditBtn").style.display = "block";
        };
    </script>

</body>
</html>

Instructions

Follow the steps carefully to get the output easily.

  1. Install Visual Studio Code on your computer.
  2. Create a new html file.
  3. Copy the code snippet using 'copy' button and paste it in that HTML file.
  4. Then cut the first 179 lines of code and paste it inside the script tag.
  5. Save and run your html file directly from your file location.


I found this code snippet by searching for "how to create a game over a screen for basic HTML/JS", you can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Visual Studio Code 1.73.1.


Using this solution, we are able to create a game over a screen for basic HTML/JS with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to create a game over a screen for basic HTML/JS.

FAQ

1. What is a game over screen?

A game over screen is a user interface element displayed when the player loses the game or fails to achieve. It provides feedback to the player, such as their score or performance statistics. It shows options to restart the game or return to the main menu.


2. Why is a game over screen important?

A game over screen provides closure to the game session. It allows players to review their providing an opportunity to restart the game or try again. It enhances the overall user experience and adds polish to the game.


3. What elements should be included in a game over screen?

A game over screen may include elements such as:

  • Text displaying a game-over message.
  • Player's score or performance statistics.
  • Buttons or links to restart the game, return to the main menu, or share the game on social media.
  • Graphics, animations, or visual effects to enhance the presentation.


4. Can I customize the appearance and layout of the game over the screen?

Yes, it can customize the appearance and layout of the game over the screen using HTML, CSS, and graphics. The Experiment has different styles, fonts, colors, and visual elements to create it. It engages with a game over screen that aligns with your game's theme and aesthetic.


5. How do I handle user interaction on the game over screen?

JavaScript event listeners to handle user interactions on the game over screen. Its Such as clicking buttons to restart the game or return to the main menu. Install functions or callbacks to respond to these interactions and updates.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.