JavaScript Project – Tower Blocks Game

FREE Online Courses: Click, Learn, Succeed, Start Now!

Learn how to create JavaScript Tower blocks game. In this article, we’ll see how to develop a simple Tower blocks game. So first let’s see how this game works.

About Tower Blocks Game

Tower blocks game is a fun game for kids of all ages. In this game, our target is to construct the highest tower by arranging blocks one over the other such that we never disobey Newton’s law by this line we mean no block can hang in the air. It has to be over some other block or over the ground.

Project Prerequisites

To implement this project we need to know the following :

1. Basic concepts of JavaScript
2. HTML
3. CSS

Download Tower Blogs Game Code

Please download the source code of javascript tower blocks game – Tower Blogs Game Code

Steps to Build the Project – Tower Blocks Game

1. Creating html file

We have used simple HTML tags and for styling we have used basic CSS and some bootstrap classes.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" 0="">
    <title>ProjectGurukul Tower Blocks</title>
    <link rel="stylesheet" href="static/style.css">
</head>
<body>
    <div class="container">
        <h1 class ="jumbotron"> ProjectGurukul Tower blocks</h1>
        <h3 id= "score">Let's play. </h3> 
        <button onclick="start()" class="btn btn-sm btn-success" >Start game</button><br>
        <div id="score"></div>
        <br><div id="board" class="hideNow">
        </div>
        <br>
        <br><br>
       
    </div>

    <script src="static/script.js"></script>
</body>
</html>

2. Creating CSS file – style.css

Code:

#board{
    width: 400px;
    height: 510px;
    border: 4px solid #333;
    margin: auto;
    position: relative;
}

.blocks{
    position: absolute;
    width:145px;
    height:50px;
    animation-fill-mode: forwards;
    border-radius: 5px;
}

.hideNow{
    visibility: hidden;
}

It is a good programming practice to create separate folders for different files therefore, our CSS and JS files will be in a static folder, so make sure you create one static folder in your project folder.

Here we have added animation-fill-mode which ensures once the animation ends implicitly or explicitly, the block remains in its final position and doesn’t come back to the initial position. Apart from that, we have added visibility: hidden to our board so that it shows only when start is clicked.

3. Creating JavaScript file – script.js

Code:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function start(){
    await sleep(300)
    maindiv= document.getElementById('board')
    document.getElementById('score').innerHTML="Let's play"
    document.getElementById('score').style.color ="black"
    colors = ['lightcoral','greenyellow','lightskyblue','palegreen','coral','lightgreen']
    let gameStatus =1;
    let flag=1;
    let top=450;
    let score=0;
    maindiv.classList.remove('hideNow');
    function deleteChild() { 
        var maindiv= document.getElementById('board')
        
        var child = maindiv.lastElementChild; 
        while (child) { 
            maindiv.removeChild(child); 
            child = maindiv.lastElementChild; 
        } 
    }
    deleteChild();
    let prevleft,prevright;

    for(let i=1;i<=10 && gameStatus;i++)
    {
        if(flag)
        await sleep(2000)
        else
        await sleep(500)
        
        let left=0;
        block = document.createElement('div')
        block.setAttribute('class','blocks')

        c = colors[Math.floor(Math.random()*6)]
        block.setAttribute('style','background-color:'+c+';')

        var id = setInterval(frame,2);
        block.style.top = top + "px"; 
        top-=50;

        function frame() {
            if(left>250)
            {
                document.getElementById('score').innerHTML= "GAME OVER score="+score
                document.getElementById('score').style.color ="red";
                maindiv.classList.add('hideNow');
                gameStatus =0;
                i=11;
                clearInterval(id);
            }
            else {
              left++; 
              block.style.left = left + "px"; 
            }
            if(gameStatus==0)
                return;
            block.addEventListener('click',function(){
                if(i!=0 && left+145 <= prevleft || left >= prevright)
                {
                    document.getElementById('score').innerHTML= "GAME OVER score="+score
                    document.getElementById('score').style.color ="red";
                    maindiv.classList.add('hideNow');
                    clearInterval(id);
                    gameStatus =0;
                }
                else
                {
                    flag=1;
                    clearInterval(id);
                }
                prevleft=left;
                prevright=145+left;
            })
        }
        if(gameStatus==0)
            break;
        maindiv.append(block)
        
        score++;
    }
    if(gameStatus!=0)
    {
        document.getElementById('score').innerHTML= "GAME WON score="+score
        document.getElementById('score').style.color ="green";
    }
    
}

The asynchronous function helps to run tasks in parallel without freezing the website. Therefore in this file we have created a sleep function that takes milliseconds as a parameter and returns a promise object which represents the completion or failure of an asynchronous operation, and its resulting value.

The await statement waits for a promise to resolve or reject. You can use it only inside the async function. Thus, we have declared start as async. Let’s discuss some important functionalities:

1. deleteChild(): This method deletes all the childNodes of the maindiv element so that when we rerun the game without refresh it works.

2. colors: This array stores names of six different colors from which we randomly choose a color for current block using Math.floor and Math.random functions.

3. Now, we run a for loop, majors tasks done here are:

a) A new block is created using DOM.

b) Background color is added to the block.

c) Animation is added using setIntervel, here in the frame function we are incrementing the left position of block which gives a moving effect to the block and we are also checking overflow condition i.e. left>250 and we are terminating the game in this case by using clearInterval.

Then we have added an eventListener ‘click’ to the block so that it stops moving when user clicks over the block and also we are checking here if the box is on top of previous block/ground or in air and if it is completely in the air (left+145 <= prevleft || left >= prevright) then also we are terminating the game else we are setting values of prevright, prevleft here.

d) Now, we are incrementing the score and appending block in maindiv.

e) Finally, Win/Lose message is shown by a div created in index.html.

JavaScript Tower Blocks Game Output

tower block game output

Summary

We have successfully developed Tower blocks game in JavaScript in 3 easy steps. This is an interesting game which can easily be developed in javascript. Now you can play this any time.

Leave a Reply

Your email address will not be published. Required fields are marked *