Math random

Math random

The Math.random function in JavaScript allows you to generate a pseudo-random decimal number between 0 inclusive and 1 excluded.

Let’s immediately make an example of using the following function.

JavaScript Math random – first example

So, try clicking on the button below ‘Generate random’.

It generates a random number between 0 and 100 and if you try to click on the button again clearly the number changes. So from time to time a new number is generated.

Implementation

To implement this example, let’s develop a function that calls:

  • the Math.random() function, that generates a floating point pseudo-random number between 0 and 1, with 1 not included.
  • the Math.round() functions that returns the value of a number approximated to the nearest integer.

So, to generate the random numbers from 0 to 100 we use:



    number = Math.round(Math.random () * 100);

With the Math.round() function we round to the integer.

We could also use the Math.floor() function in this way:



    number = Math.floor(Math.random () * 100);

But it generates numbers from 0 to 99 and therefore to have numbers from 0 to 100 we would have to write: Math.floor (Math.random ( ) * 101).

So here’s the JavaScript function:



function randomNumber() {
    number = Math.round(Math.random() * 100);
    document.getElementById("random").innerHTML ="Random number " + number ;
}

We then create a button-type input box for the button in html, to which we associate the onclick event that calls the random function ().

<input type="button" onclick="randomNumber()" value="Generate number random">
<div id="random"></div>

So for example if I want to generate the numbers from 1 to 6 I write: Math.round (Math.random () * 5) +1;

JavaScript Math random – second example

In this second example we ask the user how many random numbers he wants to generate, transcribing them into an input box. So we click on the button and generate them.

Write in the box below how many numbers you want to generate,

Algorithm procedure

We proceed by generating the Math.random function to generate the random numbers.

First we check that the number entered in the field how many numbers to generate is between 1 and 100 with an if. If it is, we proceed to generate the numbers, otherwise we give a warning message to the user to enter a value between 1 and 100.

We use the parseInt function to return an integer anyway.

So with a simple for loop I generate the numbers and print them separated by a comma.



function randomNumbers() {
  n = parseInt(document.getElementById("howMany").value);

  if (n > 0 && n <= 100) {
    str = "";
    for (i = 0; i < n; i++) {
         num = Math.round(Math.random()*100 + 1);
         if (i > 0) {
            str += ", ";
         }
         str += num;
     }
     document.getElementById("random").innerHTML ="Numbers generated: " + str;
     } else 
    document.getElementById("random").innerHTML ="Insert a number > 0 e < 100";
   }
}

Here is the html code:





Conclusion

These are just some simple examples of using the Math.random function in JavaScript, in the next lesson we will study other functions.

Some useful links

Indice argomenti tutorial JavaScript

JavaScript array includes

JavaScript array includes

JavaScript array includes method allows you to check if an element is present in an array or even in a text string, as explained in this lesson: https://www.codingcreativo.it/en/javascript-includes/.

The syntax of this method is as follows:

array.includes(element)

Where element is the element to search for in the array.

Optionally, you can also indicate the position from which to start the search by adding a second parameter as an argument to the includes method of js.

array.includes(element, start).

The includes method returns a boolean value:

  • true if the element is present in the array,
  • false if the element was not found.

JavaScript array includes – first example

Search an element in an array with the includes () method.

So let’s suppose we have the following array:



var schoolObject = ['eraser', 'notebook', 'pencil'];

Then, we apply the include method to get the boolean return value stored in a variable.



var result = schoolObject.includes('eraser');

In this case, if we try to make the result console.log we will have the boolean value true in return.

If, on the other hand, we are looking for a value that is not present:



var result = schoolObject.includes('Sharpener');

The value of the result variable will be false.

JavaScript array includes – second example

Create an array of integers of your choice. After generating a random number between 1 and 100. If the number is not present in the array we insert it, otherwise we return the message “number already present”.

So first let’s create an array of integers of your choice. Next we generate a random number using the Math.floor and Math.random functions.

After using a simple conditional statement with the logical operator not we check if the number is not present and in this way we insert it into our array. Otherwise we display the message with a simple alert.

So here is the example code that uses the includes method of js:



