Skip to content

Instantly share code, notes, and snippets.

@stut
Created April 20, 2012 13:43
Show Gist options
  • Save stut/2428724 to your computer and use it in GitHub Desktop.
Save stut/2428724 to your computer and use it in GitHub Desktop.
Python Dice Roller
# -*- coding: utf-8 -*-
"""
Dice
Part of rollnmove
Copyright © 2011-2012 Stuart Dallas
"""
import random
class Dice(object):
"""
Implements rolling dice of many different types
"""
def init(state = None):
"""
Seed the random number generator, or restore the state if one is given.
"""
if state == None:
random.seed()
else:
random.setstate(state)
init = staticmethod(init)
def getstate():
"""
Returns the current state of the random number generator. Use in
conjunction with the init function to maintain the state of the
generator between executions. See getstate and setstate in the random
module for details: http://docs.python.org/library/random.html
"""
return random.getstate()
getstate = staticmethod(getstate)
def roll(num_dice = 1, min_num = 1, max_num = 6):
"""
Roll one or more dice with the given minimum and maximum values and
return the total.
"""
retval = 0
for i in range(num_dice):
retval += random.randint(min_num, max_num)
return retval
roll = staticmethod(roll)
def rollmulti(num_dice = 1, min_num = 1, max_num = 6):
"""
Roll one or more dice with the given minimum and maximum values and
return an array containing each result.
"""
retval = []
for i in range(num_dice):
retval.append(random.randint(min_num, max_num))
return retval
rollmulti = staticmethod(rollmulti)
def rollseq(seq, num_results = 1):
"""
Select a single item from the given sequence. If num_results is 1 then
a single value will be returned, otherwise it will be an array.
"""
if num_results == 1:
return random.choice(seq)
retval = []
for i in range(num_results):
retval.append(random.choice(seq))
return retval
rollseq = staticmethod(rollseq)
if __name__ == "__main__":
Dice.init()
print ' 1-6:', Dice.roll()
print ' 1-6 x2:', Dice.roll(2)
print ' 1-6 x6:', Dice.roll(6)
print ' 1-6 x6m:', Dice.rollmulti(6)
print ' Black:', Dice.roll(1, 1, 20)
print '1st gear:', Dice.rollseq([1, 1, 1, 2])
print '2nd gear:', Dice.roll(1, 2, 4)
print '3rd gear:', Dice.roll(1, 4, 8)
print '4th gear:', Dice.roll(1, 7, 12)
print '5th gear:', Dice.roll(1, 11, 20)
print '6th gear:', Dice.roll(1, 21, 30)
print ' 1st x4:', Dice.rollseq([1, 1, 1, 2], 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment