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

Python Fibonacci

Python Fibonacci

In this lesson we will analyze some algorithmsin Python to check if a number belongs to the Fibonacci sequence.

In the previous lesson we studied how to print a Fibonacci sequence of variable length, each time decided by the user.

We have both an iterative and a recursive solution, using functions as well.

In this lesson instead ask the user to enter an integer and the program in Python will be able to tell if it is a Fibonacci number or not.

We will develop different solutions and analyze them.

Python Fibonacci – check if a number is Fibonacci

We study a first approach to a possible solution to the proposed problem.

The first thing that comes to mind, without knowing any rules, is to generate the Fibonacci numbers up to the input entered by the user and check if this number is contained in it.

We develop the solution using an iterative solution that will stop when the condition is satisfied, in our case when the entered number is found or numbers not greater than it are generated.

We create a sentinel variable, which we will call found for example, and set it to False. After that, this variable will change its value, becoming True only if the value is included in the sequence.

Here is a possible solution:


def check_fib(num):
    found = False
    a = 1
    b = 1
    c = a + b
    print(a,  end=' ')
    print(b,  end=' ')
    while(c <= num):
        print(c, end=' ')
        a = b
        b = c
        c = a + b        
        if(c == num):
            found = True
    if(found):
        print('Found')
    else:
        print('Not Found')
        
n = int(input('Insert a number: ' ))
check_fib(n)

Python Fibonacci - check if a number is Fibonacci - second solution

In this second solution we apply the well-known mathematical rules instead.

In particular, it is said that N is a Fibonacci number if and only if 5 N ^ 2 + 4 or 5 N ^ 2 - 4 is a square number.

We therefore develop an algorithm that satisfies these conditions by importing the math module in order to be able to use the square root (sqrt) function. If the square root is an integer then it means that it is a square number and therefore belongs to the sequence, otherwise it does not belong to it.


def check_fib(n):
    import math
    a = (5 * (n**2)) + 4
    b = (5 * (n**2)) - 4
    return (math.sqrt(a)).is_integer() or (math.sqrt(b)).is_integer()

n = int(input('Insert a number: ' ))
result = check_fib(n)
if (result):
    print('The number is Fibonacci')
else:
    print('The number is not Fibonacci')

Conclusion

In this lesson we learned how to check, in Python, if a number belongs to the Fibonacci sequence or not. In the next few lessons we will talk about lists in Python.

Some useful links

Python lambda function

Use Python dictionaries

Python readline()

Python max()

Break Python

Insertion Sort

Merge Sort

Numero di Fibonacci

Numero di Fibonacci

In questa lezione analizzeremo alcuni algoritmi per verificare se un numero appartiene alla successione di Fibonacci.

Nella lezione precedente abbiamo studiato come stampare una successione di Fibonacci di lunghezza variabile, di volta in volta decisa dall’utente.

Abbiamo sviluppato sia una soluzione iterativa sia ricorsiva, utilizzando anche le funzioni.

In questa lezione invece chiediamo ad utente di inserire un intero ed il programma sarà in grado di dire se è un numero di Fibonacci oppure no.

Svilupperemo delle soluzioni differenti e le analizzeremo.

Numero di Fibonacci – prima soluzione

Studiamo un primo approccio ad una possibile soluzione al problema proposto.

La prima cosa che ci viene in mente, senza conoscere nessuna regola, è quella di generare i numeri di Fibonacci fino all’input inserito dall’utente e verificare se questo numero è contenuto in esso.

Sviluppiamo la soluzione facendo uso di una soluzione iterativa che si fermerà quando la condizione sarà soddisfatta, nel nostro caso quando si trova il numero inserito oppure si generano dei numeri non superiori ad esso.

Creiamo una variabile sentinella, che chiameremo ad esempio trovato e la impostiamo a False. Dopo, questa variabile cambierà il suo valore, diventando True solo se il valore è compreso nella successione.

Ecco dunque una possibile soluzione:

def check_fib(num):
    trovato = False

    a = 1
    b = 1
    c = a + b
    print(a,  end=' ')
    print(b,  end=' ')

    while(c &lt;= num):
        print(c, end=' ')
        a = b
        b = c
        c = a + b        
        if(c == num):
            trovato = True

    if(trovato):
        print('trovato')
    else:
        print('non trovato')
        

n = int(input('Inserisci un numero: ' ))
check_fib(n)

Numero di Fibonacci – seconda soluzione

In questa seconda soluzione applichiamo invece delle note regole matematiche.

In particolare si dice che N è un numero di Fibonacci se e solo se 5 N^2 + 4 oppure 5 N^2 – 4 è un numero quadrato.

Sviluppiamo dunque un algoritmo che soddisfi queste condizioni importando il modulo math al fine di poter utilizzare la funzione radice quadrata (sqrt). Se la radice quadrata è un intero allora vuole dire che è un numero quadrato e dunque appartiene alla successione, altrimenti non vi appartiene.

def check_fib(n):
    import math
    a = (5 * (n**2)) + 4
    b = (5 * (n**2)) - 4
    return (math.sqrt(a)).is_integer() or (math.sqrt(b)).is_integer()

n = int(input('Inserisci un numero: ' ))
result = check_fib(n)
if (result):
    print('il numero è di Fibonacci')
else:
    print('il numero non è di Fibonacci')

Migliora le tue capacità di programmazione Python seguendo i nostri corsi in diretta!

corsi Python

Conclusione

In questa lezione abbiamo appreso come verificare se un numero appartiene o no alla sequenza di Fibonacci. Nelle prossime lezioni parleremo di liste in Python.

Alcuni link utili

Corso in diretta su Python

Indice tutorial sul linguaggio Python

1 – Introduzione al linguaggio Python

2 – Le variabili

