AdamTyler / react-dice-complete

Complete dice rolling functionality and animations
http://adam-tyler.com/react-dice-complete
ISC License
79 stars 26 forks source link

change default value from 6 #14

Closed MichalPP closed 4 years ago

MichalPP commented 4 years ago

I would like to change the default (unrolled) value of the dice from 6 to something else via props (and leave it to 6 if no default value is present in props). demo of my game

an even nicer feature would be to change the default face of the dice to something custom (question mark, text 'push', clicking finger, ...) so that users are pushed to click it.

do you plan such enhancement? thanks

guilhermebruzzi commented 4 years ago

@MichalPP For now, I've created a wrapper on ReactDice that on its useEffect set the values with rollAll and with rollTime: 0:

import React, { useRef, useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import ReactDice from 'react-dice-complete'

const DiceWrapper = ({ onNumberSort, diceValues }) => {
  const reactDice = useRef(null)
  const [sorted, setSorted] = useState(false)
  const [sortNum, setSortNum] = useState(0)
  const canRollAll = !sortNum
  const rollTime = canRollAll ? 2 : 0

  useEffect(() => {
    if (
      !reactDice ||
      !reactDice.current ||
      canRollAll ||
      sorted ||
      !diceValues
    ) {
      return
    }

    reactDice.current.rollAll(diceValues)
  }, [canRollAll, diceValues, sorted])

  const onRollAll = () => {
    if (!reactDice || !reactDice.current || !canRollAll) {
      return
    }

    reactDice.current.rollAll()
  }

  const onRollDone = (num, rollValues) => {
    setSorted(true)
    setSortNum(num)
    onNumberSort && onNumberSort(num, rollValues)
  }

  return (
    <div>
      <ReactDice
        rollDone={onRollDone}
        ref={(dice) => {
          reactDice.current = dice
          const currentDiceNum = diceValues ? diceValues[0] + diceValues[1] : 0
          if (currentDiceNum) {
            setSortNum(currentDiceNum)
          }
        }}
        rollTime={rollTime}
      />
      <button onClick={onRollAll} disabled={!canRollAll}>
        SORT
      </button>
    </div>
  )
}

DiceWrapper.propTypes = {
  onNumberSort: PropTypes.func.isRequired,
  diceValues: PropTypes.arrayOf(PropTypes.number),
}

export default DiceWrapper

The real component is a little more complex, but I've tried to copy and paste the important parts and as a reference

AdamTyler commented 4 years ago

The prop defaultRoll has been added in release 1.2.1 and will allow you to set the default value.