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
- Create a new TypeScript file
Creating the Basic Dice Components
- Define an enum named
DiceFacerepresenting the six faces of a dice: ONE, TWO, THREE, FOUR, FIVE, and SIX.
Dependency Injection with an Interface
- Define an interface named
Randomizerwith a single methodgetRandomFacethat returns aDiceFace. - Create a class named
DefaultRandomizerthat implements theRandomizerinterface. This class should provide the default randomization behavior (i.e., returning a random face of the dice). - Create a class named
Dicewith: - A private field named
_faceof typeDiceFace. - A constructor that accepts an instance of a class implementing the
Randomizerinterface. - A method named
rollthat sets the_faceusing the provided randomizer instance. -
A method named
printthat displays the current face of the dice. -
Instantiate the
Diceclass using theDefaultRandomizerand test its behavior by rolling and printing.
Higher-Order Function for Shaking
- Modify the
Diceclass to also accept a higher-order function in its constructor. This function should be of type() => DiceFaceand should be used as an alternative to theRandomizerfor setting the dice face. - Create a function named
customShakeoutside theDiceclass that provides a custom shake behavior (e.g., always returningDiceFace.SIX). - Instantiate the
Diceclass using thecustomShakefunction 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();