Hey everyone,
It's time for another "Fun with Python" post. A while back, I shared a Terminal Dice Roller that used Hive to generate random, deterministic results. Today, we're going to use that same concept to shuffle a deck of cards and draw from it right in the terminal.
How it Works: Seeding with the Blockchain
The most interesting part of this script is how it generates a "random" result that is both unpredictable beforehand and verifiable after the fact. It does this by creating a seed based on live data from Hive blocks.
- Fetch the Latest Blocks: The script uses my
hive-nectar
library to get the last two blocks produced on the Hive blockchain. - Create a Seed String: It then creates a long string of text by concatenating the block ID of the first block, the block ID of the second block, and the transaction ID of a random transaction found in that second block.
- Hash the String: This long string is then hashed using SHA-256, which produces a unique and very large number.
- Seed the Draw: This number is used as the seed for Python's
random
module. This means that for the exact same two blocks, the shuffle and draw will always produce the same result, making it provably fair.
Note: If this were taking place as part of a transaction I would use that block, the previous block and that transaction instead of random one.
The Code
The script uses hive-nectar
to communicate with the Hive and the rich
library to create the nicely formatted table you see in the screenshot. (Eagle-eyed readers might get a pretty decent idea of what I'm working on from the context of this post and the image.)
To build a deck of cards:
def build_deck(include_jokers: bool = False) -> List[str]:
"""Return a list of card labels like 'A♠', '10♥', 'K♦', '3♣'."""
ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
suits = [("♠", "Spades"), ("♥", "Hearts"), ("♦", "Diamonds"), ("♣", "Clubs")]
deck = [f"{r}{s[0]}" for r in ranks for s in suits]
if include_jokers:
deck += ["Joker🃏", "Joker🃏"]
return deck
You can find the full script at the Gist linked below, and will be added to the project builder soon, as well as the dice one.
As always, Michael Garcia a.k.a. TheCrazyGM