Rock Paper Scissor

Easy Rock Paper Scissor’s game with JavaScript

(Link for you to try at the bottom.) Are you ready to test your luck against the computer in a game of rock, paper, scissors? In this article, we’ll be discussing a code that allows you to play five rounds of this classic game, and see who comes out on top. But this isn’t just any ordinary game of rock, paper, scissors. This code has been designed to add a little bit of excitement and competition to the mix. Are you ready to see if you have what it takes to beat the computer? Let’s find out!

How the code works:

The code starts off by defining an array called “play”, which contains the three options that you can choose from: “rock”, “paper”, and “scissors”. It also defines three variables: “wins”, “losses”, and “draws”, which will be used to keep track of the outcome of each round.

let play = [“rock”, “paper”, “scissors”]; let wins = 0; let losses = 0; let draws = 0; 

Next, the code displays an alert message introducing the game and explaining the rules. It then enters a loop that will run for a total of five rounds.

let introduction = ("Get ready – five rounds of rock, paper, and scissors are about to start! (User's consent not required.)"); alert(introduction) let i = 0; while (i < 5) 

During each round, the code will prompt you to enter your choice. It will then convert your answer to lowercase, so that it doesn’t matter whether you type in “rock”, “ROCK”, or “RoCk”.

let hAnswer = prompt("How will it be, eh? You ought to choose!"); hAnswer = hAnswer.toLowerCase(); 

But here’s where things get interesting. The code will then generate a random answer for the computer, using the “play” array and the “Math.random()” function. It will display an alert message showing the computer’s choice, and it will also keep you on the edge of your seat by adding a little bit of suspense with some dramatic music.

let cAnswer = play[Math.floor(Math.random() * play.length)]; if (hAnswer == "rock" || hAnswer == "paper" || hAnswer == "scissors")

Finally, the code will determine the outcome of the round based on the rules of rock, paper, scissors. If it’s a draw, the “draws” counter will be incremented. If you win, the “wins” counter will be incremented. And if you lose, the “losses” counter will be incremented.

//Response for draw & counter if (hAnswer === cAnswer) < draws++ alert(`It's a draw. We're keeping tabs. ($)`) > //Response for win & counter else if ( (hAnswer == "rock" && cAnswer == "scissors") || (hAnswer == "paper" && cAnswer == "rock") || (hAnswer == "scissors" && cAnswer == "paper") ) < wins++ alert(`You have won $times, luck lol.`) > //Response for loss & counter else < losses++ alert(`You have lost $times ahaha!`) > i++ //counter for

At the end of the loop, the code will display an alert message showing the final results, including the number of wins, losses, and draws. It will also add a little bit of flair by adding some celebratory music if you win, or some commiserating music if you lose.

alert(`You have won $ times, draw $ times and lost $ times.`) 

Conclusion:

So there you have it — a code that allows you to play rock, paper, scissors against your computer in a fun and exciting way. Whether you’re a seasoned pro or a beginner, this code is a great way to test your luck and see if you have what it takes to beat the computer. So why wait? Give it a try and see if you have what it takes to come out on top! 👀 Try it here

Источник

Rock Paper and Scissors in JavaScript

Rock Paper and Scissors in JavaScript

Every developer starts with the Hello world somewhere in their life. Rock paper scissor is one popular game developers builds while learning any programming language. But writing multiple cases becomes a headache for developers. So in this article, we will learn the logic behind the rock, paper, and scissors game.

Rock, Paper, and Scissors in JavaScript

  1. A player who chooses to play the rock will strike another player who chose the scissors because the stone crushes the scissors or sometimes chamfered scissors.
  2. A player who chooses to play rock loses to another who played the paper because the paper covers the rock.
  3. A player who decides to play paper will lose to a player of scissors because scissors cut paper.

So rules are cleared; now, let’s write the logic for the game. We have created one object with key as individual choice and values as the second choice. For example, if user input is rock and the computer’s choice is also rock, then it’s a draw.

let choicesObject =   'rock' :   'rock' : 'draw',  'scissor' : 'win',  'paper' : 'lose'  >,  'scissor' :   'rock' : 'lose',  'scissor' : 'draw',  'paper' : 'win'  >,  'paper' :   'rock' : 'win',  'scissor' : 'lose',  'paper' : 'draw'  > > 

Now we can use the above object as a global rule and predict the result of a game using function.

function checker(input)  var choices = ["rock", "paper", "scissor"];  var num = Math.floor(Math.random()*3);   let computerChoice = choices[num];  let result   switch(choicesObject[input][computerChoice])  case 'win':  result = "YOU WIN";  break;  case 'lose':  result = "YOU LOSE";  break;  default:  result = "DRAW";  break;  >  console.log(result);  document.getElementById('result').textContent = result; > 

In the above function, we take user choice as input and compare the user input with computer-generated choice using a switch case. If none of the conditions is matched, it’s considered to be drawn. Now let’s take the user’s choice and print the result.

button onClick="checker('rock')">Rockbutton> button onClick="checker('paper')">Paperbutton> button onClick="checker('scissor')">Scissorbutton> p id="result">  p> 

