如何将PrimeDice可证明公平的百分骰脚本改为六面骰?
Got it, let's tweak that PrimeDice provably fair script to roll a standard 6-sided die instead of a 100-sided one. Here's how to do it step by step:
Convert PrimeDice's Provably Fair 100-Sided Roll to 6-Sided Die
Step 1: Context for the Original Roll Function
First, let's fill in the missing portion of the official roll function (your snippet cut off mid-logic). The original code extracts a numeric value from the SHA512 hash and scales it to a 0-99 range for the 100-sided roll. Here's the complete standard implementation for reference:
var crypto = require('crypto'); var roll = function(key, text) { var hash = crypto.createHmac('sha512', key).update(text).digest('hex'); var index = 0; var result; do { result = parseInt(hash.substring(index * 5, index * 5 + 5), 16); index++; } while (result >= 100000); // Restrict to values that fit 0-99 return result % 100; // Returns 0-99 for 100-sided roll };
Step 2: Modified Code for 6-Sided Die (1-6)
The core changes are adjusting the range check to avoid bias and updating the final calculation to map to a 1-6 range. Here's the fully updated script:
var clientSeed = "Test1"; var serverSeed = "a72c7d6e95badadadab91d729f4eef30af2c019488bb76274290ad183"; var nonce = 1; var crypto = require('crypto'); var rollD6 = function(key, text) { var hash = crypto.createHmac('sha512', key).update(text).digest('hex'); var index = 0; var result; // Use the largest multiple of 6 less than 16^5 (1048576) to avoid bias // 1048572 = 6 * 174762, so all values below this divide evenly into 6 outcomes do { result = parseInt(hash.substring(index * 5, index * 5 + 5), 16); index++; } while (result >= 1048572); // Convert 0-5 modulo result to standard 1-6 die range return (result % 6) + 1; }; // Calculate and log your 6-sided roll var d6Result = rollD6(serverSeed, clientSeed + '-' + nonce); console.log('Your 6-sided die roll:', d6Result);
Key Changes Breakdown
- Bias-Free Range Check: Instead of limiting values to <100000, we use a range divisible by 6. This ensures every die face (1-6) has an equal probability of being rolled.
- Final Roll Calculation:
(result % 6) + 1shifts the 0-5 modulo result to the standard 1-6 die range that players expect. - Provable Fairness Preservation: We keep the original input structure (
clientSeed + '-' + nonce) to maintain PrimeDice's provably fair verification flow.
Quick Verification Tip
To keep the system provably fair:
- Keep the server seed secret until all rolls using that seed are completed (per PrimeDice's standard practice)
- Increment the nonce by 1 for every subsequent roll with the same client/server seed pair
内容的提问来源于stack exchange,提问作者user9586797
相关产品推荐
相关产品推荐

