雜湊競猜開發原理丨雜湊競猜遊戲原始碼丨雜湊競猜系統開發設計程式碼

I76搭2o72建9II9發表於2023-03-27

這種遊戲是建立在區塊鏈上的,玩家可以透過支付一定的代幣,競猜由智慧合約生成的隨機雜湊值的末尾幾位數字。

DAPP雜湊競猜遊戲 隨著區塊鏈技術的發展,越來越多的去中心化應用程式(DAPP)開始湧現出來,其中之一就是基於

智慧合約的雜湊競猜遊戲。 如果猜中了,則可以獲得獎勵,否則代幣就會被鎖定在智慧合約中。


下面是一個簡單的DAPP雜湊競猜遊戲的程式碼示例,該程式碼基於以太坊區塊鏈和Solidity智慧合約編寫。


scssCopy codepragma solidity ^0.8.0;

 uint256 public numberOfBets;

    uint256 public maxAmountOfBets = 3;

    bytes32 public lastHash;

        address payable[] public players;

            mapping(address => uint256) public playerBets;

            mapping(address => uint256) public playerGuesses;

                mapping(address => bool) public playerExists;    

    constructor() public {

        owner = payable(msg.sender);

        minBet = 10000000000000000; // 0.01 ether

    }

    



contract HashGuessGame {    

    address payable public owner;

    uint256 public minBet;

    uint256 public totalBet;

   

    modifier onlyOwner() {

            require(msg.sender == owner);

        _;

    }

    

    function kill() public onlyOwner {

            selfdestruct(owner);

    }

    

    function guess(uint256 guessValue) public payable {

            require(msg.value >= minBet);

            require(numberOfBets < maxAmountOfBets);

                    require(playerExists[msg.sender] == false);

        playerGuesses[msg.sender] = guessValue;

        playerBets[msg.sender] = msg.value;

        players.push(payable(msg.sender));

        playerExists[msg.sender] = true;

        totalBet += msg.value;

        numberOfBets++;

    }

    

    function distributePrizes(uint256 seed) public onlyOwner {

        bytes32 winner = keccak256(abi.encodePacked(blockhash(block.number-1), seed));

        uint256 count = 0;

        for (uint256 i = 0; i < players.length; i++) {

                    address payable player = players[i];

            if (playerGuesses[player] == uint256(winner) % 100) {

                count++;

            }

        }

        if (count > 0) {

            uint256 winnerEtherAmount = totalBet / count;

            for (uint256 j = 0; j < players.length; j++) {

                            address payable player = players[j];

                if (playerGuesses[player] == uint256(winner) % 100) {

                    player.transfer(winnerEtherAmount);

                }

                delete playerBets[player];

                delete playerGuesses[player];

                delete playerExists[player];

            }

            players = new address payable[](0);

            totalBet = 0;

            numberOfBets = 0;

        }

        lastHash = winner;

    }

    

}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/70027509/viewspace-2941838/,如需轉載,請註明出處,否則將追究法律責任。

相關文章