Skip to content

Instantly share code, notes, and snippets.

@michaelcpuckett
Created April 16, 2024 20:28
Show Gist options
  • Save michaelcpuckett/96c421ab731f8b60b48c00f39833f13f to your computer and use it in GitHub Desktop.
Save michaelcpuckett/96c421ab731f8b60b48c00f39833f13f to your computer and use it in GitHub Desktop.
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissors</button>
<output> </output>
<script>
const buttonElements = Array.from(window.document.querySelectorAll("button"));
const outputElement = window.document.querySelector("output");
function rps(playerChoice) {
const winConditions = {
rock: "scissors",
paper: "rock",
scissors: "paper",
};
const computerChoice =
Object.keys(winConditions)[Math.floor(Math.random() * 3)];
if (playerChoice === computerChoice) {
return `Computer picked ${computerChoice}. It's a draw!`;
}
if (winConditions[playerChoice] === computerChoice) {
return `Computer picked ${computerChoice}. You win!`;
}
return `Computer picked ${computerChoice}. Computer wins!`;
}
buttonElements.map((buttonElement) => {
buttonElement.addEventListener("click", (event) => {
const playerChoice = event.target.id;
const result = rps(playerChoice);
outputElement.textContent = result;
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment