How Sprites Work_ipynb_2_
How did I make a rock-paper-scissors game?
It’s really simple actually, first I made a user input box where you can input rock, paper, or scissors, then I have the computer pick a random number when the player presses play, 1-3 with each number being assigned to rock, paper, or scissors. then the output from the computer is taken, and that determins which message runs, for instance if the computer’s random number is 2 (paper) and the player chooses scissors the message “You won!” but if the player chose rock then the message “You Lose!” shows, if the computer and the player choose the same thing “It’s a tie!” shows. you can check the code commnets for details about individual sections
%%html
<div>
<label for="choice">Enter Choice (Rock, Paper, Scissors):</label>
<input type="text" id="choice" name="choice" value="Rock">
<button onclick="playGame()">Play</button>
</div>
<div id="result"></div>
<script>
function playGame() {
// Get the user's choice
var userChoice = document.getElementById("choice").value.trim().toLowerCase();
// Map the user input to 1, 2, or 3 (1=Rock, 2=Paper, 3=Scissors)
var choices = ["rock", "paper", "scissors"];
// Ensure the input is valid
if (!choices.includes(userChoice)) {
document.getElementById("result").innerHTML = "Invalid choice! Please enter Rock, Paper, or Scissors.";
return;
}
// Map user choice to a number (1=Rock, 2=Paper, 3=Scissors)
var userChoiceNumber = choices.indexOf(userChoice) + 1;
// Computer's random choice (1=Rock, 2=Paper, 3=Scissors)
var computerChoiceNumber = Math.floor(Math.random() * 3) + 1;
// Map numbers back to choice names
var computerChoice = choices[computerChoiceNumber - 1];
// Determine the result
var result;
if (userChoiceNumber === computerChoiceNumber) {
result = "It's a tie!";
} else if ((userChoiceNumber === 1 && computerChoiceNumber === 3) || // Rock beats Scissors
(userChoiceNumber === 2 && computerChoiceNumber === 1) || // Paper beats Rock
(userChoiceNumber === 3 && computerChoiceNumber === 2)) { // Scissors beats Paper
result = "You win!";
} else {
result = "You lose!";
}
// Display the result
document.getElementById("result").innerHTML = `
<strong>Your choice:</strong> ${userChoice.charAt(0).toUpperCase() + userChoice.slice(1)} <br>
<strong>Computer's choice:</strong> ${computerChoice.charAt(0).toUpperCase() + computerChoice.slice(1)} <br>
<strong>Result:</strong> ${result}
`;
}
</script>