From ca847a5e4e30f4bd22ab111266fd60bf5a4f9db2 Mon Sep 17 00:00:00 2001 From: nodemixaholic Date: Tue, 5 Mar 2024 16:58:34 +0000 Subject: [PATCH] Add 'rps.js' --- rps.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 rps.js diff --git a/rps.js b/rps.js new file mode 100644 index 0000000..089bfe7 --- /dev/null +++ b/rps.js @@ -0,0 +1,44 @@ +// Function to play rock paper scissors +function playRPS() { + // Generate two random numbers between 1 and 3 (inclusive) + const player1 = Math.floor(Math.random() * 3) + 1; + const player2 = Math.floor(Math.random() * 3) + 1; + + // Determine the choices based on the closest distance + let player1Choice, player2Choice; + if (Math.abs(player1 - 1) < Math.abs(player1 - 2) && Math.abs(player1 - 1) < Math.abs(player1 - 3)) { + player1Choice = "Rock"; + } else if (Math.abs(player1 - 2) < Math.abs(player1 - 1) && Math.abs(player1 - 2) < Math.abs(player1 - 3)) { + player1Choice = "Paper"; + } else { + player1Choice = "Scissors"; + } + + if (Math.abs(player2 - 1) < Math.abs(player2 - 2) && Math.abs(player2 - 1) < Math.abs(player2 - 3)) { + player2Choice = "Rock"; + } else if (Math.abs(player2 - 2) < Math.abs(player2 - 1) && Math.abs(player2 - 2) < Math.abs(player2 - 3)) { + player2Choice = "Paper"; + } else { + player2Choice = "Scissors"; + } + + // Determine the winner based on game logic + let winner; + if (player1Choice === player2Choice) { + winner = "Tie"; + } else if (player1Choice === "Rock") { + winner = player2Choice === "Scissors" ? "Player 1" : "Player 2"; + } else if (player1Choice === "Paper") { + winner = player2Choice === "Rock" ? "Player 1" : "Player 2"; + } else { // player1Choice === "Scissors" + winner = player2Choice === "Paper" ? "Player 1" : "Player 2"; + } + + // Print the results + console.log(`Player 1: ${player1Choice}`); + console.log(`Player 2: ${player2Choice}`); + console.log(`Winner: ${winner}`); +} + +// Play the game twice +playRPS();