Die = function({value = 0,
numDice = 1, numSides = 6,
values= [1,2,3,4,5,6],
random = () => Math.floor(Math.random() * numSides),
face = pips,
callback= d => d} = {}) {
console.log("defaults", value, numDice, numSides, values, random, face, random())
const roll = () => {
const dieRolls = new Array(numDice).fill()
.map(d => values[random()])
console.log("rolls", dieRolls)
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()
const init
element.value = (value.length != numDice) ? roll() : values[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")
return c
},
update=> update,
exit => exit.remove())
dice.call(face({radius: 40}))
}
render(g)
element.onmousedown = () => {
}
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}));
};
return element
}