var arrayNumbers = [6,12,34,67,89,98,5,2,7,13];
var numberRandom = Math.floor(Math.random() * 100) + 1;

if (!arrayNumbers.includes(numberRandom)){
  arrayNumbers.push(numberRandom);
} else {
  alert('Number is present');
}

Conclusion

In this lesson we have simply seen examples of using the JavaScript array includes, in the next lessons I will propose many other examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript includes

JavaScript includes

The JavaScript includes method on String allows you to check if a text is contained in a string. This method can also be applied to arrays, as we’ll see later in the tutorial.

The syntax of this method is therefore the following: string.includes(value, start).

Where string represents the string where to search for the value. The value parameter can be a word, a number, or a phrase. It does not matter how many times the value is contained in the string, in any case the important thing is to find it at least once.

Instead, the start parameter represents the starting point for carrying out the search, since in some cases it is preferable not to start from the beginning. If the start parameter is not specified, the default value is 0.

The method returns a Boolean value, that is, true or false.

Examples JavaScript includes on String

Now let’s do some simple examples of using the includes() method with strings.

Given a sentence contained in a string variable, check if a word is contained in this sentence.

In the example below, therefore, let’s try to search for the word thought within an example sentence. We use the JavaScript includes method for this purpose.


var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript!';

var includeString = coding.includes('thinking');

console.log(includeString);

In the browser console we will display the value true, as the word thought is contained in our example string.

Clearly, even more words can be searched, as long as they are contained in the exact order.

So even in the example below, the result is true.


var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript!';

var includeString = coding.includes('logical thinking');

console.log(includeString);

When the sequence is not correct, or not all the words are contained in the sentence then the result is false.

So here’s an example where the return value is false.


var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript!';

var includeString = coding.includes('the logical thinking');

console.log(includeString);

In this lesson we have done some examples of using JavaScript includes with string. This method can also be used with arrays and the lesson can be found at the following link: inlcudes with arrays.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

15 puzzle game

15 puzzle game

In this tutorial we will learn how to create the 15 puzzle game with JavaScript.

Click on the play button and start moving the numbers, simply by passing over them, until everything is reordered. When you are done, the victory message will appear.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Implementation of the 15 puzzle game with JavaScript

We will make this game very simply by using stylesheets and JavaScript methods to handle events.

Clearly there are many implementations of this online game with JavaScript, I propose one of them.

We will use the addEventListener method that we will activate at the mouseover event, that is, when we hover the mouse over the piece to be moved.

HTML code

The HTML code for the development of the game will simply be constituted by a container for all the tiles to which we give the tile class and by every single tile that is initially in its place.

Finally I add the play button which is used to start the game.


  

Style sheet for the 15 puzzle game JavaScript

We build our style sheet by building our tiles wide and 60 pixels high. We give a 10-pixel border of light gray color to better simulate the game. The last piece will be 79 pixels in height and width.


.tiles{
  width: 320px;
  height: 315px;
  display: flex;
  flex-wrap: wrap;
}
.tiles .gusset{
  border: 10px solid #ddd;
  width: 60px;
  height: 60px;
  color: #ffffff;
  background: #5cb1d6;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
}
.tiles .last{
  width: 79px;
  height: 79px;
}

JavaScript code

Let’s build a play function that simply creates random numbers with no repetitions. Swapping the initial elements with those generated using the swap function. Notice that swap is triggered on the style property of the div level.

After we activate the displacement of the box only if the distance dx and dy ta the last piece and the piece under consideration is 0 and 1 or 1 and 0.

Finally, if each element of the array is in its place then we have solved our game.



var last = document.querySelector(".last");
var ar = Array.from(document.querySelectorAll(".gusset"));

ar.forEach(gusset => {
    gusset.addEventListener("mouseover", ev => move(gusset));
});

function game(){
    var i = 0;
    var a, b;
    while (i < 30) {
        a = Math.random() * 15 >>> 0;
        b = Math.random() * 15 >>> 0;
        swapGusset(ar[a], ar[b]);
        i++;
    }
}

function swapGusset({style: a}, {style: b}) {
	temp = a.order;
	a.order = b.order;
	b.order = temp;
}

function swapX({style}) {
    return parseInt(style.order)%4;
}

