Created
January 22, 2023 20:18
-
-
Save pxng0lin/7b92104bc3b92932f4498d9bf39362ad to your computer and use it in GitHub Desktop.
This file contains hidden or 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: MIT | |
pragma solidity ^0.8.0; | |
contract RockPaperScissors { | |
// game state | |
address public owner; | |
address public player; | |
string private pMove; | |
string private cMove; | |
string public gameResult; | |
bool private gameStatus; | |
// events | |
event GameStarted(address player); | |
event MoveMade(bytes32 playerMove); | |
event GameEnded(string gameResult); | |
// variables, mappings, arrays | |
string[] private choices = ["rock", "paper", "scissors"]; | |
mapping(address => uint) public balances; | |
// constructor | |
constructor() { | |
owner = msg.sender; | |
} | |
// functions | |
function deposit() public payable { | |
require(msg.value > 0, "Deposit amount must be greater than 0"); | |
// require(msg.sender == player, "Only the player can deposit funds."); | |
balances[msg.sender] += msg.value; | |
} | |
function startGame() public { | |
// require(msg.sender == owner, "Only the owner can start a game."); | |
require(balances[msg.sender] > 1 ether, "Not enough balance to start the game."); | |
balances[msg.sender]-= 1 ether; | |
player = msg.sender; | |
emit GameStarted(player); | |
} | |
function makeMove(string memory _pMove) public { | |
require(msg.sender == player, "Only the player can make a move."); | |
// player move | |
bytes memory _playerMove = bytes(_pMove); | |
bytes32 playerMove; | |
assembly { | |
playerMove := mload(add(_playerMove, 32)) | |
} | |
emit MoveMade(playerMove); | |
// computer move | |
cMove = choices[uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty))) % 3]; | |
bytes memory _computerMove = bytes(cMove); | |
bytes32 computerMove; | |
assembly { | |
computerMove := mload(add(_computerMove, 32)) | |
} | |
emit MoveMade(computerMove); | |
if (playerMove == computerMove) { | |
gameResult = "Tie"; | |
} else if ( | |
(playerMove == "rock" && computerMove == "scissors") || | |
(playerMove == "scissors" && computerMove == "paper") || | |
(playerMove == "paper" && computerMove == "rock") | |
) { | |
gameResult = "You Win!"; | |
} else { | |
gameResult = "You lose!"; | |
} | |
emit GameEnded(gameResult); | |
} | |
function getChoices() public view returns(string[] memory) { | |
return choices; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment