Last active
December 1, 2019 07:43
-
-
Save garbados/be53675e8bd37b5931710448f0f82be4 to your computer and use it in GitHub Desktop.
DIY Python dice-rolling library, with example.
This file contains hidden or 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
# roll 6 ability scores using the worst 4 of 5d6 | |
$ python -c 'from roll import d6; print([d6(5, w=4) for i in range(6)])' | |
[11, 14, 11, 13, 9, 15] |
This file contains hidden or 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
import random | |
def dN(n): | |
return random.randint(1, n) | |
def roll(n=1, m, x=0, b=None, w=None): | |
""" | |
Roll N dM dice, adding X to the sum. | |
If `b` is an integer, take the highest `b` rolls. | |
Or if `w` is an integer, take the lowest `w` rolls. | |
""" | |
rolls = [dN(m) for i in range(n)] | |
rolls.sort() | |
if isinstance(b, int): | |
rolls = rolls[-b:] | |
elif isinstance(w, int): | |
rolls = rolls[:w] | |
return sum(rolls) + x | |
# Convenience methods for accessing roll | |
def d4(n, *args, **kwargs): | |
return roll(n, 4, *args, **kwargs) | |
def d6(n, *args, **kwargs): | |
return roll(n, 6, *args, **kwargs) | |
def d8(n, *args, **kwargs): | |
return roll(n, 8, *args, **kwargs) | |
def d10(n, *args, **kwargs): | |
return roll(n, 10, *args, **kwargs) | |
def d12(n, *args, **kwargs): | |
return roll(n, 12, *args, **kwargs) | |
def d20(n, *args, **kwargs): | |
return roll(n, 20, *args, **kwargs) | |
def d100(n, *args, **kwargs): | |
return roll(n, 100, *args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment