【区块链】从零开始写一个区块链游戏--水果机

机器环境

  • win10
  • nodev8.9.4
  • npm install -g truffle
  • npm install -g ganache-cli

Github地址

规则

  • 初始化账号有10个ETH
  • 每次游戏输了会减1个ETH,赢了则加2个ETH
  • 注:有两个相同则不扣不增

效果

初始化项目

  • mkdir eth-slot-machine
  • cd eth-slot-machine
  • truffle init

编写游戏合约

  • contracts/slotMachine.sol
pragma solidity ^0.4.19;

contract SlotMachine {
    // 储存用户的余额
    mapping (address => uint) public balanceOf;

    // 获取用户的余额
    function getBalanceOf(address _address) public view returns (uint) {
        return balanceOf[_address];
    }

    // 游戏开始赠送10个以太坊
    function admission(address _address) public {
        balanceOf[_address] = 10;
    }

    // 判断游戏结果,win or lose, 每次游戏-1,赢得游戏则+2,平则不减不加
    function checkGameResult(string _result) public {
        require(keccak256(_result) == keccak256("win") || keccak256(_result) == keccak256("lose"));
        if (keccak256(_result) == keccak256("win")) {
            balanceOf[msg.sender] += 2;
        } else {
            balanceOf[msg.sender]--;
        }
    }
}

编写迁移脚本

  • migrations/2_deploy_contract.js
var SlotMachine = artifacts.require("./slotMachine.sol");

module.exports = function(deployer) {
  deployer.deploy(SlotMachine);
};

配置truffle.js文件

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  networks: {  
    development: {  
      host: "localhost",  
      port: 8545,  
      network_id: "*"  
    }  
  }  
};

启动ganache-cli

  • ganache-cli
  • 记录账号信息

迁移合约

  • truffle migrate
  • 记录下合约地址

编辑app/index.html

  • 修改其中的abi
  • 修改其中的合约地址

打开index.html

  • 在浏览器中访问index.html可以看到效果

猜你喜欢

转载自blog.csdn.net/ns2250225/article/details/80484636