Die = function({value = [1] , numDice = 1}) {
const random = () => Math.floor(Math.random() * 6) + 1,
roll = () => {
const dieRolls = new Array(numDice).fill()
.map(random)
return dieRolls
}
const svg = d3.create("svg")
.attr("width", numDice * 100)
.attr("height", 100)
const g = svg.append("g").attr("transform", `translate(0 50)`)
const element = svg.node()
element.value = (value.length != numDice) ? roll() : value
console.log("Die",element.value)
const render = function(sel) {
const dice = sel.selectAll(".die")
.data(element.value)
.join(enter => {
const c = enter.append("g")
.attr("transform", (d,i) => `translate( ${i*100 + 50} 0)`)
.attr("class", "die")
c.append("rect")
.attr("width", 84)
.attr("height", 84)
.attr("x", -42)
.attr("y", -42)
.attr("rx", 10)
.attr("stroke", "#000")
.attr("fill", "oldlace")
c.append("circle")
.attr("r", 40)
.attr("fill", "papayawhip")
.attr("stroke", "navajowhite")
// c.append("circle")
// .attr("class", "dot")
// .attr("r", 20)
// c.append("text").attr("class", "dot")
return c
},
update=> update,
exit => exit.remove())
const scale = d3.scaleLinear([-1,1], [-20, 20])
const pips = {
1: [[ 0, 0]],
2: [[ 1,-1], [-1, 1]],
3: [[ 0, 0], [ 1,-1], [-1, 1]],
4: [[-1,-1], [ 1,-1], [-1, 1], [ 1,1]],
5: [[ 0, 0], [-1,-1], [ 1,-1], [-1,1], [ 1, 1]],
6: [[-1,-1], [ 1,-1], [-1, 0], [ 1,0], [-1, 1], [1, 1]]
}
dice.selectAll(".pip")
.data(d => {
console.log("pips[d]", d, pips[d])
return pips[d]
})
.join(enter => enter.append("circle")
.attr("class", d => `pip`)
.attr("r", 5)
.attr("fill", "#000"),
update => update,
exit => exit.remove() )
.attr("cx", d => scale(d[0]))
.attr("cy", d => scale(d[1]))
// dice.each(function(d) {
// console.log("each", d)
// d3.select(this)
// .select(".dot")
// .attr("fill", d)
// // .text(d)
// })
}
render(g)
element.onmousedown = () => {
element.style.transition = "none";
// element.style.transform = `scale(1.5) rotate(${Math.random() * 90 - 45}deg)`;
};
element.onclick = () => {
element.value = roll()
render(g)
g.transition()
.duration(0)
.style("opacity", 0)
g.transition()
.delay(500)
.duration(250)
.style("opacity", 1)
element.dispatchEvent(new Event("input", {bubbles: true}));
};
console.log("element.value", element.value)
return element
}