一、前言
看了一些区块链的教程,论文,在网上刚刚找到了一个项目实战,CryptoZombies。
如果你想了解更多有关于机器学习、深度学习、区块链、计算机视觉等相关技术的内容,想与更多大佬一起沟通,那就扫描下方二维码加入我们吧!
二、Require
用户可以创建僵尸,但是不能无限制创建,所以需要作出限定:每个用户只能持续调用一次。我们使用require来做限制,即当不满足某些条件时,我们可以抛出异常,并停止运行。
下面是使用使用示例,比较 _name 是否等于 "Vitalik",如果不成立,抛出异常并终止程序。
注意:
Solidity 并不支持原生的字符串比较, 我们只能通过比较两字符串的 keccak256 哈希值来进行判断。
function sayHiToVitalik(string memory _name) public returns (string memory) {
// Compares if _name equals "Vitalik". Throws an error and exits if not true.
// (Side note: Solidity doesn't have native string comparison, so we
// compare their keccak256 hashes to see if the strings are equal)
require(keccak256(abi.encodePacked(_name)) == keccak256(abi.encodePacked("Vitalik")));
// If it's true, proceed with the function:
return "Hi!";
}
如果你这样调用函数
sayHiToVitalik(“Vitalik”)
它会返回“Hi!”。而如果调用的时候使用了其他参数,它则会抛出错误并停止执行。
因此,在调用一个函数之前,用 require
验证前置条件是非常有必要的。
三、实战
1、要求
在我们的僵尸游戏中,我们不希望用户通过反复调用 createRandomZombie
来給他们的军队创建无限多个僵尸 —— 这将使得游戏非常无聊。我们使用了 require
来确保这个函数只有在每个用户第一次调用它的时候执行,用以创建初始僵尸。
在 createRandomZombie
的前面放置 require
语句。 使得函数先检查 ownerZombieCount [msg.sender]
的值为 0
,不然就抛出一个错误。
注意:
在 Solidity 中,关键词放置的顺序并不重要
1.虽然参数的两个位置是等效的。 但是,由于我们的答案检查器比较呆板,它只能认定其中一个为正确答案
2.于是在这里,我们就约定把
ownerZombieCount [msg.sender]
放前面吧
2、代码
pragma solidity >=0.5.0 <0.6.0;
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;
function _createZombie(string memory _name, uint _dna) private {
uint id = zombies.push(Zombie(_name, _dna)) - 1;
zombieToOwner[id] = msg.sender;
ownerZombieCount[msg.sender]++;
emit NewZombie(id, _name, _dna);
}
function _generateRandomDna(string memory _str) private view returns (uint) {
uint rand = uint(keccak256(abi.encodePacked(_str)));
return rand % dnaModulus;
}
function createRandomZombie(string memory _name) public {
// start here
require(ownerZombieCount[msg.sender] == 0);
uint randDna = _generateRandomDna(_name);
_createZombie(_name, randDna);
}
}