When you run the above code, it will print something like this. The result may vary based on the computer’s choice.

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

Источник

How to make a Rock Paper Scissors Game in JavaScript?

How to make a Rock Paper Scissors Game in JavaScript?

In this article, we will guide you through the process of building the game logic and user interface and provide you with all the code you need to get started.

So bear with us as we will show you how to code rock paper scissors in JavaScript . Let’s get started!

What is Rock Paper Scissors?

Whether as a childhood pastime with friends or a means to settle disputes in the workplace, this timeless game always brings a sense of excitement and friendly rivalry.

Rock paper scissors in JavaScript

Get ready for a simple and fun game of rock-paper-scissors JavaScript codewars ! With just three options – rock, paper, or scissors – two players face off to see who wins.

In this JavaScript-based game, you’ll be playing against the computer. You’ll make your choice while the computer randomly selects its own.

The final result will be displayed on the screen, along with a handy restart button. Plus, this game is designed to be responsive, so you can enjoy it on any device.

How to code a rock paper scissors game in JavaScript?

Here, we will show you how to make a rock paper scissors game in js or JavaScript .

Here’s the code for HTML

         
Player 1

0

Player 2

0

Here’s the code for the CSS

/* style.css */ /* universal selector - Applies to whole document */ * < padding: 0; margin: 0; box-sizing: border-box; background: #f5f4f5; color: hwb(0 3% 97%); >/* To center everything in game */ .game < display: flex; flex-direction: column; height: 100vh; width: 100vw; justify-content: center; align-items: center; >/* Title of the game */ .title < position: absolute; top: 0; font-size: 4rem; z-index: 2; >/* Score Board */ .score < display: flex; width: 30vw; justify-content: space-evenly; position: absolute; top: 70px; z-index: 1; >/* Score */ .p-count,.c-count < text-align: center; font-size: 1.5rem; margin-top: 1rem; >/* displaying three buttons in one line */ .options < display: flex; width: 50vw; justify-content: space-evenly; margin-top: 2rem; >/* Styling on all three buttons */ .rock, .paper, .scissor < padding: 0.8rem; width: 100px; border-radius: 10px; background: rgb(216, 128, 172); outline: none; border-color: rgb(248, 86, 113); border: none; cursor: pointer; >.move < font-size: 2rem; font-weight: bold; >/* Reload button style */ .reload < display: none; margin-top: 2rem; padding: 1rem; background: rgb(216, 128, 172); outline: none; border: none; border-radius: 10px; cursor: pointer; >.result < margin-top: 20px; font-size: 1.2rem; >/* Responsive Design */ @media screen and (max-width: 612px) < .title< text-align: center; >.score < position: absolute; top: 200px; width: 100vw; >.options 

Here’s the code for script.js

// Complete logic of game inside this function const game = () => < let playerScore = 0; let computerScore = 0; let moves = 0; // Function to const playGame = () => < const rockBtn = document.querySelector('.rock'); const paperBtn = document.querySelector('.paper'); const scissorBtn = document.querySelector('.scissor'); const playerOptions = [rockBtn,paperBtn,scissorBtn]; const computerOptions = ['rock','paper','scissors'] // Function to start playing game playerOptions.forEach(option =>< option.addEventListener('click',function()< const movesLeft = document.querySelector('.movesleft'); moves++; movesLeft.innerText = `Moves Left: $`; const choiceNumber = Math.floor(Math.random()*3); const computerChoice = computerOptions[choiceNumber]; // Function to check who wins winner(this.innerText,computerChoice) // Calling gameOver function after 10 moves if(moves == 5) < gameOver(playerOptions,movesLeft); >>) >) > // Function to decide winner const winner = (player,computer) => < const result = document.querySelector('.result'); const playerScoreBoard = document.querySelector('.p-count'); const computerScoreBoard = document.querySelector('.c-count'); player = player.toLowerCase(); computer = computer.toLowerCase(); if(player === computer)< result.textContent = 'Tie' >else if(player == 'rock')< if(computer == 'paper')< result.textContent = 'Player 2 Won'; computerScore++; computerScoreBoard.textContent = computerScore; >else < result.textContent = 'Player 1 Won' playerScore++; playerScoreBoard.textContent = playerScore; >> else if(player == 'scissors')< if(computer == 'rock')< result.textContent = 'Player 2 Won'; computerScore++; computerScoreBoard.textContent = computerScore; >else < result.textContent = 'Player 1 Won'; playerScore++; playerScoreBoard.textContent = playerScore; >> else if(player == 'paper')< if(computer == 'scissors')< result.textContent = 'Player 2 Won'; computerScore++; computerScoreBoard.textContent = computerScore; >else < result.textContent = 'Player 1 Won'; playerScore++; playerScoreBoard.textContent = playerScore; >> > // Function to run when game is over const gameOver = (playerOptions,movesLeft) => < const chooseMove = document.querySelector('.move'); const result = document.querySelector('.result'); const reloadBtn = document.querySelector('.reload'); playerOptions.forEach(option =>< option.style.display = 'none'; >) chooseMove.innerText = 'Game Over!!' movesLeft.style.display = 'none'; if(playerScore > computerScore) < result.style.fontSize = '2rem'; result.innerText = 'You Won The Game' result.style.color = '#308D46'; >else if(playerScore < computerScore)< result.style.fontSize = '2rem'; result.innerText = 'You Lost The Game'; result.style.color = 'red'; >else < result.style.fontSize = '2rem'; result.innerText = 'Tie'; result.style.color = 'grey' >reloadBtn.innerText = 'Restart'; reloadBtn.style.display = 'flex' reloadBtn.addEventListener('click',() => < window.location.reload(); >) > // Calling playGame function inside game playGame(); > // Calling the game function game(); 

Different way on how to make a rock paper scissors game in javascript

Rock paper scissors is a game played by two people using their hands.

Each player makes one of three shapes: rock (a closed fist), paper (an open hand), or scissors (a fist with the index and middle fingers extended).

The outcome depends on these rules:

To create a Rock Paper Scissors game in JavaScript , we need to know how to get user input, generate random choices for the computer, and compare the choices to determine the winner. Let’s go through the process step by step.

1. Set up the project

First, you’ll need to have Node.js installed on your computer. Create a new directory for your project and navigate to it in the command line.

Then, create a new file for your code for instance (game.js).

2. Get user input

In order to begin our JavaScript implementation, we must obtain the user’s selection.

We can accomplish this by utilizing the prompt function, you can use the readline module that comes with Node.js. At the top of your game.js file, add the following code to create a readline interface:

const readline = require('readline').createInterface(< input: process.stdin, output: process.stdout >); 

3. Define the game logic

You’ll need to define the logic for the game. This includes defining the possible choices (rock, paper, and scissors), a function to randomly choose the computer’s move, and a function to determine the winner of the game based on the rules of rock-paper-scissors.

const choices = ['rock', 'paper', 'scissors']; const getComputerChoice = () => < const index = Math.floor(Math.random() * 3); return choices[index]; >const determineWinner = (playerChoice, computerChoice) => < if (playerChoice === computerChoice) < return 'It\'s a tie!'; >else if ( (playerChoice === 'rock' && computerChoice === 'scissors') || (playerChoice === 'paper' && computerChoice === 'rock') || (playerChoice === 'scissors' && computerChoice === 'paper') ) < return 'You win!'; >else < return 'The computer wins!'; >> 

4. Use the readline interface to get the player’s choice

After that you have defined the game logic, you can use the readline interface to get the player’s choice and play the game. Here’s an example of how you could do this:

const playGame = () => < readline.question('Choose rock, paper, or scissors: ', playerChoice => < playerChoice = playerChoice.toLowerCase(); if (!choices.includes(playerChoice)) < console.log('Invalid choice'); readline.close(); return; >const computerChoice = getComputerChoice(); console.log(`You chose $`); console.log(`The computer chose $`); console.log(determineWinner(playerChoice, computerChoice)); readline.close(); >); > playGame(); 

In this code, we ask the user for their choice using the question method from the readline interface.

Then, we use the getComputerChoice and determineWinner functions to play the game and show the result.

5. Play the game

To run and play your game, save your code to the game.js file and run it from the command line using the node command for example (node game.js).

You should see a prompt asking you to choose rock, paper, or scissors. After making your choice, you’ll see the result of the game.

Here’s the complete code:

const readline = require('readline').createInterface(< input: process.stdin, output: process.stdout >); const choices = ['rock', 'paper', 'scissors']; const getComputerChoice = () => < const index = Math.floor(Math.random() * 3); return choices[index]; >const determineWinner = (playerChoice, computerChoice) => < if (playerChoice === computerChoice) < return 'It\'s a tie!'; >else if ( (playerChoice === 'rock' && computerChoice === 'scissors') || (playerChoice === 'paper' && computerChoice === 'rock') || (playerChoice === 'scissors' && computerChoice === 'paper') ) < return 'You win!'; >else < return 'The computer wins!'; >> const playGame = () => < readline.question('Choose rock, paper, or scissors: ', playerChoice => < playerChoice = playerChoice.toLowerCase(); if (!choices.includes(playerChoice)) < console.log('Invalid choice'); readline.close(); return; >const computerChoice = getComputerChoice(); console.log(`You chose $`); console.log(`The computer chose $`); console.log(determineWinner(playerChoice, computerChoice)); readline.close(); >); > playGame(); 
Choose rock, paper, or scissors: You chose rock The computer chose scissors You win!

Conclusion

In conclusion, this article provides a step-by-step guide on how to code a rock paper scissors game using JavaScript .

It covers the game logic, and user interface, and provides the necessary code to get started.

The game allows players to choose between rock, paper, and scissors while playing against the computer.

The result of each round is displayed on the screen, and there is an option to restart the game.

By executing the provided instructions and using the code above, readers can easily create their own rock paper scissors game in JavaScript.

We are hoping that this article provides you with enough information that helps you understand how to make a rock paper scissors game in js or JavaScript .

Thank you for reading itsourcecoders 😊.

Источник

Читайте также:  Java data objects example
Оцените статью