A Javascript Game

Let’s review now the Javascript code behind this small game.

First of all our little program define 4 elements:

One array called myarr

myarr={
    "it-flag.gif":"Italy",
    "tn_fi-flag.gif":"Finland",
    "tn_mx-flag.gif":"Mexico",
    "po-flag.gif":"Portugal",
    "ja-flag.gif":"Japan",
    "tn_us-flag.gif":"USA",
    "tn_ro-flag.gif":"Romania",
    "pl-flag.gif":"Poland",
    "tn_gm-flag.gif":"Germany"
};

This array contain all the flags that are loaded in the game.

We also define 3 elements more that will be accessible from any function of the program

randomNmber=0;
completedList=false;
var score=0;

Now the first function that we review is called startGame()

function startGame() {
    getNextEntry();
    document.getElementById("sourceimg").src=defineCandidate(randomNmber);

    if (completedList==true) {
        document.getElementById("sourceimg").src="win.gif";

    }
}

The first line of the function call the function getNextEntry. This is a function that define a random number. The function is below

function getNextEntry(){
    const val = Object.keys(myarr);
    max = val.length;

    if (max==0) {
        listTerminated()
        completedList=true;
    }

    else {
        randomNmber=Math.floor(Math.random()*max ) + 0;
    }

This function first get all the keys from the array myarr.

If we print to console the val object we will see that the array is a collection of all the flags loaded.

Array(9) [ “it-flag.gif”, “tn_fi-flag.gif”, “tn_mx-flag.gif”, “po-flag.gif”, “ja-flag.gif”, “tn_us-flag.gif”, “tn_ro-flag.gif”, “pl-flag.gif”, “tn_gm-flag.gif” ]

The variable max get the current lenght of the array

If the array is equal to zero than the user has won: in this case the program will call a listTerminated function that will print out the congratulation message for the player.

If the array is greater than zero then a random number is generated. The global variable (randomNmber) will be assigned a random number

Let’s go back to the function startGame.

In the html page we have a an image tag has the one below

Image Tag

Now we need to insert the randomly chosen flag in the image tag.

To do so we call the function defineCandidate(randomNmber) and we pass the random number as a parameter.

Let’s have a loo at the defineCandidate function.

//Return first Key of the Object
function defineCandidate(num){
    const keys= Object.keys(myarr);
    return keys[num];
}

If we console out the keys[num] the result will be :

Passing from number to file name.

As you can see anytime we press Start Game the function defineCandidate will receive a number as parameter and return the key (which in this case consist in the name file of the picture).

So far we have seen how to choose randomly a number from the Flag Array (myarr) and then pass the number to a function that will give us the name of the picture to insert in the img tag.

Let’s check now what happens when the user actual select the answer from the list of values and hit the confirm button.

As usual first the function and then the explanation

function okconf(){
    var userSelection=document.getElementById("Country")
    var countrySelected=userSelection.options[userSelection.selectedIndex].value;
    let flag_posted= myarr[defineCandidate(randomNmber)];

    if (flag_posted==countrySelected) {
        addscore();
    }

    else {
        removescore()
    }

    updateLOV(defineCandidateValues(randomNmber));
    removefromselection(flag_posted);
    startGame();
    
}

When the user hit the button “Confirm” the function okconf() is called.

First of all a variable userSelection is generated: this variable is populated with the drop down list of value. Let’s have a look at what happen when we press confirm and console out the userSelection variable.

userSelection variable returns the drop down menu

At this point we need to get the value actually displayed in the drop down (in the picture above we need to get Finland).

To do so:

countrySelected=userSelection.options[userSelection.selectedIndex].value;
We use the selectedIndex command from the drop down menu to get the value of the country chosen by the user.

At this point we know that the user has selected one country (for example Finland).

We need to check if the answer from the user is equal to the flag displayed.

We still have our randomNumber referring to the array. So all we need to do is get the value from the array dictionary

Once this is done we can check if the answer provided by the user is correct or not. If it is correct we will call addscore, otherwise removescore

The functions addscore and removescore are self-explanatory.

Let’s instead keep going with our function okconf.

After updating the score the function call the function updateLOV. This function receive as a parameter the name of the country displayed.

//Remove item from list of values in the webpage
function updateLOV(mycountry){
    mylist=document.getElementById("Country");
    console.log(mylist);
    for (i=0;i<mylist.length;i++) {
        if (mylist[i].value==mycountry) {
            mylist.remove(i);
        }
    }
}


The function above assign to mylist the selection list of values. So mylist is a type array with all the values

Then the function start a loop inside the array mylist and check if the value of the list is equal to the name of the country received as a parameter. If that is the case from mylist the value of the country is removed.

So far we have removed from the list of value the name of the country displayed. We need also remove the country selected from the global array

We do so with the function below

//delete the item from the object 
function removefromselection(flag_posted) {
    item_to_remove=defineCandidate(randomNmber);
    delete myarr[item_to_remove];
    //console.log(myarr);       
}

Leave a Reply

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