0

Hey all i need your help. In this rock paper scissor game the winner is the first to get to five wins between the user and computer. Although i have not looped this yet, i need help storing the counts of each win into a variable from my points() function into var playerPoints = 0 ; or var compPoints = 0 ; depending on who wins the round. if you have loop suggestions feel free to advice me on that as well! thanks

    //decalring an array with weapons of choice
    const weaponArray = ["rock", "paper", "scissors"];
    // selects a random index from array to represent computer choice
    const computerChoice = weaponArray[[Math.floor(Math.random() * weaponArray.length)]];
    //prompts user to make a choice of weapon
    const playerPrompt = prompt("Please enter Rock, Paper, or Scissors!");
    //lowers all alphabet input to lower case
    const playerChoice = playerPrompt.toLowerCase();
    
 

    
    //function runs player vs computer choices and determines winner of round
    const round = (computerChoice, playerChoice) => {
      if (playerChoice === "scissors" && computerChoice === "rock" || playerChoice === "rock" && computerChoice === "paper" || playerChoice ==="paper" && computerChoice === "scissors") {
      return "Just Give Up Now Looser!";
    }
      else if (playerChoice === "rock" && computerChoice === "scissors" || playerChoice === "paper" && computerChoice === "rock" || playerChoice==="scissors" && computerChoice === "paper")
      {
      return "You Won This Round!";
    }
    else {
      return "Its a Tie!";
    }
    };
    
    //stores round function value  into a variable 
    var state = round(computerChoice, playerChoice);
   
   
   // adds points to player or computer based on "state" value 
  const points = () => {
    if (state === "You Won This Round!"){
      return playerPoints + 1;
    }
    else if (state === "Just Give Up Now Looser!"){
      return compPoints + 1;
    }
    else{
      return null
    }
    
  };
   
   
    var playerPoints = points()  ;
    var compPoints = points()  ;
   
   
   
 console.log(state);
 console.log(points());
 //console.log(compPoints);
 //console.log(playerPoints);

5
  • BTW, else shouldn't be followed by (conditions). It should be else { ... } not else (conditions) { ... } Commented May 15, 2018 at 15:29
  • Using prompt is really not user friendly. Why not let the user press one of three buttons? Commented May 15, 2018 at 15:31
  • I think you want an else if instead of an else. You should also be using triple equal signs instead of double equal signs in Javascript. As for your loop, just define the variables before the loop and then increment them in the conditionals of the loop Commented May 15, 2018 at 15:31
  • totally right that passed right by me thank you ibrahim Commented May 15, 2018 at 15:34
  • @chevybow the plan is to add buttons at the end, i am running everything off the console for now for testing purposes. thanks for the triple equal suggestion i will update that as well thanks once again Commented May 15, 2018 at 15:48

2 Answers 2

1

Might as well add my answer here. I wouldn't use a prompt approach, but buttons instead. Store the scores in an object and use a conditional to check if someone has reached five points after each game:

const userScore = document.querySelector('.user .score')
const computerScore = document.querySelector('.computer .score')
const resultContainer = document.querySelector('.result')
const userThrowContainer = document.querySelector('.userThrow')
const opponentThrowContainer = document.querySelector('.opponentThrow')
const buttons = document.querySelectorAll('button')

const score = {
  user: 0,
  computer: 0
}

function rpsMatch(userThrow) {
  // Define possible throws
  const throwOptions = [
    'rock',
    'paper',
    'scissors'
  ]
  
  // Choose randomly from array of throws
  let opponentThrow = throwOptions[Math.floor(Math.random() * throwOptions.length)]
  
  // Print user and computer throws
  userThrowContainer.innerText = `You threw ${userThrow}`
  opponentThrowContainer.innerText = `Computer threw ${opponentThrow}`
  
  function userWins() {
    resultContainer.innerText = 'You win'
    score.user++
    updateScores()
  }
  
  function computerWins() {
    resultContainer.innerText = 'You lose'
    score.computer++
    updateScores()
  }
  
  function updateScores() {
    userScore.innerText = score.user
    computerScore.innerText = score.computer
  }
  
  function resetScore() {
    userScore.innerText = 0
    computerScore.innerText = 0
    score.user = 0
    score.computer = 0
  }
  
  // RPS logic
  if (userThrow == opponentThrow) {
    resultContainer.innerText = 'You tied'
  } else {
    if (userThrow == 'rock') {
      opponentThrow == 'scissors' ? userWins() : computerWins()
    } else if (userThrow == 'paper') {
      opponentThrow == 'rock' ? userWins() : computerWins()
    } else {
      opponentThrow == 'paper' ? userWins() : computerWins()
    }
  }
  
  if (score.user === 5) {
    alert('You won the first to 5!')
    resetScore()
  }
  
  if (score.computer === 5) {
    alert('You lost the first to 5!')
    resetScore()
  }
}

