A Simple Smart Contract for Non-Programmers to Read

Bryant Nielson | May 15, 2023

This smart contract allows two players to place a bet on a number between 1 and 100. One player can choose the winning number, and then both players can place their bets. If a player guesses the winning number, they win the bet and the contract will pay out the winnings. The contract also has a function to end the game and pay out to the winner.

pragma solidity ^0.6.0;
contract Bet {
    // Declare variables
    address payable public player1;
    address payable public player2;
    uint public betAmount;
    uint public winningNumber;
    bool public player1Wins;
    bool public player2Wins;
    bool public gameOver;
    // Constructor function – runs when contract is deployed
    constructor(address payable _player1, address payable _player2, uint _betAmount) public {
        player1 = _player1;
        player2 = _player2;
        betAmount = _betAmount;
    }
    // Function to place a bet
    function placeBet(uint _guess) public payable {
        require(!gameOver, “The game is over, no more bets allowed”);
        require(msg.value == betAmount, “The bet must be for the agreed upon amount”);
        require(_guess >= 1 && _guess <= 100, “The guess must be between 1 and 100”);
        if (_guess == winningNumber) {
            if (msg.sender == player1) {
                player1Wins = true;
            } else {
                player2Wins = true;
            }
            gameOver = true;
        }
    }

    // Function to choose the winning number
    function chooseWinningNumber(uint _winningNumber) public {
        require(!gameOver, “The game is over, the winning number cannot be changed”);
        require(msg.sender == player1 || msg.sender == player2, “Only player 1 or 2 can choose the winning number”);
        require(_winningNumber >= 1 && _winningNumber <= 100, “The winning number must be between 1 and 100”);
        winningNumber = _winningNumber;
    }
    // Function to end the game and pay out to the winner
    function endGame() public {
        require(gameOver, “The game is not over yet”);
        if (player1Wins) {
            player1.transfer(2 * betAmount);
        } else if (player2Wins) {
            player2.transfer(2 * betAmount);
        }
    }
}

One does not necessarily need to be a programmer to understand the construction of a Smart Contract.  In the above example can you:

Write down the sequence of steps that the Smart Contract follows.

What happens if the number is not guessed?

Can the 2 parties independently select the amount of bet?