# 区块链上编程：DApp 开发实战——来写个竞猜游戏吧！

#### 合约编写

``````pragma solidity ^0.4.0;

``````contract Lottery {
uint public betMoney = 10 finney;
}

``````contract Lottery {
...
function generateRandomNumber() private view returns(uint[]) {
uint[] memory dices = new uint[](3);
for (uint i = 0; i < 3; i++) {
dices[i] = uint(keccak256(abi.encodePacked(block.difficulty, now, i))) % 6 + 1;
}
return dices;
}
...
}

``````contract Lottery {
...
function getBankBalance() public view returns(uint) {
}
...
}

``````contract Lottery {
...
function bet() public payable {
uint amount = msg.value;
require(amount >= betMoney, 'bet money not less than 10 finney');
require(address(this).balance >= amount * 20, 'contract money not enough to pay reward');

uint[] memory dices = generateRandomNumber();
require(dices.length == 3, 'dices illegal');

bool isReward = false;
uint reward = 0;

if ((dices[0] == dices[1]) && (dices[1] == dices[2]) && (dices[0] == 6)) {
isReward = true;
} else if ((dices[0] == dices[1]) && (dices[1] == dices[2]) && (dices[0] != 6)) {
isReward = true;
reward = amount * 5;
} else if ((dices[0] == dices[1]) || (dices[0] == dices[2]) || (dices[1] == dices[2])) {
isReward = true;
reward = amount * 2;
}

if (isReward) {
}
}
...

``````contract Lottery {
...
event BetList(
uint amount,
bool isReward,
uint reward,
uint[] dices
);

function bet() public payable {
...
emit BetList(addr, amount, isReward, reward, dices);
}
...

#### 与合约进行交互

``````import Web3 from 'web3';

if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider(NODE_NRL));
}

``````this.contract = new web3.eth.Contract(
CONTRACT_ABI,
);

``````userBet = async () => {
try {
await this.contract.methods
.bet(
...
)
.send({
from: ACCOUNT,
value: MONEY,
});
} catch (error) {
...
}
}

``````queryEvent = async () => {
const event = await this.contract.getPastEvents(
EVENT_NAME,
{
filter: {},
fromBlock: 0,
toBlock: 'latest',
}
)
}

#### 功能拓展

``````contract Lottery {
...

modifier onlyOwner() {
require(owner == msg.sender);
_;
}

constructor() public {
owner = msg.sender;
}
...
}

``````contract Lottery {
...
function setBetMoney(uint _betMoney) public onlyOwner {
betMoney = _betMoney;
}

function deposit() public payable onlyOwner {}
...
}

(掘金社区链接点此)