Skip to content

Instantly share code, notes, and snippets.

@John-Doggett
Created May 8, 2023 21:17
Show Gist options
  • Save John-Doggett/5b5b56ddbb95200db1e5467e2d333865 to your computer and use it in GitHub Desktop.
Save John-Doggett/5b5b56ddbb95200db1e5467e2d333865 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.19+commit.7dd6d404.js&optimize=false&runs=200&gist=
pragma solidity ^0.8.19;
contract LuckyNumberMachine {
address owner;
uint256 contractBalance;
constructor() {
owner = msg.sender;
}
function generateRandomNumber() public view returns (uint) {
uint randomNumber = block.prevrandao; //implemented in vm >= 0.8.18
randomNumber = randomNumber % 6 + 1;
return randomNumber;
}
function playGame(uint256 chosenNumber) public payable {
require(msg.value == 0.1 ether, "Please send exactly 0.1 ether to play the game.");
require(chosenNumber >= 1 && chosenNumber <= 6, "Please choose a number between 1 and 6.");
require(contractBalance >= 0.2 ether, "Not enough balance to play game.");
uint randomNumber = generateRandomNumber();
if (chosenNumber == randomNumber) {
payable(msg.sender).transfer(0.2 ether);
contractBalance -= msg.value;
} else {
contractBalance += msg.value;
}
}
function getContractBalance() public view returns (uint256) {
require(msg.sender == owner, "Only the contract owner can view the balance.");
return contractBalance;
}
function deposit() public payable {
require(msg.sender == owner, "Only the contract owner can deposit ether.");
contractBalance += msg.value;
}
function withdraw(uint256 amount) public {
require(msg.sender == owner, "Only the contract owner can withdraw ether.");
require(amount <= contractBalance, "Withdraw amount exceeds contract balance.");
payable(owner).transfer(amount);
contractBalance -= amount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment