Table of Contents

Dice Class

The “Class Dice” I usually write is a utility class, and as such it is a static class. Therefore this lesson requires previous instruction in basic classes and object oriented programming. Students should be familiar with encapsulating objects as classes as well as aspects of (game) programming such as save files, windows, game engines, etc.

Code Commentary

Static vs. Instantiated Classes

Because this is a “static class”, the class is declared static and used in a static way. To use a class statically means to reference the methods or variables of the class directly:

Instantiated vs. Static example

a = Fruit("Apple")
b = Fruit("Banana")

# Here, since a and b are different instantiations of fruit, the method can return a different value based on the copy of the object in 'b'.
print("A banana is " + b.color())

# Here, we directly reference the class method without instantiating the class. This does not create a copy of the object.
print(Fruit.totalFruits())

We use “Class Dice” as a static class because the methods it contains are a collection of methods about Dice and we don't need to instantiate different dice. We can just call the methods.

String Manipulation

The strategy is to analyze a string and process it. The logic of the method relies on the idea that the method will always receive a string with a 'd' in it. Therefore, it is easy to determine which numbers are being used one we identify the location of the 'd':

    def roll(s):
        d = s.find("d")

        n = s[:d]
        p = s[d+1:]

        return Dice.ndp(n, p)

The function ndp(n,p) returns an n sided dice rolled p times.

The eloquence of finding the d and the macro-ization of what amounts to 'substr()' in many other languages is a feature of Python that can be replicated in other languages by the use of custom functions;

    d = s.find("d")
    n = s.left(d)
    p = s.right(d)

The above code could be written in another language.

Complete Class

Class Dice (in Python)

import random

class Dice:
    def roll(s):
        d = s.find("d")

        n = s[:d]
        p = s[d+1:]

        return Dice.ndp(n, p)

    def ndp(n, p):
        sum = 0
        for x in range(int(n)):
            sum = sum + random.randint(1, int(p))

        return sum