Skip to content

T070 Advanced Dice Mechanics

In this assignment, you’ll delve into TypeScript classes and explore advanced concepts such as dependency injection and higher-order functions. Your task is to create a dice simulation with customizable shake behaviors.

Setup

  1. Create a new TypeScript file

Creating the Basic Dice Components

  1. Define an enum named DiceFace representing the six faces of a dice: ONE, TWO, THREE, FOUR, FIVE, and SIX.

Dependency Injection with an Interface

  1. Define an interface named Randomizer with a single method getRandomFace that returns a DiceFace.
  2. Create a class named DefaultRandomizer that implements the Randomizer interface. This class should provide the default randomization behavior (i.e., returning a random face of the dice).
  3. Create a class named Dice with:
  4. A private field named _face of type DiceFace.
  5. A constructor that accepts an instance of a class implementing the Randomizer interface.
  6. A method named roll that sets the _face using the provided randomizer instance.
  7. A method named print that displays the current face of the dice.

  8. Instantiate the Dice class using the DefaultRandomizer and test its behavior by rolling and printing.

Higher-Order Function for Shaking

  1. Modify the Dice class to also accept a higher-order function in its constructor. This function should be of type () => DiceFace and should be used as an alternative to the Randomizer for setting the dice face.
  2. Create a function named customShake outside the Dice class that provides a custom shake behavior (e.g., always returning DiceFace.SIX).
  3. Instantiate the Dice class using the customShake function and test its behavior by rolling and printing.
Solution

Solution

enum DiceFace {
    ONE = 1,
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX
}

interface Randomizer {
    getRandomFace(): DiceFace;
}

class DefaultRandomizer implements Randomizer {
    getRandomFace(): DiceFace {
        return Math.floor(Math.random() * 6) + 1 as DiceFace;
    }
}

class Dice {
    private _face: DiceFace;
    private randomizer?: Randomizer;
    private shakeFunction?: () => DiceFace;

    constructor(randomizer?: Randomizer, shakeFunction?: () => DiceFace) {
        this.randomizer = randomizer;
        this.shakeFunction = shakeFunction;
    }

    roll() {
        if (this.randomizer) {
            this._face = this.randomizer.getRandomFace();
        } else if (this.shakeFunction) {
            this._face = this.shakeFunction();
        }
    }

    print() {
        console.log(`Dice Face: ${this._face}`);
    }
}

let diceWithDefaultRandomizer = new Dice(new DefaultRandomizer());
diceWithDefaultRandomizer.roll();
diceWithDefaultRandomizer.print();

function customShake(): DiceFace {
    return DiceFace.SIX;
}

let diceWithCustomShake = new Dice(undefined, customShake);
diceWithCustomShake.roll();
diceWithCustomShake.print();