An object oriented approach to rolling a custom dice! this technique allows a person to define a custom dice by list, by integer, or by nothing at all defaulting to 6 sides.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from random import choice as _choice
class die:
def __init__(self, sides=6):
try: self.sides = range(1,sides+1)
except TypeError: self.sides = list(sides)
def __str__(self):
return str(_choice(self.sides))
'''
#to roll
#default
print die()
#custom number
print die(12)
#custom sides
print die(('yes','no','maybe'))
#changing die
changing=['something','something else','also something']
print die(changing)
changing+=['something new!']
print die(changing)
'''
|
is there something similar to __str__ for class' that will return anything and not just a string??
Tags: oop
Hi
By storing the sides as a list, equal to range(1, sides + 1) when the die is initiated with an integer, you can eliminate the if statement in the roll method...
from random import randrange as _rand
class die():
Cheers
Tony
BTW, is there a neater way to put code into comments? :-)
Use random.choice() instead? What's wrong with using the random.choice method? Seems like it was built for exactly this situation.
Also I tend to try to employ the "it's easier to ask forgiveness than permission" principle when possible to avoid things like type checking. So initially assume the sides parameter is an integer. If that assumption fails then assume it's something iterable. If that fails then bubble the exception back up to the user.
thanks for the comment! thanks for looking it over, that does look like a better way to approach this algorithm!
quick correction. if anyone plans to use Brandons code, change range(sides) to range(1,sides+1), the default of range includes 0 and only goes up to sides, not including it. so the code should be:
from random import choice
class die: def __init__(self, sides=6): try: self.sides = range(1,sides+1) except TypeError: self.sides = list(sides)
def roll(self): return choice(self.sides)
oops. i meant
if anyone plans to use Brandons code,
change range(sides) to range(1,sides+1),
the default of range includes 0 and only goes up to sides,
not including it. so the code should be:
yep. you paste your code in and use a little html code to display it properly:
pre "your code" /pre
except surround the pre and /pre with a less than symbol on the left and a greater than symbol on the right...
and thats it!
honestly. i hate the way comments are handled on this site... i cant even delete a comment that i wrote... and you cant put returns or tabs in without using the limited html code they allow... not a very good way to go about it... although i do like nested comments!
theif. alright i'm stealing your code, and modifying it a bit haha i hope you dont mind, i'll credit you or remove it if you would like! just let me know!