Create a Magic Square in Javascript

Free Web development courses with real-time projects Start Now!!

A magic square is a 2D square matrix of distinct positive integers from 1 to n^2. It has a constant sum in every row, column, diagonal, which is known as magic sum.

Algorithm to solve a n*n magic square:

It follows the following conditions:

1. Place 1 anywhere except the middle position.

2. The position of the next number is calculated by incrementing the column number of the previous number by 1 and decrementing the row number of previous number by 1.

3. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.

4. If the calculated position is preoccupation, calculated column position will be decremented by 2, and calculated row position will be incremented by 1.

5. If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2).C:\Users\welcome\Desktop\Games\JsGames\Magic Square\index.html

Project Prerequisites

To implement this project we need to know the following :

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

Download Magic Square Source Code

Please download the source code of magic square in javascript: Magic Square Code

Steps to Build Magic Square in JavaScript

1. Creating html file

HTML provides the basic structure. So it is the very first step of the project. Our code will contain some basic HTML tags like div, h1, title etc. And also we’ve used bootstrap buttons and classes to make our life simpler.

index.html 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>DataFlair Magic Square</title> 
    <style>
        .board{

            border:3px solid black;
            margin:0 auto;
            width: fit-content;
            padding: 10px;
            border-collapse:collapse;
        }
        td{
            width:10px;
            height: 10px;
            padding: 0px;
            border-collapse:collapse;
        }
        table,td{
            border: 2px solid black;
            border-collapse: collapse;
        }
        .lost{
            color: red;
        }
        .won{
            color: green;
        }
        .NoDeco{
            text-decoration: none;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class ="jumbotron">DataFlair Magic Square</h1>
        <h3 id= "score">Let's play!</h3> 
        <br><br>
        <div class="board">
            <h2>Enter values</h2>
            <table>
                <tr>
                    <td><input id="one" type="text" class="enter" ></td>
                    <td><input id="two" type="text" class="enter" ></td>
                    <td><input id="three" type="text" class="enter" ></td>
                </tr>
                <tr>
                    <td><input id="four" type="text" class="enter" ></td>
                    <td><input id="five" type="text" class="enter" ></td>
                    <td><input id="six" type="text" class="enter" ></td>
                </tr>
                <tr>
                    <td><input id="seven" type="text" class="enter" ></td>
                    <td><input id="eight" type="text" class="enter" ></td>
                    <td><input id="nine" type="text" class="enter" ></td>
                </tr>
            </table><br>
            <button class="btn btn-success" onclick="start()"> Submit</button><br><br>
            <p>Re-enter values and submit to play again</p>
        </div>  
        <br>   
        <p>Stuck here! Let's look at the solution </p>   
        <button class="btn btn-info"> <a class="NoDeco" href='./magicsq.html'>Solution</a> </button><br><br>
            
    </div> 
    

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

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

Here the most important tag is <input> which takes values from the user so that we can further process them in our JS file. And we have used a table tag to make a real three by three magic square.

2. Creating Solution Page-magicsq.html

Code:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" 0="">
    <title>DataFlair Magic Square</title>
</head>
<body>
    <div class="container">
        <h1 class ="jumbotron">DataFlair Magic Square</h1>
        <h3 id= "score">3X3 Magic Square-</h3> 
        <br><br>
        <div class="board">
            <table>
                <tr>
                    <td><input id="one" type="text"  ></td>
                    <td><input id="two" type="text"  ></td>
                    <td><input id="three" type="text"  ></td>
                </tr>
                <tr>
                    <td><input id="four" type="text"  ></td>
                    <td><input id="five" type="text"  ></td>
                    <td><input id="six" type="text"  ></td>
                </tr>
                <tr>
                    <td><input id="seven" type="text"  ></td>
                    <td><input id="eight" type="text"  ></td>
                    <td><input id="nine" type="text"  ></td>
                </tr>
            </table><br>
            <button class="btn btn-success" onclick="gen()"> Generate</button><br><br>
        </div>        
    </div> 
    <script >
    function gen(){

    let n=3;
    var vals = new Array();;

    for(var i=0;i<3;i++)
    {
        vals.splice(i,0,new Array());
        for(var j=0;j<3;j++)
        vals[i].splice(i,0,0);
    }

    i=Math.floor(Math.random() * 10)%3;
    j=(i+1)%3;

    let cnt=1;
    while(cnt<=9)
    {       
        if(i==-1 && j==n)
        {
            j=n-2;
            i=0;
        }else
        {
            if(i<0)
            i=n-1;

            if(j==n)
            j=0;
        }
        if(vals[i][j]!=0)
        {
            i++;
            j-=2;
            continue;
        }
        // console.log(i,j);
        // console.log(j);
        vals[i][j]=cnt++;
        // console.log(vals[i][j]);
        
        j++;
        i--;
    }
    document.getElementById('one').value=vals[0][0];
    document.getElementById('two').value=vals[0][1];
    document.getElementById('three').value=vals[0][2];
    document.getElementById('four').value=vals[1][0];
    document.getElementById('five').value=vals[1][1];
    document.getElementById('six').value=vals[1][2];
    document.getElementById('seven').value=vals[2][0];
    document.getElementById('eight').value=vals[2][1];
    document.getElementById('nine').value=vals[2][2];
 
}</script>
</body>
</html>

We are just implementing the magic square creation algorithm explained above and then we are displaying the calculated magic square by using getElementById and value.

3. Creating JavaScript file- script.js

Let’s understand with the help of code.

Code:

function start(){
    document.getElementById('score').innerHTML="";
    let n=3;

    let one = parseInt(document.getElementById('one').value)
    let two = parseInt(document.getElementById('two').value)
    let three = parseInt(document.getElementById('three').value)
    let four = parseInt(document.getElementById('four').value)
    let five = parseInt(document.getElementById('five').value)
    let six = parseInt(document.getElementById('six').value)
    let seven = parseInt(document.getElementById('seven').value)
    let eight = parseInt(document.getElementById('eight').value)
    let nine = parseInt(document.getElementById('nine').value)
 
    let vals = [[one,two,three],[four,five,six],[seven,eight,nine]];

    //checking row sum
    let sum=15; 
    let currsum=0;
    let flag=1;

    for(let i=0;i<3;i++){
        currsum =0;
        //checking row sum
        for(let j=0;j<n;j++){
            currsum+=vals[i][j];
        }
        if(currsum!=sum){
            flag=0;
            break;
        }

        currsum =0;
        //checking row sum
        if(flag)
        for(let j=0;j<n;j++){
            currsum+=vals[j][i];
        }
        if(currsum!=sum){
            flag=0;
            break;
        }
    }

    //checking diagonals
    if(flag){
        currsum=0;
        let dsum = vals[0][0] + vals[1][1] + vals[2][2]; 
        if(dsum!=sum)
            flag=0;

        if(flag)
        {
            dsum = vals[0][2] + vals[1][1] +vals[2][0];
            if(dsum!=sum)
            flag=0;
        }
    }

    var h1 = document.createElement('h1');
    h1.setAttribute('id','result')
    if(flag){
        console.log("won");
        h1.setAttribute("class",'won')
        var textNode= document.createTextNode("You Won!!!");
    }else{
            console.log("lost")
            var textNode= document.createTextNode("You Lost!!!");
            h1.setAttribute("class",'lost')
    }
    h1.appendChild(textNode)
    document.getElementById('score').appendChild(h1);

}

In this file, we have first created a 3*3 matrix that stores all the values entered by user, for which we have used simple DOM’s (Document Object Model) getElementById() and to convert this string type input to int type, we have used parseInt(). Now as we have all the elements of magic square, we can simply check each row, column, diagonal sum.

Magic sum of 3*3 magic square is given by n*(n^2+1)/2 i.e. 15 in our case.

We’ll check the sum of every row and if we get a row sum not equal to 15 in any case we won’t check further and thus use the variable flag. Similarly, we check for all columns and both diagonals. When all sums are equal to the magic sum, the flag will be 1 otherwise it will be zero.

And the last thing is the ‘game won’ message, the game is won when the flag is 1, therefore we create a new element h1 in h1.score and display the message. Also we have added corresponding classes(‘won’, ’lost’) that change the color of the text.

JavaScript Magic Square Output

javascript magic square output

javascript magic square output

Summary

We have successfully implemented magic square game using javascript in 2 easy steps. Now you can train your brain anytime with this.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

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