Skip to content

Instantly share code, notes, and snippets.

@idimitrov07
Created March 4, 2018 19:29
Show Gist options
  • Select an option

  • Save idimitrov07/4fde39d3cf9fff34ed5917441d484a77 to your computer and use it in GitHub Desktop.

Select an option

Save idimitrov07/4fde39d3cf9fff34ed5917441d484a77 to your computer and use it in GitHub Desktop.
Simple guessing game on Solidity
pragma solidity ^0.4.18;
// Problem - generate a random rumber
contract GuessingGame {
uint nonce = 0;
event UserWon(address user, uint numberGenerated);
event UserLost(address user, uint numberGenerated);
// start with an empty payable function so users can fund the game with ETH
function() public payable {
}
// get balance of contract
function getBalance() public constant returns(uint) {
return this.balance;
}
function playGame() public payable {
// RULE 1: Users needs to pay 0.01 ETH to play
// use code bellow if using JavaScript VM, comment assert
// if(msg.value != 0.01 ether) {
// throw;
// }
// use if using Injected Web3
assert(msg.value == 0.01 ether);
// generate a random number by getting the block No
uint randomNumber = uint(keccak256(block.blockhash(block.number), nonce)) % 100;
nonce++;
// RULE 2: User gets 0.02 back if number is even
if(randomNumber % 2 == 0) {
// even, send the user 0.02 ether
msg.sender.transfer(msg.value * 2);
UserWon(msg.sender, randomNumber);
} else {
// odd
UserLost(msg.sender, randomNumber);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment