Skip to content

Instantly share code, notes, and snippets.

@HarryR
Last active April 23, 2023 18:04
Show Gist options
  • Save HarryR/6bc0d22632f097fcf479a7ccadbd7120 to your computer and use it in GitHub Desktop.
Save HarryR/6bc0d22632f097fcf479a7ccadbd7120 to your computer and use it in GitHub Desktop.
Shuffle a deck of cards on Oasis Sapphire
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
contract SapphireShuffle {
address private constant RANDOM_BYTES = 0x0100000000000000000000000000000000000001;
error ErrorGeneratingRandom();
function _random_bytes32()
private view
returns (bytes32)
{
(bool success, bytes memory entropy) = RANDOM_BYTES.staticcall(
abi.encode(uint256(32), "")
);
if( entropy.length != 32 || false == success ) revert ErrorGeneratingRandom();
return bytes32(entropy);
}
// Durstenfeld's version of Fisher-Yates shuffle
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
function shuffle_deck(uint256 seed, uint8 k)
private pure
returns (bytes memory deck)
{
deck = new bytes(k);
for( uint8 i = 0; i < k; i++ ) {
deck[i] = bytes1(i);
}
for( uint8 i = (k-1); i > 0; i-- ) {
seed = uint256(keccak256(abi.encodePacked(seed)));
uint8 j = uint8(seed % i);
(deck[j], deck[i]) = (deck[i], deck[j]);
}
return deck;
}
event Deck(bytes d);
function random_deck()
public
{
emit Deck(shuffle_deck(uint256(_random_bytes32()), 52));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment