Created
August 21, 2021 12:50
-
-
Save prtk418/c8addf03fda5046d6609923df9abb525 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.7+commit.e28d00a7.js&optimize=false&runs=200&gist=
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: GPL-3.0 | |
pragma solidity ^0.8; | |
contract RockPaperScissors { | |
uint public enrollmentAmount; | |
address owner; | |
address[] public players; | |
mapping(address => bool) playerPlayed; | |
mapping(address => bytes32) public choices; | |
bytes32 ROCK = keccak256(bytes("Rock")); | |
bytes32 PAPER = keccak256(bytes("Paper")); | |
bytes32 SCISSOR = keccak256(bytes("Scissor")); | |
// pass enrollment amount in wei | |
constructor() { | |
owner = msg.sender; | |
} | |
receive() external payable{} | |
function initialiseGame(uint256 enrollmentAmount, address player1, address player2) public { | |
require(msg.sender == owner); | |
require(player1 != player2); | |
enrollmentAmount = enrollmentAmount; | |
players.push(player1); | |
players.push(player2); | |
playerPlayed[player1] = false; | |
playerPlayed[player2] = false; | |
} | |
function playGame(string memory choice) public payable { | |
require(msg.value == enrollmentAmount); | |
require(msg.sender == players[0] || msg.sender == players[1]); | |
choices[msg.sender] = keccak256(bytes(choice)); | |
playerPlayed[msg.sender] = true; | |
} | |
function _resetGame() internal { | |
delete choices[players[0]]; | |
delete choices[players[1]]; | |
delete playerPlayed[players[0]]; | |
delete playerPlayed[players[0]]; | |
delete players; | |
} | |
function endGameAndDistributeReward() public { | |
require(msg.sender == owner); | |
require(playerPlayed[players[0]] && playerPlayed[players[1]]); | |
address winner; | |
if (choices[players[0]] == ROCK && choices[players[1]] == SCISSOR) { | |
winner = players[0]; | |
} else if (choices[players[0]] == ROCK && choices[players[1]] == PAPER) { | |
winner = players[1]; | |
} else if (choices[players[0]] == PAPER && choices[players[1]] == ROCK) { | |
winner = players[0]; | |
} else if (choices[players[0]] == PAPER && choices[players[1]] == SCISSOR) { | |
winner = players[1]; | |
} else if (choices[players[0]] == SCISSOR && choices[players[1]] == PAPER) { | |
winner = players[0]; | |
} else if (choices[players[0]] == SCISSOR && choices[players[1]] == ROCK) { | |
winner = players[1]; | |
} | |
_resetGame(); | |
payable(winner).transfer(address(this).balance); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment