Skip to footer navigation.

« Oatmeal

dice.js 2.0

A little dice rolling class in JavaScript for all your dice rolling needs.

class diceRoller {

  constructor() {
    this.log = [];
  }

  validate(diceNotation) {
    const match = /^(\d+)?d(\d+)([+-]\d+)?$/.exec(diceNotation);
    if (!match) {
      throw "Invalid dice notation: " + diceNotation;
    } else {
      return match;
    }
  }

  parseDice(diceNotation) {
    const match = this.validate(diceNotation);
    if (match) {
      const diceInfo = {
        numberOfDice: typeof match[1] === "undefined" ? 1 : parseInt(match[1]),
        sidesOfDice: parseInt(match[2]),
        diceModifier: typeof match[3] === "undefined" ? 0 : parseInt(match[3])
      };
      return diceInfo;
    }
  }

  tallyRolls(diceData) {
    let total = 0;
    for (let i = 0; i < diceData.numberOfDice; i++) {
      total += Math.floor(Math.random() * diceData.sidesOfDice) + 1;
    }
    total += diceData.diceModifier;
    return total;
  }

  roll(humanInput) {
    const rollResult = this.tallyRolls(this.parseDice(humanInput));
    const rightNow = new Date();
    let logEntry = {
      "timestamp": rightNow.toISOString(),
      "input": humanInput,
      "result": rollResult
    }
    this.log.push(logEntry);
    return rollResult;
  }

};

And a quick example of how to use it,

// instantiate yo' players
const playerSarah = new diceRoller();
const playerEli = new diceRoller();

// play the game
playerSarah.roll('2d10-4');
playerEli.roll('2d12+12');
playerSarah.roll('1d12');
playerEli.roll('1d2');


// check the log!
console.log('==== Sarah\'s log ====');
playerSarah.log.forEach(logEntry => {
  console.log(logEntry.input + " : " + logEntry.result + " : " + logEntry.timestamp);
});

console.log('==== Eli\'s log ====');
playerEli.log.forEach(logEntry => {
  console.log(logEntry.input + " : " + logEntry.result + " : " + logEntry.timestamp);
});

Published

Tags