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
Related
I've put playerScore and computerScore variables in global scope. When user wins or loses these values increment by one number. They do work well. But in my HTML page they do not change dynamically.
Why my playerScore and computerScore values do not change in my HTML page, when I console.log them separately in console they are changed, but not in html page. I've tried to put them in function but it didn't work as expected.
// Selecting all the items with tag button
const buttons = document.querySelectorAll('button');
// Returns random item and assignes it to computerSelection variable
function computerPlay() {
const rps = ['rock', 'paper', 'scissors'];
let numberItem = Math.floor(Math.random() * rps.length);
computerSelection = rps[numberItem];
if (computerSelection === 'rock') {
console.log('computer selections is rock');
return computerSelection;
}
else if (computerSelection === 'paper' ) {
console.log('It is a paper!');
return computerSelection;
}
console.log('it is scissors');
return computerSelection;
}
// Plays game only five rounds;
let computerScore = 0;
let playerScore = 0;
function playRound(playerSelection, computerSelection) {
if(playerScore < 5 && computerScore < 5 ) {
if(((playerSelection == 'rock') && (computerSelection == 'paper')) || ((playerSelection == 'paper') && (computerSelection == 'scissors')) ||
((playerSelection == 'scissors') && (computerSelection == 'rock') )) {
console.log(`${computerSelection} beats ${playerSelection} the ROBOT WINS!`);
playerScore++;
return console.log(playerScore);
}
else if (((playerSelection == 'rock') && (computerSelection == 'scissors')) || ((playerSelection == 'paper') && (computerSelection == 'rock')) ||
((playerSelection == 'scissors') && (computerSelection == 'paper'))) {
console.log(` ${playerSelection} beats ${computerSelection} the PLAYER WINS!`);
computerScore++;
return console.log(computerScore);
}
return console.log('It is a DRAW');;
}
return console.log("GAME OVER!!!");
}
// returns value of clicked button and plays round
function fetchButtonValue(e) {
let itemClicked = e.target.dataset.item;
console.log(` THIS WAS CLICKED ${itemClicked}`);
return playRound(itemClicked, computerPlay());
}
// uses fetchButtonValue
buttons.forEach(function(button) {
button.addEventListener('click', fetchButtonValue);
});
// implement the vlaues to HTML but they doesn't change but the value changes when tracking them in console of browser.
let score= `
<p class = 'playerPoints'>Player: ${playerScore}</p>
<p class = 'computerPoints'>Computer: ${computerScore}</p>
`;
const divScore = document.querySelector('.score');
divScore.insertAdjacentHTML('beforebegin', scoreHTML);
Can anyone tell me why my code doesn't work properly? I'm trying to make game ROCK, PAPER, SCISSORS on plain Java Script. For some reason it doesn't work as I expect.
const computerAanswer = ["rock", "paper", "scissors"];
function computerPlay() {
let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
return answer;
}
console.log('computer choice is: ' + computerPlay().toUpperCase());
function playRound (playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase()
if (playerSelection == "rock" && computerSelection == "scissors") {
return "Congrats,you are winner!";
} else if (playerSelection == "paper" && computerSelection == "rock") {
return "Congrats,you are winner!";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
return "Congrats,you are winner!";
} else if (playerSelection == "rock" && computerSelection == "rock") {
return "Draw!";
} else if (playerSelection == "paper" && computerSelection == "paper") {
return "Draw!";
} else if (playerSelection == "scissors" && computerSelection == "scissors") {
return "Draw!";
} else {
return "You lose. Maybe next time...";
}
}
let playerSelection = prompt("Make your choose: Rock, Paper or Scissors?");
let computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
console.log('player choice is: ' + playerSelection.toUpperCase());
I guess that's just your first console.log :
console.log('computer choice is: ' + computerPlay().toUpperCase());
It plays a round for computer, then you play another one against prompted user.
Do that instead :
function computerPlay() {
let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
console.log('computer choice is: ' + answer.toUpperCase());
return answer;
}
When I nested
console.log('computer choice is: ' + answer.toUpperCase());
into computerPlay function it works.
const computerAanswer = ["rock", "paper", "scissors"];
function computerPlay() {
let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
console.log('computer choice is: ' + answer.toUpperCase());
return answer;
}
function playRound (playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase()
if (playerSelection == "rock" && computerSelection == "scissors") {
return "Congrats,you are winner!";
} else if (playerSelection == "paper" && computerSelection == "rock") {
return "Congrats,you are winner!";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
return "Congrats,you are winner!";
} else if (playerSelection == "rock" && computerSelection == "rock") {
return "Draw!";
} else if (playerSelection == "paper" && computerSelection == "paper") {
return "Draw!";
} else if (playerSelection == "scissors" && computerSelection == "scissors") {
return "Draw!";
} else {
return "You lose. Maybe next time...";
}
}
let playerSelection = prompt("Make your choose: Rock, Paper or Scissors?");
let computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
console.log('player choice is: ' + playerSelection.toUpperCase());
In following code, the outer variables playerScore and computerScore are not updated when I use the function calcScore? How do I update it, using a function? From what I understand, it is possible to change the value of the outer variable from an inner scope, but why does it not work here?
<script>
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result, playerScore, computerScore) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
}
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
calcScore(result, playerScore, computerScore);
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
Javascript doesn't pass variables by reference - so any modifications you do to playerScore and computerScore within calcScore() are only local to that function.
What you can do is make playerScore and computerScore global variables. That way any modifications will be in the global scope. Alternatively, you could have calcScore() return the modified values.
Using the global method:
<script>
let playerScore = 0;
let computerScore = 0;
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
}
function game() {
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
calcScore(result);
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
Alternative method:
<script>
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerSelection.toLowerCase();
if (playerSelection === computerSelection) {
return "draw";
}
else if (playerSelection === "rock"){
if (computerSelection === "scissors") return "win";
else if (computerSelection === "paper") return "lose";
}
else if (playerSelection === "paper"){
if (computerSelection === "scissors") return "lose";
else if (computerSelection === "rock") return "win";
}
else if (playerSelection === "scissors"){
if (computerSelection === "rock") return "lose";
else if (computerSelection === "paper") return "win";
}
}
function computerSelection() {
let selection = ["rock", "paper", "scissors"];
return selection[Math.floor(Math.random() * selection.length)];
}
function calcScore(result, playerScore, computerScore) {
if (result === "win") {
playerScore += 1;
console.log("win");
}
else if (result === "lose") {
computerScore += 1;
console.log("lose");
}
else if (result === "draw") {
playerScore += 1;
computerScore += 1;
}
return [playerScore, computerScore];
}
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i <= 5; i++) {
let result = playRound(prompt("Select rock, paper, or scissors!"), computerSelection());
let scores = calcScore(result, playerScore, computerScore);
playerScore += scores[0];
computerScore += scores[1];
console.log(`You have ${playerScore} points! Computer has ${computerScore} points!`);
}
playerScore, computerScore = 0, 0;
}
</script>
your defining both of those variables twice so now im confused. do you want to be abled to reuse those variables in the game function without re defining them? because if thats the case then they should be global variables instead of function parameters(you wont be able to use those defined in the function parameter outside of that function).
i'm very new to js, and it's my first code on it. i'm trying to make a game "rock, papper, scissors". please, look at my code, my funcrion playRound doesn't wor, i need it to return scores.
please, give me advises how to change my code, but i don't want you to solve all for me. thank you.
function computerPlay() {
let computerAction = Math.floor(Math.random() * choises.length);
let computerSelection = choises[computerAction];
return computerSelection;
}
function userPlay() {
let playerSelection = prompt(choises).toLowerCase();
return playerSelection;
}
let choises = ['rock', 'paper', 'scissors'];
let Score = new Map([
['userScores', 0],
['computerScores', 0]
]);
function playRound(playerSelection, computerSelection) {
if (playerSelection === choises[0] && computerSelection === choises[0]) ||
(playerSelection === choises[1] && computerSelection === choises[1]) ||
(playerSelection === choises[2] && computerSelection === choises[2]){
return Score = ['userScores' + 1, 'computerScores' + 1];
} else if (playerSelection === choises[0] && computerSelection !== choises[0]) ||
(playerSelection === choises[1] && computerSelection !== choises[1]) ||
(playerSelection === choises[2] && computerSelection !== choises[2])
return Score = ['userScores' + 1, 'computerScores'];
} else if (playerSelection !== choises[0] && computerSelection === choises[0]) ||
(playerSelection !== choises[1] && computerSelection === choises[1]) ||
(playerSelection !== choises[2] && computerSelection === choises[2])
{
return Score = ['userScores', 'computerScores' + 1];
}
}
Refer to this:
function computerPlay() {
let computerAction = Math.floor(Math.random() * choises.length);
let computerSelection = choises[computerAction];
return computerSelection;
}
function userPlay() {
let playerSelection = prompt(choises).toLowerCase();
return playerSelection;
}
let choises = ['rock', 'paper', 'scissors'];
let Score = {
user: 0,
computer: 0
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection){
Score.user = Score.user + 1;
Score.computer = Score.computer + 1;
} else if ((playerSelection === choises[0] && computerSelection === choises[2]) ||
(playerSelection === choises[1] && computerSelection === choises[0]) ||
(playerSelection === choises[2] && computerSelection === choises[1])) {
Score.user = Score.user + 1;
} else {
Score.computer = Score.computer + 1;
}
}
let computerChoice = computerPlay();
let userChoice = userPlay();
playRound(userChoice, computerChoice);
console.log('computer hand', computerChoice);
console.log('user hand', userChoice);
console.log(Score);
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());
});