function swapY({style}) {
    return parseInt(style.order)/4 >>> 0;
} 
      
function move(gusset) {
    var ux = swapX(last);
    var x = swapX(gusset);
    var uy = swapY(last);
    var y = swapY(gusset);
    var dx = Math.abs(ux-x),  dy = Math.abs(uy-y);

    if (dx == 0 && dy == 1 || dx == 1 && dy == 0) {
        swapGusset(last, gusset);
        if (ar.every((p, i) => i == swapX(p) + swapY(p) * 4)) {
           alert("You Won!");
        }
    }
}

In this lesson we have found a possible solution to the 15 puzzle game in JavaScript, in the next lessons we will have fun developing many other applications.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript Slot Machine

JavaScript Slot Machine

In this tutorial I propose a simple version of the JavaScript Slot Machine.

The game consists of clicking on a button and trying to win, bringing out 3 identical symbols, in our example they are smileys.

Only if all 3 symbols are the same is there a victory situation, otherwise you lose.

So here’s a demo of the JavaScript Slot Machine:

Slot Machine Game

Your result will be visible here!

JavaScript Slot Machine – development

Let’s now explain the procedure of the game, starting from the programming logic and then from the JavaScript.

First we populate an array with symbols. In our case we call the array array Symbols and insert 6 symbols that I took from this link: https://html-css-js.com/html/character-codes/.

let arraySimboli = [
  '😣',
  '😁',
  '😴',
  '🤩',
  '🙄',
  '🤗'
];

We continue the realization of the slot machine game in JavaScript by generating 3 static starting positions of the game. So let’s make sure to display 3 smileys in 3 different divs of our page.

As shown in the example below:

//Starting situation
document.getElementById('slot1').innerHTML = arraySimboli[0];
document.getElementById('slot2').innerHTML = arraySimboli[2];
document.getElementById('slot3').innerHTML = arraySimboli[1];

Now let’s generate an event on the click of a button and assign the play function.

The play function is the heart of the JavaScript slot machine program. First of all, we deactivate the play button so as not to allow the user to click several times.

Then we also establish the number of random attempts to be made before showing the 3 faces and we do it through a function created specifically for numbers (min, max).

Then, for each slot, we generate random symbols until the number of attempts is reached using the setInterval function, useful for marking the time between one display and another.

When the retry count is reached, the slots are cleared using the clearInterval function.

Finally, when the last slot has loaded, the win function is called up.

This function simply sees if the contents of the 3 slots are the same. If it is true, the ‘you won’ message is displayed in a portion of the html code, otherwise the ‘you lost’ message is displayed.

So here is all the complete code of the game on the slot machine in JavaScript:


document.getElementById("button-slot").addEventListener("click", game);

function game(){
 document.getElementById("button-slot").disabled = true;

  const attempts = numberAttempts(3,12);

  let t1 = 0, t2 = 0, t3 = 0;

  let slot1 = setInterval(function(){
    numberRandom = generaRandom(arraySimbols.length);
    document.getElementById("slot1").innerHTML = arraySimbols[numberRandom ];
    console.log(arraySimbols[numberRandom ]);
    t1++;
    if (t1 == attempts) {
      clearInterval(slot1);
      return null;
    }
  }, 100);

  let slot2 = setInterval(function(){
    t2++;
    if (t2 == attempts) {
      clearInterval(slot2);
      return null;
    }
    numberRandom = generaRandom(arraySimbols.length);
    document.getElementById("slot2").innerHTML = arraySimbols[numberRandom ];
    console.log(arraySimbols[numberRandom ]);
  }, 100);

  let slot3 = setInterval(function(){
    t3++;
    if (t3 == attempts) {
      clearInterval(slot3);
      victory();
      document.getElementById("button-slot").disabled = false;
      return null;
    }
    numberRandom = generaRandom(arraySimbols.length);
    document.getElementById("slot3").innerHTML = arraySimbols[numberRandom ];
    console.log(arraySimbols[numberRandom ]);
  }, 100);

  function victory() {
    slot1 = document.getElementById("slot1").innerHTML;
    slot2 = document.getElementById("slot2").innerHTML;
    slot3 = document.getElementById("slot3").innerHTML;

    if (slot1 == slot2 && slot2 == slot3){
      document.getElementById("result").innerHTML = 'YOU WON';
    } else {
      document.getElementById("result").innerHTML = 'YOU LOST';
    }
  }
}


