Advertisement
Guest User

Untitled

a guest
Dec 30th, 2013
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. def dice(number, sides=6):
  2.     total = 0
  3.     for _ in range(number):
  4.         total += random.randrange(1, sides+1)
  5.     return total
  6.  
  7. # I'm calling randrange once _each time through the loop_,
  8. # so I'm getting <number> different random numbers, and
  9. # adding them together. (I used randrange instead of choice
  10. # so you don't have to keep around a list of 4 numbers for
  11. # a d4, and a list of 6 numbers for a d6, and so on.)
  12.  
  13. # Use it like this:
  14.  
  15. strength = dice(3, 6)
  16. intelligence = dice(3, 6)
  17. wisdom = dice(3, 6)
  18. dexterity = dice(3, 6)
  19. constitution = dice(3, 6)
  20. charisma = dice(3, 6)
  21.  
  22. # Each of these six variables will end up with a different
  23. # number from 3-18. (Well, it's _possible_ they'll all be
  24. # the same, just rare--just as it's possible, but rare, to
  25. # roll the same number over and over with real dice.)
  26.  
  27. ###
  28.  
  29. # A cleaner and more idiomatic implementation might be:
  30.  
  31. def die(sides=6):
  32.     return random.randrange(1, sides+1)
  33.  
  34. def dice(number, sides=6):
  35.     return sum(die(sides) for _ in range(number))
  36.  
  37. # You use it the exact same way
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement