(Image Source: Pixabay)
最近在学习写Solidity的合约,最好的学习办法就是边写边学,所以就试着写了一个剪刀石头布的合约
这个合约挺简单,就是你出石头(0),布(1),剪刀(2)并发送ETH到合约地址,如果你获胜会获得双倍奖励,如果平局就会把发送的ETH退回,输了就没收ETH
这是合约代码:
pragma solidity ^0.5.0;
contract RockPaperScissors{
//rock-0
//paper-1
//scissors-2
uint computerChoice;
event sentPrize(uint computerChoice,uint playerChoice);
function play(uint num)public payable{
computerChoice = random();
if(num-computerChoice==uint(-1)){
sendMoney(msg.value*2);
}else if(num-computerChoice==0){
sendMoney(msg.value);
}else{
//you lose
}
emit sentPrize(computerChoice,num);
}
//get random number between 0-2
function random() private view returns(uint){
return block.timestamp%3;
}
//Send prize
function sendMoney(uint amount) private{
address payable player = msg.sender;
player.transfer(amount);
}
//Get contract balance
function getBalance()public view returns(uint){
return address(this).balance;
}
}
这个只是很简单的合约,里面也有一些问题,比如:
- 随机出拳是按timestamp算的,所以很容易猜到合约下一个出拳是什么
- 合约初始没有初始金