Created
June 1, 2022 23:07
-
-
Save ptmcg/a79e20b126442162ba6b624139fac59f to your computer and use it in GitHub Desktop.
Pyscript+plusminus Dice Roller
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
<html> | |
<head> | |
<title>Plusminus Dice Roller</title> | |
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> | |
<script defer src="https://pyscript.net/alpha/pyscript.js"></script> | |
<py-env> | |
- plusminus | |
</py-env> | |
</head> | |
<body> | |
<py-title>Plusminus Dice Roller</py-title> | |
<table> | |
<tr><td> </td><td> | |
<details><summary>Help</summary> | |
Evaluate expressions representing rolls of dice, as used in many board and | |
role-playing games, such as: | |
<pre> | |
3d6 | |
d20 | |
5d6 + d20 | |
d100 | |
</pre> | |
Enter a dice roll expression, and click "Roll!". | |
</details> | |
<br> | |
<input type="text" id="roll-input-text" style="border:solid 1px;" placeholder="Enter die roll expression..."> | |
<py-button id="roll-btn" label="Roll!" pys-onClick="evaluate_roll"></py-button> | |
<py-button id="clear-btn" label="Clear" pys-onClick="clear_roll_input_and_output"></py-button> | |
<p> | |
<p id="roll-result-value"></p> | |
<py-script> | |
from plusminus import BaseArithmeticParser | |
class DiceRollParser(BaseArithmeticParser): | |
def customize(self): | |
import random | |
def roll_dice(num_dice, sides): | |
return sum(random.randint(1, sides) | |
for _ in range(num_dice)) | |
self.add_operator("d", 1, BaseArithmeticParser.RIGHT, | |
lambda a: roll_dice(1, a)) | |
self.add_operator("d", 2, BaseArithmeticParser.LEFT, | |
lambda a, b: roll_dice(a, b)) | |
parser = DiceRollParser() | |
roll_input = Element("roll-input-text") | |
roll_display = Element("roll-result-value") | |
def evaluate(s): | |
try: | |
return str(parser.evaluate(s)) | |
except Exception as e: | |
return f"{type(e).__name__}: {e}" | |
def evaluate_roll(evt): | |
input_str = roll_input.value.strip() | |
if input_str: | |
ret = evaluate(input_str) | |
roll_display.write(ret) | |
else: | |
clear_roll_input_and_output(None) | |
def clear_roll_input_and_output(evt): | |
roll_input.clear() | |
roll_display.clear() | |
</py-script> | |
</td></tr> | |
</table> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment