Last active
June 15, 2018 00:57
-
-
Save Jaylooker/f382686bafdf37da6493071cc0654bf9 to your computer and use it in GitHub Desktop.
A Python 3 dice class in that rolls between 3 and the systems word size.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
.. module:: dice | |
.. moduleauthor:: Jack Bartolone <jackbartolone@comcast.net> | |
''' | |
import random | |
import operator | |
import sys | |
class Dice(object): | |
''' | |
Python 3 dice used to roll a random an integer | |
between 3 to 2^63 -1 for 64-bit machines and 3 to 2^31-1 for 32-bit machines. | |
''' | |
#constants | |
MINSIDES = 3 | |
#constructors | |
def __init__(self, sides): | |
''' | |
Intializes dice with :param sides | |
:param sides: sides of the dice | |
:raises: Exception for out of bounds and non-integer values | |
''' | |
self.sides = sides | |
#range check | |
sides = property(operator.attrgetter('_sides')) | |
@sides.setter | |
def sides(self, value): | |
''' | |
Throws exceptions for invalid input. | |
:param value: setter value | |
''' | |
if (value <= self.MINSIDES): | |
raise Exception('Dice can must have at least three sides') | |
elif (value > sys.maxsize): | |
raise Exception('Dice value exceeds max int size') | |
elif (isinstance(value, int)): | |
raise Exception('Dice value is not an integer') | |
else: | |
self._sides = value | |
#methods | |
def roll(self): | |
''' | |
Rolls dice. | |
:returns: pseudorandom integer between 1 and its sides | |
''' | |
result = random.randint(1, self.sides) | |
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
.. module:: dice | |
.. moduleauthor:: Jack Bartolone <jackbartolone@comcast.net> | |
''' | |
import pytest | |
import dice | |
import sys | |
def testlowerbounds(): | |
'''Test if numbers < 3 throw exception''' | |
with pytest.raises(Exception): | |
dice(1) | |
def testinbounds(): | |
'''Test if sys.maxsize + 1> numbers >= 3 not throw exception''' | |
with pytest.raises(Exception): | |
dice(3) | |
def testupperbounds(): | |
'''Test if sys.maxsize + 1 > numbers throw exception''' | |
with pytest.raises(Exception): | |
dice(sys.maxsize + 1) | |
def testisaninteger(): | |
'''Test if throwing exception for non-integer value''' | |
with pytest.raises(Exception): | |
dice('word') | |
testlowerbounds() | |
testinbounds() | |
testupperbounds() | |
testisaninteger() | |
#print docs | |
help(Dice) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment