Rock Paper Scissors game issue - javascript

I built a very basic rock paper scissors game but it seems that somehow the game is not correctly capturing the userSelection or outputing the correct result...
I've spent hours researching and adjusting various aspects of my code but can't figure it out - I'm too green I guess.
I don't want a totally different version of how to do this -I'd like to fix this version and understand why it doesn't work currently :)
https://codepen.io/anna_whiskey/pen/XWRjQXV
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game() {
function humanPlay() {
document.getElementById("btn1").addEventListener("click", () => {
userSelection = "rock";
})
document.getElementById("btn2").addEventListener("click", () => {
userSelection = "paper";
})
document.getElementById("btn3").addEventListener("click", () => {
userSelection = "scissors";
})
}
function computerPlay() {
computerSel = Math.floor(Math.random() * gameInputs.length);
round1Answer = (gameInputs[computerSel]);
console.log((gameInputs[computerSel]));
humanPlay();
}
computerPlay();
document.getElementById("outcome").textContent = `You: ${userSelection} Computer: ${round1Answer}`
function playRound(round1Answer, userSelection) {
if (userSelection === 'rock' && round1Answer === 'scissors') {
alert('You WIN!');
} else if (userSelection === 'rock' && round1Answer === 'rock') {
alert('It/s a tie!');
} else if (userSelection === 'paper' && round1Answer === 'rock') {
alert('You WIN!');
} else if (userSelection === 'paper' && round1Answer === 'paper') {
alert('It/s a tie!');
} else if (userSelection === 'scissors' && round1Answer === 'paper') {
alert('You WIN!');
} else if (userSelection === 'scissors' && round1Answer === 'scissors') {
alert('It/s a tie!');
} else {
alert('You LOSE!');
}
}
playRound(round1Answer, userSelection);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<title>Rock Paper Scissors</title>
<body>
<div class="bg"></div>
<button id="btn1" onclick="game()">Rock</button>
<button id="btn2" onclick="game()">Paper</button>
<button id="btn3" onclick="game()">Scissors</button>
<div id="outcome"></div>
<link rel="stylesheet" href="rps.css">
<script type="text/javascript" src="rpsv2.js"></script>
</body>
</html>

you should try adding event listeners for human inputs
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game() {
function humanPlay() {
document.getElementById("btn1").addEventListener("click", () => {
userSelection = "rock";
console.log(`User Selection: ${userSelection}`)
})
document.getElementById("btn2").addEventListener("click", () => {
userSelection = "paper";
console.log(`User Selection: ${userSelection}`)
})
document.getElementById("btn3").addEventListener("click", () => {
userSelection = "scissor";
console.log(`User Selection: ${userSelection}`)
})
}
function computerPlay() {
computerSel = Math.floor(Math.random() * 3);
round1Answer = (gameInputs[computerSel]);
// console.log(`Round ans is ${round1Answer}`)
}
function playRound(round1Answer, userSelection) {
if (userSelection == 'rock' && round1Answer == 'scissors') {
alert('You WIN!');
}
else if (userSelection == 'paper' && round1Answer == 'rock') {
alert('You WIN!');
}
else if (userSelection == 'scissors' && round1Answer == 'paper') {
alert('You WIN!');
}
else if (userSelection == 'rock' && round1Answer == 'rock') {
alert('It/s a tie!');
}
else if (userSelection == 'paper' && round1Answer == 'paper') {
alert('It/s a tie!');
}
else if (userSelection == 'scissors' && round1Answer == 'scissors') {
alert('It/s a tie!');
}
else {
alert('You LOSE!');
}
}
humanPlay();
computerPlay();
playRound(round1Answer, userSelection);
}
using this i managed to log rock paper and scissor

You can simple do the task by the following script
JS
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game (humanChoosed) {
userSelection = gameInputs[humanChoosed];
function computerPlay() {
computerSel = Math.floor(Math.random() * gameInputs.length);
round1Answer = (gameInputs[computerSel]);
}
computerPlay();
document.querySelector('h1').textContent = `Human: ${userSelection} Computer: ${round1Answer}`;
function playRound (round1Answer, userSelection) {
if (userSelection === 'rock' && round1Answer === 'scissors') {
alert ('You WIN!');
} else if (userSelection === 'rock' && round1Answer === 'rock') {
alert ('It/s a tie!');
} else if (userSelection === 'paper' && round1Answer === 'rock') {
alert ('You WIN!');
} else if (userSelection === 'paper' && round1Answer === 'paper') {
alert ('It/s a tie!');
} else if (userSelection === 'scissors' && round1Answer === 'paper') {
alert ('You WIN!');
} else if (userSelection === 'scissors' && round1Answer === 'scissors') {
alert ('It/s a tie!');
} else {
alert ('You LOSE!');
}
}
playRound (round1Answer, userSelection);
}
HTML
<body>
<div class="bg"></div>
<button id="btn1" onclick="game(0)">Rock</button>
<button id="btn2" onclick="game(1)">Paper</button>
<button id="btn3" onclick="game(2)">Scissors</button>
<h1>Hello</h1>
<link rel="stylesheet" href="rps.css">
<script type="text/javascript" src="rps.js"></script>
</body>

Related

getResult is Undefined

I can't seem to find out what is creating this undefined error in my basic rock paper scissor game it gives me to results instead of just one I'm trying to understand javascript its just taking me time to really grasp the in and outs of it if anyone can solve this for me and explain where I went wrong I'd really appreciate it
<!DOCTYPE html>
<head>
<title>Rock, Paper, Scissors</title>
<link rel="stylesheet" type="text/css" href="./css/reset.css">
<link rel="stylesheet" type="text/css" href="./css/style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<h2>User Choice: <span id="user-choice"></span></h2>
<h2>Computer Choice: <span id="computer-choice"></span></h2>
<h2>Result: <span id="result"></span></h2>
<button id="Rock">Rock</button>
<button id="Paper">Paper</button>
<button id="Scissors">Scissors</button>
<script src="rock.js"></script>
</body>
</html>
const computerChoiceDisplay = document.getElementById ("computer-choice")
const userChoiceDisplay = document.getElementById("user-choice")
const resultDisplay = document.getElementById("result")
const possibleChoices = document.querySelectorAll("button")
let userChoice
let computerChoice
let result
possibleChoices.forEach(possibleChoices => possibleChoices.addEventListener('click', (e) => {
userChoice = e.target.id
userChoiceDisplay.innerHTML = userChoice
generateComputerChoice()
getResult()
}))
function generateComputerChoice() {
const randomNumber = Math.floor(Math.random() * 3) + 1 // or you can use possibleChoices.length
if(randomNumber === 1) {
computerChoice = 'rock'
}
if(randomNumber === 2) {
computerChoice = 'scissors'
}
if(randomNumber === 3) {
computerChoice = 'paper'
}
computerChoiceDisplay.innerHTML = computerChoice;
}
function getResult() {
if (userChoice === 'rock' && computerChoice === 'paper') {
result = 'you win!'
}
if (userChoice === 'scissor' && computerChoice === 'rock') {
result = 'you win!'
}
if (userChoice === 'paper' && computerChoice === 'scissors') {
result = 'you win!'
}
if (userChoice === 'rock' && computerChoice === 'scissors') {
result = 'you lost!'
}
if (userChoice === 'scissors' && computerChoice === 'paper') {
result = 'you lost!'
}
if (userChoice === 'paper' && computerChoice === 'rock') {
result = 'you lost!'
}
if (userChoice === computerChoice) {
result = `its a draw!`
}
resultDisplay.innerHTML = result
console.log(getResult)
}
The conditions inside the getResult() function never gets true because the string values compared inside if conditions doesn't match.
The string value equaled to userChoice is lowercase and the string value which you actually get through userChoice is Title case(First letter capital). So the strings doesn't match and result variable never gets assigned. Hope this helps!
function getResult() {
if (userChoice == 'Rock' && computerChoice == 'paper') {
result = 'you win!';
}
if (userChoice == 'Scissors' && computerChoice == 'rock') {
result = 'you win!'
}
if (userChoice == 'Paper' && computerChoice == 'scissors') {
result = 'you win!'
}
if (userChoice == 'Rock' && computerChoice == 'scissors') {
result = 'you lost!'
}
if (userChoice == 'Scissors' && computerChoice == 'paper') {
result = 'you lost!'
}
if (userChoice == 'Paper' && computerChoice == 'rock') {
result = 'you lost!'
}
if (userChoice == computerChoice) {
result = 'its a draw!'
}
resultDisplay.innerHTML = result
console.log(getResult)
}

why is my rock,paper game not running correctly

I'm learning front end and this project for a rock paper game is killing me, I'm not getting any errors and the logic seems correct to me but I'm not getting any output. I think my buttons are wrong and maybe I'm but I honestly have no clue id really appreciate it if somebody could help me out I have been stuck on this for hours.
<script>
const score=document.querySelector("score");
const buttons=document.querySelectorAll("buttons");
const computer=document.querySelector("computer");
const player=document.querySelector("player");
const rock=document.getElementById("rock");
const paper=document.getElementById("paper");
const scisscors=document.getElementById("scisscors");
function computerplayer(){
let computer=Math.floor(Math.random() * 3);
let random=['rock',"paper",'sisscors']
if(computer>3){
return 'rock'
}
if(computer<2){
return 'paper'
}
else{
return 'sisscors'
}
}
function game(choice,computer){
if(choice=='rock'&& computer=='sisscors'){
pscore++
score();
console.log( 'u win');
}
if(choice== 'rock'&& computer==="rock"){
console.log("it be a tie")
}
if(choice=="rock"&& computer=="paper"){
cscore++
score();
console.log("u lose");
}
if(choice== 'sisscors'&& computer=='rock'){
console.log( "u lost")
cscore++
score();
}
if(choice=='sisscors'&& computer=='paper'){
console.log('you win')
pscore++
score();
}
if(choice=='paper'&& computer=='rock'){
console.log("you win")
pscore++
score();
}
if(choice=='paper'&& computer=='sisscors'){
console.log("lost")
cscore++
score();
}
}
function score(){
if(pscore==3){
console.log("end game win")
}
if(cscore==3){
console.log("end game loser")
}
}
buttons.addEventListener('click', function(){
game('rock')
})
buttons.addEventListener('click', function(){
game('paper')
})
buttons.addEventListener('click', function(){
game('sisscors')
})
</script>
Thanks
First of all this code won't return 3 or greater number
let computer = Math.floor(Math.random() * 3);
then computerplayer() will only return 'paper' and 'sisscors' and you should change computerplayer() function.
Next you should change your buttons event listennr to these:
rock.addEventListener('click', function () {
game('rock', computerplayer())
})
paper.addEventListener('click', function () {
game('paper', computerplayer())
})
rock.addEventListener('click', function () {
game('sisscors', computerplayer())
})
Since you have to change many more things, then I mentioned a complete code here:
<script>
window.addEventListener('load', () => {
let pscore = 0;
let cscore = 0;
const result = document.querySelector(".result");
const player = document.querySelector(".pscore");
const computer = document.querySelector(".cscore");
const rock = document.getElementById("rock");
const paper = document.getElementById("paper");
const scissors = document.getElementById("scissors");
rock.addEventListener('click', function () {
game('rock', computerplayer())
})
paper.addEventListener('click', function () {
game('paper', computerplayer())
})
scissors.addEventListener('click', function () {
game('scissors', computerplayer())
})
function computerplayer() {
let random = Math.floor(Math.random() * 3);
if (random == 0)
return 'rock'
else if (random == 1)
return 'paper'
else if (random == 2)
return 'scissors'
}
function game(choice, computerAction) {
if (choice == 'rock' && computerAction == 'scissors') {
pscore++
score();
console.log('u win');
} else if (choice == 'rock' && computerAction === "rock") {
console.log("it be a tie")
} else if (choice == "rock" && computerAction == "paper") {
cscore++
score();
console.log("u lose");
} else if (choice == 'scissors' && computerAction == 'rock') {
console.log("u lost")
cscore++
score();
} else if (choice == 'scissors' && computerAction == 'paper') {
console.log('you win')
pscore++
score();
} else if (choice == 'scissors' && computerAction === "scissors") {
console.log("it be a tie")
} else if (choice == 'paper' && computerAction == 'rock') {
console.log("you win")
pscore++
score();
} else if (choice == 'paper' && computerAction == 'scissors') {
console.log("lost")
cscore++
score();
} else if (choice == 'paper' && computerAction === "paper") {
console.log("it be a tie")
}
function score() {
console.log(pscore, cscore)
player.innerHTML = pscore;
computer.innerHTML = cscore;
if (pscore == 3) {
console.log("end game win")
result.innerHTML = 'You won.';
} else if (cscore == 3) {
console.log("end game loser")
result.innerHTML = 'Computer won.';
}
if (pscore == 3 || cscore == 3) {
rock.style.display = 'none';
paper.style.display = 'none';
scissors.style.display = 'none';
}
}
}
});
</script>
<body>
Computer:<span class="cscore"></span>
<br />
Player: <span class="pscore"></span><br />
<br />
<input type="button" id="rock" value="Rock" />
<input type="button" id="paper" value="Paper" />
<input type="button" id="scissors" value="scissors" />
<span class="result"></span>
</body>

How can I loop the function playRound()?

I am building my first rock paper scissors game. I have not formally done loops as yet but I am trying to apply a for loop to the playRound function so it plays five times. Sadly I am not certain where to apply it. I have tried a few ways but keep getting errors. Anyone able to take a look and provide an option. code is below.
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
}
if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
playerSelection = "rock";
computerSelection = computerPlay();
if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")
) {
return "Player Wins!";
} else if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
If I understood correctly what you want, you can do a while loop with a counter, also I improved a bit your code, making strict equality (from == to ===), and removed redundant code
let counter = 1;
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
} else if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
counter++;
if (
(playerSelection === "rock" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "paper") ||
(playerSelection === "paper" && computerSelection === "rock")
) {
return "Player Wins!";
} else if (
(playerSelection === "rock" && computerSelection == "paper") ||
(playerSelection === "paper" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
while (counter < 6) {
console.log(playRound(playerSelection, computerPlay()));
}
Hope this example gives some hint on how to do good programming
// rock = 0
// paper = 1
// scissor = 2
const valueMap = {
0: 'rock',
1: 'paper',
2: 'scissor'
}
function pick() {
return Math.floor(Math.random() * 3)
}
function decide(p1, p2) {
const pool = [p1, p2]
const sortedPool = pool.sort((a, b) => b.value - a.value)
const diff = sortedPool[0].value - sortedPool[1].value
if (diff === 2) {
return sortedPool[1].name
} else if (diff === 0) {
return 'draw'
} else {
return pool.find(v => v.value === sortedPool[0].value).name
}
}
function play(times, cb) {
let n = 1
while (n <= times) {
cb(n)
n++
}
}
play(5, function(n) {
const player1 = {
name: 'Player',
value: pick()
}
const player2 = {
name: 'Computer',
value: pick()
}
const result = decide(player1, player2)
console.log(
`Game ${n}`,
`${player1.name} ${valueMap[player1.value]}`,
` vs `,
`${player2.name} ${valueMap[player2.value]}`,
`>>> Winner ${result}
`
)
})
Add loop for last 3 line
for (i=0; i<5; i++){
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
}
Edit: Please note that you have redundant call function computerPlay() inside playRound function since computer selection is passed in second argument

Changing the value of a variable with DOM element click

Im trying to allow the player to click the Rock paper or scissors button and that changes the value of the 'playerChoice' variable so so the playRound function can be called with their choice but it doesnt seem to work and im not sure what im doing wrong
Code
// Rock paper scissors game
let rockBtn = document.querySelector('.Rock');
let paperBtn = document.querySelector('.Paper');
let scissorBtn = document.querySelector('.Scissors');
function computerPlay() {
let rps = ["Rock", "Paper", "Scissors"];
let computerChoice = rps[Math.floor(Math.random()*rps.length)];
return computerChoice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == "Rock" && computerSelection == "Rock") {
console.log('Its a Draw');
} else if (playerSelection == "Rock" && computerSelection == "Scissors") {
console.log("Player wins");
} else if(playerSelection == "Rock" && computerSelection == "Paper") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Paper") {
console.log("Its a draw");
} else if(playerSelection == "Paper" && computerSelection == "Scissors") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Rock") {
console.log("Player wins");
} else if(playerSelection == "Scissors" && computerSelection == "Scissors") {
console.log("Its a draw");
} else if(playerSelection == "Scissors" && computerSelection == "Paper") {
console.log("Player wins ");
} else if(playerSelection == "Scissors" && computerSelection == "Rock") {
console.log("Computer wins");
}
}
function game() {
const computerChoice = computerPlay();
var playerChoice = "";
rockBtn.addEventListener('click' , function() {
playerChoice = "Rock";
});
paperBtn.addEventListener('click' , function() {
playerChoice = "Paper";
console.log(playerChoice);
});
scissorBtn.addEventListener('click' , function() {
playerChoice = "Scissors";
});
console.log("Player choice is" + playerChoice);
console.log('Computer choice is' + computerChoice);
playRound(playerChoice, computerChoice);
}
game();
Is this the correct way to do this is there a better way?
You should call playRound method inside the click listeners.
// Rock paper scissors game
let rockBtn = document.querySelector('.Rock');
let paperBtn = document.querySelector('.Paper');
let scissorBtn = document.querySelector('.Scissors');
var playerChoice = "";
function computerPlay() {
let rps = ["Rock", "Paper", "Scissors"];
let computerChoice = rps[Math.floor(Math.random()*rps.length)];
return computerChoice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == "Rock" && computerSelection == "Rock") {
console.log('Its a Draw');
} else if (playerSelection == "Rock" && computerSelection == "Scissors") {
console.log("Player wins");
} else if(playerSelection == "Rock" && computerSelection == "Paper") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Paper") {
console.log("Its a draw");
} else if(playerSelection == "Paper" && computerSelection == "Scissors") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Rock") {
console.log("Player wins");
} else if(playerSelection == "Scissors" && computerSelection == "Scissors") {
console.log("Its a draw");
} else if(playerSelection == "Scissors" && computerSelection == "Paper") {
console.log("Player wins ");
} else if(playerSelection == "Scissors" && computerSelection == "Rock") {
console.log("Computer wins");
}
playerChoice = "";
}
rockBtn.addEventListener('click' , function() {
playerChoice = "Rock";
playRound(playerChoice, computerPlay());
});
paperBtn.addEventListener('click' , function() {
playerChoice = "Paper";
playRound(playerChoice, computerPlay());
});
scissorBtn.addEventListener('click' , function() {
playerChoice = "Scissors";
playRound(playerChoice, computerPlay());
});

alert() not working in function

Added buttons to my rock paper scissors game, I was having trouble making the alert show up after the userChoice variable changes, so I used eventListeners for that and the winner stopped showing up with the alert, why is this happening? Is there a better way to do this?
I'm a beginner any help is appreciated.
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){} //picks a random nb and makes it rock paper...
let userChoice;
function userPlay (){
btnRock.addEventListener("click", ()=>{
userChoice="rock";
return userChoice;
});
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
return userChoice;
});
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
return userChoice;
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
theGame(compPlay(),userPlay());
</script>
</html>
The function call will happen during the load of the script.At that time, the compPlay function will return a value whereas the userPlay function will create the elements. Thereafter when the button click is happening, the function will not even be called.
Edit:For your info..This is one way to do it
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){
let comChoice= Math.random();
console.log(comChoice);
if (comChoice<=0.33){
comChoice= "rock";
} else if (comChoice<=0.66){
comChoice= "scissors";
} else {
comChoice= "paper";
}
userPlay(comChoice);
}
let userChoice;
function userPlay (comChoice){//Function for user's click comparison with computer's option
let btnRock = document.createElement("button");
let tRock = document.createTextNode("Rock");
btnRock.appendChild(tRock);
document.body.appendChild(btnRock);
btnRock.addEventListener("click", ()=>{
userChoice="rock";
theGame(comChoice,userChoice);//Main function call to decide the winner
});
let btnPaper = document.createElement("button");
let tPaper = document.createTextNode("Paper");
btnPaper.appendChild(tPaper);
document.body.appendChild(btnPaper);
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
theGame(comChoice,userChoice);
});
let btnScissors = document.createElement("button");
let tScissors = document.createTextNode("Scissors");
btnScissors.appendChild(tScissors);
document.body.appendChild(btnScissors);
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
compPlay();//Basic initialising function call
</script>
</html>
You could call the game function when you click on a button
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
EDIT:
I forgot to said that in order to work to you should change your comChoice to a Global variable.Thanks #Krisna Prashatt

Categories

Resources