DiceLab

HTML

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dice Lab</title>
    <link rel="stylesheet" href="dice_copy.css">
  </head>

  <body>
    <h1>Dicey Business</h1>
    <div class="container">
      <div>
        <button id="btn">Roll 1 Die</button>
        <button id="all">Roll All Dice</button>
        <button id="sum">Add All Dice</button>
      </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="dice_copy.js></script>
</body>

</html>

CSS

.div {
  border: 1rem solid black;
  height: 20rem;
  width: 20%;
  float: left;
  display: flex;
  align-items: center;
  justify-content: center;
}

JavaScript

// Dice Lab -- Class example with jQuery

$(document).ready(function() {

  // create a class called Die
  class Die {
    constructor(value) {

      // set value property
      this.value = value;

      // create a div for each new object, assign class
      this.div = $('<div></div>').attr("class", "div");
      $(this.div).append(this.value);
      $('.container').append(this.div);

      // when Roll All Dice button is clicked, run the rollAll method (below)
      $('#all').click(() => this.rollAll());

      // when a div is clicked, run rollOne function below
      $('.div').click(() => this.rollOne());

      // when any div is double clicked, run removeOne function below
      $('.div').dblclick(() => this.removeOne());
    }

    // roll all dice again; get random number, replace value in div
    rollAll() {
      this.value = Math.floor(Math.random() * 6 + 1);
      $(this.div).html(this.value);
    }

    // roll the clicked dice again
    rollOne() {
      this.value = Math.floor(Math.random() * 6 + 1);
      $(this.div).html(this.value);
    }

    //remove die that was clicked from display and from sumable dice
    removeOne() {
      console.log($(this.div));
      $(this.div).remove();
    }

  }

  // when Add All Dice button is clicked, add value (text) in each div, display sum as alert
  $('#sum').click(function() {
    let sum = 0;
    $('.div').each(function() {
      sum += parseFloat($(this).text()); //parseFloat turns strings into sumable numbers
    })
    alert(sum);
  })

  // Roll 1 Die button generates random number, creates an instance of Die class
  $('#btn').click(function roll() {
    let val = Math.floor(Math.random() * 6 + 1);
    let die = new Die(val);
  })

})