3 – Operatori aritmetici e di assegnazione

4 – Stringhe in python

5 – Casting in python

6 – Input e print in python

7 – Primi esercizi in python

8 – Errori in Python

9 – Script Python

10 – Scambio di variabili in python

11 – Modulo math

Fibonacci sequence in Python

Fibonacci sequence in Python

Fibonacci sequence in Python can have different implementation algorithms.

Recall that the Fibonacci sequence is a sequence of positive integers in which each number starting from the third is the sum of the previous two except the first two which are 1, 1.

For example, if N = 9, the terms of the sequence are: 1, 1, 2, 3, 5, 8, 13, 21, 34.

Fibonacci sequence in Python algorithm

So let’s create an algorithm that represents the Fibonacci sequence.

Take a number N as input and display the N terms of the Fibonacci sequence.

To implement this algorithm, first of all we take two variables a and b and assign the value 1 to both. We thus create the first two terms of the Fibonacci sequence that we will immediately print.

Then, we make a for loop to display the N terms with an index i ranging from 0 to N-1. After, within the cycle we calculate the third term c and then exchange a with b and b with c. Finally we print c.

Here is a possible solution:


n = int(input('How many numbers?: ' ))
a,b = 1,1
print(a)
print(b)

for i in range(n):
    c = a+b
    a = b
    b = c
    print(c, end=' ')

Once we understand the procedure, we rewrite the algorithm in a more elegant way, avoiding some instructions, such as the initial prints, and we carry out the exchange in a single line.

Here is the solution:


n = int(input('How many numbers?: ' ))
    
a,b = 1,1

for i in range(n):
    print(a, end=' ')
    a,b = b,a+b
    print()

Fibonacci sequence in Python algorithm – with a function

We can also use a function to solve the algorithm.


def print_fibonacci(length):

    a = 1
    b = 1

    for i in range (length):
        print(a, end=" ")
        a,b=b,a+b

n = int(input('How many numbers?: ' ))
print_fibonacci(n)

We can also add a control input. If a user insert a negative number the program can be request a new number.


def print_fibonacci(length):

    a = 1
    b = 1

    for i in range (length):
        print(a, end=" ")
        a,b=b,a+b

n = int(input('How many numbers?: ' ))
while(n < 0):
    n = int(input('How many numbers? Insert a positive number: ' ))
print_fibonacci(n)

Fibonacci sequence in Python algorithm – recursive solution

Here is the recursive solution to the algorithm. Remember that recursion is when you have a call directly to the function itself. In our case, in fact, we call the function rec_fib within the same function rec_fib.


def rec_fib(n):
    if n > 1:
        return rec_fib(n-1) + rec_fib(n-2)
    return n

n = int(input('How many numbers?: ' ))

for i in range(1,n+1):
    print(rec_fib(i))

Conclusion

In this lesson we studied how to develop a Fibonacci sequence algorithm in Python, in the next lesson we will see how to understand if a number is part of the sequence.

Some useful links

Python lambda function

Use Python dictionaries

Python readline()

Python max()

Break Python

Insertion Sort

Merge Sort

How to generate random numbers in Python

How to generate random numbers in Python

How to generate random numbers in Python?

Random numbers are used for many purposes, let’s take some examples to better understand how are work.

First example about how to generate random numbers in Python

Write a program that generates n random numbers in an interval set by the user and displays them in output.

So, first of all, let’s import the random module.

Then we ask you to enter the interval values ​​that we store in two variables, for example named x and y.

We also ask you to enter the amount of random numbers to be generated.


import random

x = int(input('Insert the first number : '))
y = int(input('Insert the first number : '))

n = int(input('How many numbers? : '))

Now we can generate the random numbers with the for loop, using randint in the interval (x, y).


import random

x = int(input('Insert the first number : '))
y = int(input('Insert the first number : '))

n = int(input('How many numbers? : '))

for i in range(n):
  random_number = random.randint(x,y)
  print(random_number,end=' ')

But be careful if the user enters the value of y smaller than x?

The program returns an error at the randint point (x, y) because the value of x must be less than the value of y.

Therefore, we can check the data entered by requesting the user to re-enter the data. Or you can also swap the two variables.

By exchanging the variables we therefore have:


import random

x = int(input('Insert the first number : '))
y = int(input('Insert the first number : '))

if x > y:
    x,y = y,x

n = int(input('How many numbers? : '))

for i in range(n):
  random_number = random.randint(x,y)
  print(random_number,end=' ')

With an input check we could instead write like this:


import random

x = int(input('Insert the first number : '))
y = int(input('Insert the second number : '))

while x > y:
    print('The first number must be smaller than second!')
    x = int(input('Insert the first number : '))
    y = int(input('Insert the second number : '))

n = int(input('How many numbers? : '))

for i in range(n):
  random_number = random.randint(x,y)
  print(random_number,end=' ')

Second example about how to generate random numbers in Python

Generate 100 random numbers from 1 to 200 in steps of 2, sum them and make the average.

In steps of 2 from 1 to 200-1, it means that only odd numbers from 1 to 199 are generated.

So let’s use the randrange function for this purpose which, unlike randint, also allows us to indicate the step.

Here, then, is the complete code of the algorithm on random numbers in Python:


import random

n = 100
sum = 0

for i in range(n):
  random_number = random.randrange(1,200,2)
  print(random_number,end=' ')
  sum += random_number

average= sum / n

print('Average: ', average)

Clearly the calculation of the average is carried out as we have done many times with non-random numbers.

Conclusion

In this lesson we have developed some simple exercises on how to generate random numbers in Python, in the next lessons we will continue to practice again.

Useful links

Python tutorial

Introduzione al linguaggio Python

Create Python matrix

Python lambda function

Python test Lambda Function