block by mgold f19a850f12d4e87b5bbc

Dice roll probabilities

Full Screen

Built with blockbuilder.org

index.html

<!DOCTYPE html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
    <style>
      body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
      svg { width: 100%; height: 100%; }
      text { fill: white; font-family: avenir, sans-serif; text-anchor: middle}
    </style>
  </head>

  <body>
    <script>
      
      var SIDES = 6;
      
      function rollDie(){
        return Math.floor(Math.random()*SIDES) + 1;
      }
      
      function indexToPos(i){
        return [Math.floor(i/SIDES) + 1, i % SIDES + 1];
      }
      
      function posToIndex(i,j){
        return (i-1)*SIDES + (j-1);
      }
      
      var margin = {top: 20, right: 10, bottom: 20, left: 10};
      var width = 960 - margin.left - margin.right;
      var height = 500 - margin.top - margin.bottom;
      var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      var s = 50;
      var data = d3.range(36).map(function(){return 0})
      var totalData = 0;
      
      var color = d3.scale.linear()
        .range(["#000000", "#FF0000"])
      
      
      function render(){
        var cells = svg.selectAll("g.cell").data(data)
      
     	  newCells = cells.enter()
     		 	.append("g")
          .attr("class", "cell")
          .attr("transform", function(d,i){
        		var pos = indexToPos(i);
          	return "translate("+(s*pos[0])+","+(s*pos[1])+")"
        	})
       
        newCells.append("rect")
     		 	.attr({width: s+"px", height: s+"px"})
        	
        newCells.append("text")
        	.attr("class", "rollCount")
          .attr("transform", "translate("+s/2+","+s/2+")")
        
        newCells.append("text")
          .attr("transform", "translate("+s/2+","+0.8*s+")")
          .text(function(d,i){ return "(" + indexToPos(i) + ")" })
          .style("font-size", "12px")
        
      
        cells.select("rect")
          .attr("fill", color)
        cells.select("text.rollCount")
        	.text(function(d){return d})
      }
      
      render();
      
      d3.timer(function(){
        var i = posToIndex(rollDie(), rollDie());
        data[i]++;
        totalData++;
        color.domain(d3.extent(data))
        render();
      })
        
      
      
    </script>
  </body>