Skip to content

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

  1. Create a new TypeScript file

Creating a Dice Class

  1. Define an enum named DiceFace representing the six faces of a dice: ONE, TWO, THREE, FOUR, FIVE, and SIX.
  2. Create a class named Dice with the following:
  3. A private field named _face of type DiceFace.
  4. A static method named randomFace that returns a random face of the dice.
  5. A method named roll that sets a random face to _face using the randomFace method.
  6. A getter property named face that returns the current face of the dice.
  7. A method named print that displays the current face of the dice.

Creating a Cup Class

  1. Create a class named Cup with the following:
  2. A private field named _dices which is an array of Dice objects, initialized with 5 dice.
  3. A method named shake that rolls all the dice in the _dices array.
  4. A method named print that displays the current face of all the dice in the cup.

Simulating the Dice and Cup

  1. Create an instance of the Dice class and roll it. Print its face.
  2. Create an instance of the Cup class, 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();
        }
    }
}

Simulating the Dice and Cup

let singleDice = new Dice();
singleDice.roll();
singleDice.print();

let diceCup = new Cup();
diceCup.shake();
diceCup.print();