vendredi 15 avril 2016

Adding a numerical value to a DOM created element

I have a university assignment where I am supposed to code a dice roller. All of the HTML structure for the dice roller is supposed to be created by the DOM, except for the button to start the actual roller.

You can add and subtract dice from the roller. When you press the button to add a dice a d6 is created with a random number of dots ( 1 through 6). You can add up to 40 dice to the roller.

The code for adding a random die looks like this: (If this is the wrong method please tell me :) )

var addLi = document.createElement("li"); // this creates the button to add a die.
addLi.className = "add";
addLi.addEventListener("click", addRandomDice) // this fires of the function to create a random die.

toolbarUl.appendChild(addLi); 

function get_random()
{
    var ranNum= Math.floor(Math.random()*6);
    return ranNum;
}

function addRandomDice(){
var whichDice=get_random();

    var dice=new Array(5)
    dice[0]=diceSideOne;
    dice[1]=diceSideTwo;
    dice[2]=diceSideThree;   
    dice[3]=diceSideFour;
    dice[4]=diceSideFive;
    dice[5]=diceSideSix;

    contentUl.appendChild(dice[whichDice].cloneNode(true)); // creates a random d6 dice.

};  

The code for a die with one dot like this:

// dice-side-one li
var diceSideOne = document.createElement("li");
diceSideOne.className = "dice dice-side-one";

The code for a die with 2 dots looks like this:

// dice-side-two li
var diceSideTwo = document.createElement("li");
diceSideTwo.className = "dice dice-side-two";

And et cetera...

The value of all the dice is supposed to be added together and shown to the user.

My question is: How can I add a numerical value to each dice which represents it's amount of dots. So that I can add them all together to show the user the summ of all the dice.

In other words. If I have 5 d6 dice, with the faces 2, 3, 5, 4, 5. How can I show the user the sum of the dice faces rolled, which in this case would be 19 to the user.




Aucun commentaire:

Enregistrer un commentaire