欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ethereum Solidity Dapp Game Contract

程序员文章站 2022-06-06 10:22:21
...
pragma solidity >=0.4.17 <0.6.0;

import "./SafeMath.sol";
import "./Strings.sol";

contract Game {
    using Strings for *;
    using SafeMath for *;
    address public manager;
    // address[] public players;
    
    struct GameInstructor {
        string number;
        uint256 totalSupply;
    }

    uint256 _totalSupply = 0;
    uint _GamePeriod = 1;
    uint _players = 0;

    mapping(uint => GameInstructor) GameInstructors;

    event log(string, uint); //变动时调用事件

    function Game() public {
        manager = msg.sender;
    }

    function enter(uint256 _value) public onlyManagerCanCall {
        // require(msg.value >= .01 ether);
        _totalSupply = _totalSupply.add(_value);
        _players++;
    }

    function fetchSeed() public view returns (uint) {
        // 
        uint value = uint(sha3(block.difficulty, now, _players));

        log("seed number", value);

        return value;
    }

    function convert() view public returns (string){
        uint _i = fetchSeed();
        uint j = _i;
        uint len;
        while (j != 0) {
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint k = len - 1;
        while (_i != 0) {
            bstr[k--] = byte(uint8(48 + _i % 10));
            _i /= 10;
        }

        return string(bstr);
    }

    function random() public view returns (string) {
        string memory x = convert();
        return x._substring(4, 4);
    }

    // function modifier, reduce code we need to write
    modifier onlyManagerCanCall() {
        // only manage can pick winner
        require(msg.sender == manager);
        _;
        // all code in your function will replace the "_"
    }

    function pickWinner() public onlyManagerCanCall {
        string memory GameNumber = random();
        // this.balance has all the ether in current smart contract
        // players[index].transfer(address(this).balance); 
        // inital dynamic array whose length is 0;
        // players = new address[](0);
        addGameInstructor(_GamePeriod, _totalSupply, GameNumber);
 
        _totalSupply = 0;
        _players = 0;
        _GamePeriod++;
    }

    function addGameInstructor(uint GamePeriodKey, uint256 periodTotal, string GameNumber) public onlyManagerCanCall {
        var GameInstructor = GameInstructors[GamePeriodKey];
        GameInstructor.number = GameNumber;
        GameInstructor.totalSupply = periodTotal;
    }

    function getGame(uint GamePeriodKey) view public returns (string, uint256){
        return (GameInstructors[GamePeriodKey].number, GameInstructors[GamePeriodKey].totalSupply);
    }

    function getCurrentPlayers() public view returns (uint) {
        return _players;
    }

    function getCurrentTotalSupply() public view returns (uint) {
        return _totalSupply;
    }

}