function generaRandom(max){
	return Math.floor((Math.random() *  max));
}

function numberAttempts(min, max){
	return Math.floor((Math.random() * (max-min + 1)) + min);
}

Here is the html code needed to view the game:



Finally, here is the style given to the html page that you can customize as you wish:


#slot-machine{
	border-radius: 5px;
	background-color: #3889c4;
	margin-top: 30px;
	padding: 20px;
	width: 500px;
	margin: auto;
	text-align: center;
}
h2#title{
	color: white;
	font-size: 26px;
	text-align: center;
	padding:10px;
}

section.slots{
	display: flex;
	justify-content: space-around;
	border-radius: 15px;
	background-color: #FAFAFA;
	padding: 20px;
}

#button-slot{
	color: white;
	font-size: 26px;
	text-align: center;
	margin-top: 25px;
	padding: 20px;
	background-color: #ffc83d;
	border: 1px solid #3889c4;
	border-radius: 10px;
	cursor: pointer;
}
.icons{
	font-size: 50px;
	text-align: center;
	margin:10px;
}

#button-slot:hover{
	background-color: #16486c;
}

div#result{
	width: 300px;
	margin: 10px auto;
	border: 1px solid #87c6f4;
	border-radius: 15px;
	background-color: #87c6f4;
	padding: 10px;
}

Conclusion

In this lesson we have developed a simplified version of the JavaScript slot machine game. Try creating your own version.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

For in JavaScript

For in JavaScript

The for in loop is used to list all properties of a given object in JavaScript.

It can be used on objects but also on arrays. Using this loop it is not necessary to specify the length of the array as we did using the for loop instead.

Warning: do not use the for in loop on arrays when the order of the index is important, in this case it is necessary to prefer the simple for loop. Thus, we can say that the for in loop is more used with objects in JavaScript.

The syntax is as follows:

for (var in object)
  instructions

Where in is a keyword used to test whether the specified variable is present in the object. So the expression (var in object) returns a Boolean value. As long as this value is true the cycle will be executed.

Let’s take some examples to better understand how it works.

Example 1 – for in loop JavaScript

In this first example we are building a simple user object with 3 properties.


user = {
  name: 'Coding',
  lastname: 'Creativo',
  phone: '333'
}

for (var k in user){
  console.log(k);
}

In our example k will take the value of all the properties present in our object. So in the console.log you will see: name, surname and telephone.

Instead of k we can indicate any variable name. The name is purely indicative. Also pay attention to the fact that var.

The for in loop in JavaScript is therefore executed until it finds properties within the object.

If we want to display the property values ​​as well, then we need to indicate each element.

In this case we use the notation with square brackets, this is because if I wrote user.k, k is not recognized as a property of the user object, so it would give an error. So the only way to access the key value in an object is the notation with square brackets.


user = {
  name: 'Coding',
  lastname: 'Creativo',
  phone: '333'
}

for (var k in user){
  console.log(k + 'value ' + user[k]);
}

In the console in this way I will see: name value Coding, last name value Creative and telephone value 333.

If we find ourselves using nested objects, we can nest the for loop inside another, as shown in the example below:


user = {
  name: 'Coding',
  lastname: 'Creativo',
  phone: '333',
  address: {
    street: 'dei tulipani',
    city: 'Modica'
  }
}

for (var k in user){
  if (k == 'address'){
    for (var j in user.address){
      console.log(j + ': ' + user.address[j]);
    }
  } else {
      console.log(k + ': ' + user[k]);
  }
}

So to view the elements within the address property, which represents an object, I use another for loop.

We note that we can also write in this way:


for (var k in user){
  if (k == 'address'){
    for (var j in user[k]){
      console.log(j + ': ' + user[k][j]);
    }
  } else {
      console.log(k + ': ' + user[k]);
  }
}

In this lesson we have introduced this new iterative cycle, the for in loop in JavaScript, in the next lessons I will propose other examples.

Alcuni link utili

Indice tutorial JavaScript