| 1 | """Run a CLI to simulate dice throws.""" |
| 2 | |
| 3 | import random |
| 4 | import asyncio |
| 5 | import argparse |
| 6 | |
| 7 | from aioconsole import AsynchronousCli |
| 8 | |
| 9 | |
| 10 | async def dice(reader, writer, faces): |
| 11 | for _ in range(3): |
| 12 | await asyncio.sleep(0.33) |
| 13 | writer.write(".") |
| 14 | await writer.drain() |
| 15 | writer.write("\n") |
| 16 | return random.randint(1, faces) |
| 17 | |
| 18 | |
| 19 | def main(): |
| 20 | parser = argparse.ArgumentParser(description="Throw a dice.") |
| 21 | parser.add_argument( |
| 22 | "--faces", "-f", metavar="N", type=int, default=6, help="Number of faces" |
| 23 | ) |
| 24 | cli = AsynchronousCli({"dice": (dice, parser)}, prog="dice") |
| 25 | |
| 26 | loop = asyncio.get_event_loop() |
| 27 | loop.run_until_complete(cli.interact()) |
| 28 | |
| 29 | |
| 30 | if __name__ == "__main__": |
| 31 | main() |