Friday, August 16, 2013

Javascript Game pt. 2 - Rolling the Dice

 Since this game revolves around rolling dice, that is the first thing that I needed to do. Rolling a die is in essence, a random number generation function. So I ended up with the following function:


function rolldice ()

{die1=Math.floor(Math.random ()*6+1);

dieroll1.innerHTML="<p>"+die1"<p>";

die2=Math.floor(Math.random ()*6+1);

dieroll2.innerHTML="<p>"+die2+"<p>";

die3=Math.floor(Math.random ()*6+1);

dieroll3.innerHTML="<p>"+die3+"<p>";}


Math.floor () is the Javascript round down command. Therefore Math.floor (12.6) would result in 12. Nested inside the round down command I placed the actual random generator. Math.random by itself will generate a random decimal greater than zero, but less than one, and up to 10 digits long. Therefore to turn this random generation into a method that resulted in an integer between one and six, I had to multiply the result by six, add one, and round it down – as shown above. In totality the rolldice () function showed above will obtain a random die result for three dice, and then show them in the HTML of the page.

No comments:

Post a Comment