I have been reading Fluent Python, and I can tell that it's going to help me be a better Python coder right away.
A while ago, I started a Javascript library for rolling common dice types, which I intended to use for various games. While reading Fluent Python, I realized that I could write the same logic in a much more compact form, thanks to listcomps, generator functions, and unpacking. In fact, the core implementation takes only four lines of code:
sides = [4, 6, 8, 10, 12, 20]
d4, d6, d8, d10, d12, d20 = [range(1, count + 1) for count in sides]
def roll(die, count=1):
return tuple(choice(die) for _ in range(count))
I can even shave off a whole line (and a possibly unneeded assigment) like this:
d4, d6, d8, d10, d12, d20 = [range(1, sides + 1) for sides in (4, 6, 8, 10, 12, 20)]
That might even be more readable…
This is pretty small. The JS library is much larger (and depends on Ramda to make it more functional), though I suspect I could rewrite it to be more compact now (and in fact I did a more compact version later). And there's more I could do to make this Python version hardier. Nevertheless, I continue to be impressed by how smooth this language can be.
I tested this code in CPython and CircuitPython 7.3.3.
I also coded a little dice roller for Arduino. That's the roller.ino
file.