T060 Using Classes (dice/cup)
In this assignment, you’ll delve deeper into TypeScript by working with classes, enums, static methods, and properties. You’ll create a dice simulation, where you can roll individual dice and also shake a cup containing multiple dice.
Setup
- Create a new TypeScript file
Creating a Dice Class
- Define an enum named
DiceFacerepresenting the six faces of a dice: ONE, TWO, THREE, FOUR, FIVE, and SIX. - Create a class named
Dicewith the following: - A private field named
_faceof typeDiceFace. - A static method named
randomFacethat returns a random face of the dice. - A method named
rollthat sets a random face to_faceusing therandomFacemethod. - A getter property named
facethat returns the current face of the dice. - A method named
printthat displays the current face of the dice.
Creating a Cup Class
- Create a class named
Cupwith the following: - A private field named
_diceswhich is an array ofDiceobjects, initialized with 5 dice. - A method named
shakethat rolls all the dice in the_dicesarray. - A method named
printthat displays the current face of all the dice in the cup.
Simulating the Dice and Cup
- Create an instance of the
Diceclass and roll it. Print its face. - Create an instance of the
Cupclass, shake it, and then print the faces of all the dice in the cup.
Solution
Solution
Creating a Dice Class
enum DiceFace {
ONE = 1,
TWO,
THREE,
FOUR,
FIVE,
SIX
}
class Dice {
private _face: DiceFace;
static randomFace(): DiceFace {
return Math.floor(Math.random() * 6) + 1 as DiceFace;
}
roll() {
this._face = Dice.randomFace();
}
get face(): DiceFace {
return this._face;
}
print() {
console.log(`Dice Face: ${this._face}`);
}
}
Creating a Cup Class
class Cup {
private _dices: Dice[] = [new Dice(), new Dice(), new Dice(), new Dice(), new Dice()];
shake() {
for (let dice of this._dices) {
dice.roll();
}
}
print() {
console.log("Cup contains:");
for (let dice of this._dices) {
dice.print();
}
}
}