// Attach event handlers to each button
buttons.forEach(button => {
  button.addEventListener('click', e => {
    // Assign data attribute to variable
    let userThrow = e.target.dataset.type
    e.preventDefault()
    // Pass user selection to rpsMatch
    rpsMatch(userThrow)
  })
})
<div class="user">User Score: <span class="score">0</span></div>
<div class="computer">Computer Score: <span class="score">0</span></div>
<button data-type="rock">Rock</button>
<button data-type="paper">Paper</button>
<button data-type="scissors">Scissors</button>
<div class="userThrow"></div>
<div class="opponentThrow"></div>
<div class="result"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

YES! thank you, answered my question and then some. i appreciate your time to teach i will definitely use an object to keep track of score and adjust my conditionals as you did for it makes much better sense.
Glad this helps! I already had a version of this without the scoring so I just forked that Pen and updated it to fit your needs. If you have any questions leave a comment and I can edit my response.
0

I would not use prompt but HTML buttons to get the user's input. That way they don't have to type, just click.

Here is how you could do it:

//declaring an array with weapon of choice
const weaponArray = ["rock", "paper", "scissors"];
const players = ["tie", "you", "computer"];
const points = [0, 0, 0]; // tie, player, computer
const human = document.querySelector('#human');
const computer = document.querySelector('#computer');
const winner = document.querySelector('#winner');
const humanScore = document.querySelector('#humanScore');
const computerScore = document.querySelector('#computerScore');

// Respond to input
document.querySelector("#buttons").onclick = function(e) {
    const playerChoice = +e.target.value; // 0, 1 or 2
    human.textContent = weaponArray[playerChoice];
    // selects a random index from array to represent computer choice
    const computerChoice = Math.floor(Math.random() * weaponArray.length); // 0, 1 or 2
    computer.textContent = weaponArray[computerChoice];
    // Determine result
    const result = (playerChoice + 3 - computerChoice) % 3; // 0 = tie, 1 = player win, 2 = computer win
    winner.textContent = players[result];
    // add point to the relevant winner. Winner 0 represents the ties - they don't really count
    points[result]++; 
    humanScore.textContent = points[1];
    computerScore.textContent = points[2];
    if (result && points[result] >= 5) {
        alert("Game over. " + players[result] + " won");
        location.reload();
    }
}
Please make your choice:<br>
<div id="buttons">
    <button value="0">rock</button> <button value="1">paper</button> <button value="2">scissors</button><br>
</div>
Your weapon: <span id="human"></span><br>
Computer's weapon: <span id="computer"></span><br>
Winner: <span id="winner"></span><br>
Your score: <span id="humanScore"></span><br>
Computer's score: <span id="computerScore"></span><br>

3 Comments

thank you, i will be adding buttons but am using console.log to test out my functions while i go as i am learning. My trouble right now is getting each "rounds" winner stored or "pushed" into one of two variables (playerPoints or compPoints ) to keep count of their wins, any suggestions?
My code shows how I would update points. I would not use the names for calculating points. Working with 0, 1 and 2 makes things easier. Better use good patterns from the start. If you don't want buttons now then use a while loop that tests wether you have 5 points.
ok just got done looking at your code, it makes more sense to me now. since im new i had to understand your logic behind it. My approach required a different answer to storing the score, but i like the use of arrays to represent the players points and weapons in your code not to mention it looks shorter an simpler!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.