2 declare your variables


#1


i dont quite understand how the math. random thing works especially the second part.
can someone please kindly explain


Replace this line with your code. 

var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random()* 5 + 1);
totalDamage = 0;


#2

From MDN:

math.random()

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive).

math.floor()

Math.floor( 45.95); //  45
Math.floor( 45.05); //  45

This should show you what we do in the second random

var random = Math.random();
var randomTimesFive = random * 5;
var randomTimesFivePlusOne = randomTimesFive +1;
var randomTimesFivePlusOneFloor = Math.floor(randomTimesFivePlusOne);

console.log(random);
console.log(randomTimesFive);
console.log(randomTimesFivePlusOne);
console.log(randomTimesFivePlusOneFloor);

#3

ok. thanks for replying. i get everything you just explained but am still slightly confused.

in this code, we have

var youHit = Math.floor(Math.random() * 2);

why times the random number by 2. for what purpose?
and here too,
var damageThisRound = Math.floor(Math.random()* 5 + 1);
*5 + 1? are all this numbers constant or i can use any number i like. and what is the purpose of mutiplying by 5 and adding 1.


#4

var youHit

We want to decide if we have landed a hit.
How we can do that?

var youHit = Math.floor(Math.random() * 2);

if (youHit)
  { 
  // youHit must be true (1) 
  }

Let's take a closer look:

Math.random() gives us a number between 0 - 1 (inclusive 0, exclusive 1)
That means Math.random() alone will not help us. There can never be a true( 1 )

var result = Math.random(); // 0 - 0.9999~

Now multiply by 2

var resultTimesTow = result * 2;
// If result is under 0.50 we will get now a value smaller 1 
// If result is greater 0.50 we will get a value greater 1

And now Math.floor()

var youHit = Math.floor(resultTimesTwo);
// The Math.floor() function returns the largest integer less than or equal to a given number
// resultTimesTwo is greater 1 we get 1 (true)
// resultTimesTwo is smaller 1 we get 0 (false)

#5

ok now i get it thanks


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.