Last active
February 7, 2022 06:16
-
-
Save danielkhoo/d78485de8120d117f88da6c18d802b92 to your computer and use it in GitHub Desktop.
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
pragma solidity >=0.8.0 <0.9.0; | |
/** | |
* @notice Function for players to commit their choice | |
* @dev players can commit multiple times to change their choice until the other player commits | |
* @param choice - "rock", "paper" or "scissors" | |
* @param salt - a player chosen secret string used to "salt" the commit hash | |
*/ | |
function commit(string memory choice, string memory salt) | |
public | |
validGameState(activeGame[msg.sender], GameState.CommitPhase) | |
{ | |
// Get the game hash from active game mapping | |
address gameHash = activeGame[msg.sender]; | |
bytes32 unsaltedChoiceHash = keccak256(abi.encodePacked(choice)); | |
// Check choice is valid i.e. "rock", "paper", "scissors" | |
require( | |
unsaltedChoiceHash == rockHash || | |
unsaltedChoiceHash == paperHash || | |
unsaltedChoiceHash == scissorsHash, | |
"Invalid choice. Please select 'rock', 'paper' or 'scissors'" | |
); | |
// Generate commit hash with choice + user chosen salt | |
bytes32 commitHash = keccak256(abi.encodePacked(choice, salt)); | |
bool isPlayer1 = games[gameHash].player1 == msg.sender; | |
if (isPlayer1) { | |
games[gameHash].commit1 = commitHash; | |
} else { | |
games[gameHash].commit2 = commitHash; | |
} | |
// If both player have committed, set game state to reveal phase | |
if (games[gameHash].commit1 != 0 && games[gameHash].commit2 != 0) { | |
games[gameHash].gameState = GameState.RevealPhase; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment