28 - Virtual Dice Roller with Multiple Dice

Description

Develop a web application or React app for a virtual dice roller with the following features:

  • Allows users to choose the number of dice they want to roll (from a dropdown menu or buttons).

  • Supports various types of dice (e.g., D4, D6, D8, D10, D12, D20) with selectable options.

  • Rolls the chosen number of dice and displays the individual results for each die.

  • Calculates and displays the sum of all rolled dice.

2. Puzzle Algorithm:

  1. State Management:

    • Define state variables to hold:

      • numberOfDice: Selected number of dice to roll.

      • diceType: Array of chosen dice types for each die.

      • diceResults: Array of rolled values for each die.

      • totalRoll: Sum of all rolled dice.

      • pastRolls: Array of previous roll results for history.

  2. User Interaction:

    • Provide a dropdown menu or buttons for users to choose the number of dice.

    • Offer a selection of available dice types (D4, D6, etc.) for each die.

    • Implement a roll button to trigger dice rolling and update results.

  3. Dice Rolling Logic:

    • Generate random numbers based on the chosen dice type for each die.

    • Store the individual results in the diceResults state array.

    • Calculate the sum of all rolled values and update the totalRoll state.

  4. Display and Output:

    • Show the chosen number of dice and their selected types.

    • Display the individual results for each die after rolling.

    • Show the total sum of all rolled dice prominently.

Code

import React, { useState } from 'react';

const diceTypes = ['D4', 'D6', 'D8', 'D10', 'D12', 'D20'];

function DiceRoller() {
  const [numberOfDice, setNumberOfDice] = useState(1);
  const [diceType, setDiceType] = useState(Array(numberOfDice).fill('D6'));
  const [diceResults, setDiceResults] = useState([]);
  const [totalRoll, setTotalRoll] = useState(0);
  const [pastRolls, setPastRolls] = useState([]);

  const handleDiceNumberChange = (event) => setNumberOfDice(Number(event.target.value));

  const handleDiceTypeChange = (index, event) => {
    const newDiceType = [...diceType];
    newDiceType[index] = event.target.value;
    setDiceType(newDiceType);
  };

  const handleRollClick = () => {
    const newDiceResults = [];
    let newTotalRoll = 0;
    for (let i = 0; i < numberOfDice; i++) {
      const roll = Math.floor(Math.random() * Number(diceType[i].slice(1))) + 1;
      newDiceResults.push(roll);
      newTotalRoll += roll;
    }
    setDiceResults(newDiceResults);
    setTotalRoll(newTotalRoll);
    setPastRolls([...pastRolls, { diceType, diceResults, totalRoll }]);
  };

  return (
    <div className="dice-roller">
      <div className="settings">
        <label htmlFor="number-of-dice">Number of dice:</label>
        <select id="number-of-dice" onChange={handleDiceNumberChange}>
          {Array.from({ length: 10 }, (_, i) => i + 1).map((num) => (
            <option key={num} value={num}>{num}</option>
          ))}
        </select>
        {Array.from({ length: numberOfDice }, (_, i) => (
          <label key={i} htmlFor={`dice-type-${i}`}>Dice {i + 1} type:</label>
          <select key={i} id={`dice-type-${i}`} value={diceType[i]} onChange={(e) => handleDiceTypeChange(i, e)}>
            {diceTypes.map((type) => (
              <option key={type} value={type}>{type}</option>
            ))}
          </select>
        ))}
      </div>
      <button onClick={handleRollClick}>Roll Dice</button>
      <div className="results">
        {diceResults.map((result, i) => (
          <div key={i} className="dice-result">
            Dice {i + 1}: {result}
          </div>
        ))}
        <div className="total-roll">Total Roll: {totalRoll}</div>
      </div>
      <div className="past-rolls">
        <h3>Past Rolls:</h3>
        <ul>
          {pastRolls.map((roll, i) => (
            <li key={i}>
              {roll.diceType.join(', ')}: {roll.diceResults.join(', ')} = {roll.totalRoll}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

export default DiceRoller;

Explanation

  • The handleRollClick function generates random results for each die based on its type, calculates the total roll, and updates the state.

  • The JSX renders the UI with dropdowns for number of dice and dice types, a roll button, individual dice results, total roll, and past roll history.

Additional notes

Extend by adding features like:

  • Ability to hold and re-roll specific dice.

  • Custom dice with user-defined number of sides.

  • Animations and sound effects for rolling dice.

  • History of past rolls for tracking results.

Last updated