Skip to content

J120 Dice Game

Objective: Create two ES6 modules that represent a dice (dice.mjs) and a cup (cup.mjs) containing five dice. You should be able to test the modules through a third module, app.mjs.

Task Details:

  1. Dice Module (dice.mjs):

    • The dice should be represented as a class named Dice.
    • It should have a value between 1 and 6.
    • If no value is provided or if the provided value is invalid, an error should be thrown.
    • The dice should include a print method that returns the current value formatted like [value].
    • Include a shake method that assigns a new random value to the dice.
  2. Cup Module (cup.mjs):

    • This module should represent a cup containing five dice.
    • Represent this as a class named Cup.
    • The cup starts with five dice, each initialized to the value of 1.
    • Include a print method that returns the current value of all dice in the cup.
    • Include a shake method that assigns new random values to all the dice in the cup.
  3. App Module (app.mjs):

    • This is your testing module.
    • Import both the Dice and Cup classes.
    • Create a new dice and print its value. Shake the dice and print its new value.
    • Create a new cup and print its value. Shake the cup and print its new value.
Solution
  1. dice.mjs
// dice.mjs

export default class Dice {
    constructor(value = 1) {
        if (value < 1 || value > 6) {
            throw new Error("Invalid dice value. It should be between 1 and 6.");
        }
        this.value = value;
    }

    print() {
        return `[${this.value}]`;
    }

    shake() {
        this.value = Math.floor(Math.random() * 6) + 1;
    }
}
  1. cup.mjs
// cup.mjs

import Dice from './dice.mjs';

export default class Cup {
    constructor() {
        this.dices = Array(5).fill().map(() => new Dice(1));
    }

    print() {
        return this.dices.map(d => d.print()).join(' ');
    }

    shake() {
        this.dices.forEach(d => d.shake());
    }
}
  1. app.mjs
// app.mjs

import Dice from './dice.mjs';
import Cup from './cup.mjs';

// Testing the Dice class
let d = new Dice(5);
console.log(d.print());  // Expected Output: [5]
d.shake();
console.log(d.print());  // Expected Output: [random value between 1 and 6]

// Testing the Cup class
let c = new Cup();
console.log(c.print());  // Expected Output: [1] [1] [1] [1] [1]
c.shake();
console.log(c.print());  // Expected Output: [random value] [random value] [random value] [random value] [random value]

How to run: In a Node.js environment supporting ES6-style modules, run the app using:

node --experimental-modules app.mjs