其他分享
首页 > 其他分享> > cryptozombies第二讲

cryptozombies第二讲

作者:互联网

zombiefeeding.sol

pragma solidity ^0.4.19;
//导入其余文件
import "./zombiefactory.sol";
//合约接口,只需定义函数,编译器会从其他文件中找函数方法
contract KittyInterface {
  function getKitty(uint256 _id) external view returns (
    bool isGestating,
    bool isReady,
    uint256 cooldownIndex,
    uint256 nextActionAt,
    uint256 siringWithId,
    uint256 birthTime,
    uint256 matronId,
    uint256 sireId,
    uint256 generation,
    uint256 genes
  );
}

//合约继承
contract ZombieFeeding is ZombieFactory {

  address ckAddress = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
  //接口创建合约对象
  KittyInterface kittyContract = KittyInterface(ckAddress);

  function feedAndMultiply(uint _zombieId, uint _targetDna, string _species) public {
      //只有require成立才会跑后面的
      require(msg.sender == zombieToOwner[_zombieId]);
      //storage保存指针,memory保存副本
      Zombie storage myZombie = zombies[_zombieId];
      _targetDna = _targetDna % dnaModulus;
      uint newDna = (myZombie.dna + _targetDna) / 2;
      //字符串比较256位16进制hash值
      if (keccak256(_species) == keccak256("kitty")) {
          newDna = newDna - newDna % 100 + 99;
      }
      _createZombie("NoName", newDna);
  }

  function feedOnKitty(uint _zombieId, uint _kittyId) public {
      uint kittyDna;
      //函数有多个返回值通过这种方法赋值
      (,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
          feedAndMultiply(_zombieId, kittyDna, "kitty");
      }

}

zombiefactory.sol

pragma solidity ^0.4.19;

contract ZombieFactory {

    event NewZombie(uint zombieId, string name, uint dna);

    uint dnaDigits = 16;
    uint dnaModulus = 10 ** dnaDigits;

    struct Zombie {
        string name;
        uint dna;
    }

    Zombie[] public zombies;

    mapping (uint => address) public zombieToOwner;
    mapping (address => uint) ownerZombieCount;

    //internal:private的升级版,子类也能用函数;
    //external: public的降级版,函数定义的类的里面不能用这个函数;
    function _createZombie(string _name, uint _dna) internal {
        uint id = zombies.push(Zombie(_name, _dna)) - 1;
        zombieToOwner[id] = msg.sender;
        ownerZombieCount[msg.sender]++;
        NewZombie(id, _name, _dna);
    }

    function _generateRandomDna(string _str) private view returns (uint) {
        uint rand = uint(keccak256(_str));
        return rand % dnaModulus;
    }

    function createRandomZombie(string _name) public {
        require(ownerZombieCount[msg.sender] == 0);
        uint randDna = _generateRandomDna(_name);
        randDna = randDna - randDna % 100;
        _createZombie(_name, randDna);
    }

}

 

标签:function,dna,name,uint256,第二,cryptozombies,uint,public
来源: https://www.cnblogs.com/wen2077/p/15807307.html