Lab - Dice

Let’s suppose we want to make a set of dice rolling utilities. We will define a generic Die class, representing a single die with an arbitrary number of sides. We will also define six-sided Die6 and twenty-sided Die20 subclasses.

Pseudorandom Number Generator

We will use the randint function from the random library to generate pseudo-random numbers for our dice rolls. It takes two integers as arguments, a min and max, and returns a random integer between the two.

Note: Do NOT use Python’s standard random library for cryptographic purposes - it is deterministic and NOT a cryptographically secure PRNG.

File Layout

We will start with a file layout like this:

dice_lab/
   roll.py
   dice/
      __init__.py
      die.py
      dice.py

Code Stubs

roll.py

This script contains an example of using the classes. If you can run the example, your dice classes are at least minimally working.


'''
Lab - Dice

Make a package of dice rolling utilities.
* Make a simple Die class for the basic rolling of a die
* Make D6 (six-sided) and D20 (twenty-sided) subclasses
* Each Die instance will have a roll() method, returning a random
  number between 1 and the number of sides on that die.
* When one die instance is added to another die instance, roll() is
  called on both instances and the results added together.
* When a die instance is added to an integer, the instance's roll()
  method is called, and the result is added to the integer.
* If a die is added to something other than an integer or another die, the
  operation should fail with an exception.
'''

from dice.dice import Die6
from dice.dice import Die20


def main():
    d6 = Die6()
    d20 = Die20()
    print d6.roll()     # Returns int between 1 and 6
    print d6 + d20      # Returns int between 2 and 26
    print d6 + 15       # Returns int between 16 and 21
    print d6 + "foobar" # Throws exception

if __name__ == '__main__':
    main()

dice/__init__.py

The __init__.py file will be mostly empty, containing only a docstring and a VERSION variable:

'''
dice - Utilities to simulate dice rolling.
'''

VERSION = '0.1'

dice/die.py

The main Die class is found in die.py:

from random import randint

class Die(object):
    '''A single die with arbitrarily many sides.'''
    
    def roll(self):
        '''Returns a random number between 1 and the number of sides on this die'''
        pass
    
    def __add__(self, other):
        '''Adds the result of rolling this die to an integer, or to the result of rolling 
        another die.'''
        pass

dice/dice.py

Two subclasses, representing six- and twenty-sided dice, are found in dice.py.

1
2
3
4
5
6
7
class Die6(Die):
    '''A six-sided die'''
    pass

class Die20(Die):
    '''A twenty-sided die'''
    pass