This is my first time posting a question so I apologize if I posted incorrectly. I am doing The Odin Project and I am stuck on why my code returns undefined and does not run my return code on the function singleRound. I also do not understand why my game function console.logs all of the code and does not run based on if the computer or the player got the point. If someone could point me in the right direction it would be greatly appreciated!
function computerPlay(computerSelection){
let choices=['Rock','Paper','Scissors']
let pick= choices[Math.floor(Math.random()*choices.length)];
}
//plays single round
function singleRound(playerSelection,computerSelection){
if (playerSelection === 'Paper'|| computerSelection === 'Rock') {
playerPoints=+1
return "You Win! Paper beats Rock";
}
else if (playerSelection === 'Paper'|| computerSelection=='Scissors') {
computerPoints=+1
return"Paper does not beat Scissors! You lose";
}
else if (playerSelection === 'Paper' || computerSelection ==='Paper') {
return "Paper does not beat Paper! Tie Game!";
}
else if (playerSelection === 'Rock' || computerSelection ==='Paper') {
computerPoints=+1
return"Rock does not beat Paper! You lose";
}
else if (playerSelection === 'Rock' || computerSelection ==='Rock') {
return"Rock does not beat Rock! Tie Game!";
}
else if (playerSelection === 'Rock' || computerSelection ==='Scissors') {
playerPoints=+1
return "Rock beats Scissors! You Win!";
}
else if (playerSelection === 'Scissors' || computerSelection ==='Paper') {
playerPoints=+1
return "Scissors Beats Paper! You Win!";
}
else if (playerSelection === 'Scissors' || computerSelection ==='Rock') {
computerPoints=+1
return "Scissors does not beat Rock! You lose!";
}
else if (playerSelection === 'Scissors' || computerSelection ==='Scissors') {
return"Scissors does not beat Scissors! Tie Game!";
}
}
//plays 5 rounds**strong text**
function game(){
for (let i = 0; i < 5; i++) {
let playerPoints=0;
let computerPoints=0;
if (playerPoints === i++)
{console.log('1 point for player');}
else if (computerPoints === i++){
console.log('1 point for the computer');}
else if (computerPoints !== i++ && playerPoints !== i++){ console.log('No one won this round. No points for either of you.');}
if (playerPoints= 5 && computerPoints< 5){
console.log('Yay! Congrats! You won the game! ');
}
if (computerPoints=5 && playerPoints < 5){
console.log('Sorry :/ You lost the game.');
}
else{
endGame();
}
}
}
let playerSelection=['Rock','Paper','Scissors']
const computerSelection=computerPlay
console.log('The computer chose:' + computerSelection());
prompt("Do you want to pick Rock, Paper, or Scissors?");
console.log(singleRound(playerSelection,computerSelection));
computerPlay();
Add return pick; in the computerPlay function. It is returning undefined because computerPlay returns nothing in the above code
function computerPlay(computerSelection){
let choices=['Rock','Paper','Scissors']
let pick= choices[Math.floor(Math.random()*choices.length)];
return pick
}
Also I would change the bottom code to the following since computerPlay returns the selection and we want to preserve the selection between the first console.log statement and when you call the singleRound
let playerSelection=['Rock','Paper','Scissors']
const computerSelection=computerPlay()
console.log('The computer chose:' + computerSelection);
prompt("Do you want to pick Rock, Paper, or Scissors?");
console.log(singleRound(playerSelection,computerSelection));
computerPlay();
Related
Hello everyone this is my first question here so sorry if it doesn't match all the rules. I am trying to make a rock paper scissors game from the Odin Project in javascript, and I'm having problem with the result output because it doesn't display what it should. If computer plays rock for e. and i play rock i should get it's a draw but i get something random all the time. Current code is with prompt() for user input, but I tried putting a fixed string like "paper" and it was the same, I also thought it was because I didn't put toLowerCase() properly so I removed it completely and it's still the same, I would appreciate your help!
function computerPlay() {
let rps = ["rock", "paper", "scissors"];
let random = rps[Math.floor(Math.random() * rps.length)];
return random;
}
console.log(computerPlay());
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return ("It's a draw!");
} else if ((playerSelection === "rock") && (computerSelection === "scissors")) {
return ("You win! Rock beats scissors");
} else if (playerSelection === "rock" && computerSelection === "paper") {
return ("You lose! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "rock") {
return ("You win! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "scissors") {
return ("You lose! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "paper") {
return ("You win! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "rock") {
return ("You lose!Rock beats scissors");
}
}
let computerSelection = computerPlay();
let playerSelection = prompt("Choose your weapon");
console.log(playRound(playerSelection, computerSelection));
You first console.log the function computerPlay() and that returns a certain value. After that you play the round and calls again the function computerPlay(), this computes the round with another value than you first console.log.
Try this code below
function computerPlay() {
let rps = ["rock", "paper", "scissors"];
let random = rps[Math.floor(Math.random() * rps.length)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return ("It's a draw!");
} else if ((playerSelection === "rock") && (computerSelection === "scissors")) {
return ("You win! Rock beats scissors");
} else if (playerSelection === "rock" && computerSelection === "paper") {
return ("You lose! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "rock") {
return ("You win! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "scissors") {
return ("You lose! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "paper") {
return ("You win! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "rock") {
return ("You lose!Rock beats scissors");
}
}
let computerSelection = computerPlay();
let playerSelection = prompt("Choose your weapon");
console.log(computerSelection)
console.log(playRound(playerSelection, computerSelection));
You can simplify your conditions in this way
const choices = ["Rock", "Paper", "Scissors"]
const computerPlay = () => choices[Math.floor(Math.random() * choices.length)]
function playRound(playerSelection, computerSelection) {
const difference = (choices.length + choices.indexOf(playerSelection) - choices.indexOf(computerSelection) )% choices.length
switch(difference){
case 0:
return "It's a draw!"
case 2:
return `You lose! ${computerSelection} beats ${playerSelection}`
default:
return `You win! ${playerSelection} beats ${computerSelection}`
}
}
let computerSelection = computerPlay();
let playerSelection
while(!choices.includes(playerSelection)){
const selected = prompt("Choose your weapon").trim().toLowerCase();
playerSelection = selected[0].toUpperCase()+selected.slice(1)
}
console.log(playRound(playerSelection, computerSelection));
I'm a complete beginner in Javascript and coding in general.
I'm trying to make a simple command-line javascript paper-rock-scissors game but I keep getting a bug. I've created a function for the computer to randomly pick paper, rock or scissors and getting the user's selection from a prompt. To get the result I've written an if else statement that will show an alert with the outcome but regardless the input it always shows a tie. It seems that the code always ends up on the else part of the statement and I can't figure out why. Can someone help me with what's wrong with the statement and why it skips to else?
function computerPlay() {
let computerChoices = ["paper", "rock", "scissors"];
let computerChoice = computerChoices[Math.floor(Math.random() * computerChoices.length)];
return computerChoice;
}
function playRound(computerSelection, playerSelection) {
if (computerSelection === "rock" && playerSelection.toLowerCase() === "paper") {
alert("You win, paper beats rock!")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "scissors") {
alert("You win, scissors beat paper!")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "rock") {
alert("You win, rock beat scissors")
} else if (computerSelection === "rock" && playerSelection.toLowerCase() === "scissors") {
alert("You loose, rock beats scissors")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "rock") {
alert("You loose, paper beats rock")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "paper") {
alert("You loose, scissors beats paper")
} else {
alert("even steven")
}
}
for (let i = 1; i <= 5; i++) {
computerPlay()
const playerSelection = prompt("Please enter your choice", " ");
const computerSelection = computerPlay();
console.log(computerSelection);
console.log(playerSelection);
playRound(computerSelection, playerSelection);
}
Remove " " from the prompt, it's adding an unnnecessary white space causing issues in your if statements
function computerPlay() {
let computerChoices = ["paper", "rock", "scissors"];
let computerChoice = computerChoices[Math.floor(Math.random() * computerChoices.length)];
return computerChoice;
}
function playRound(computerSelection, playerSelection) {
if (computerSelection === "rock" && playerSelection.toLowerCase() === "paper") {
alert("You win, paper beats rock!")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "scissors") {
alert("You win, scissors beat paper!")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "rock") {
alert("You win, rock beat scissors")
} else if (computerSelection === "rock" && playerSelection.toLowerCase() === "scissors") {
alert("You loose, rock beats scissors")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "rock") {
alert("You loose, paper beats rock")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "paper") {
alert("You loose, scissors beats paper")
} else {
alert("even steven")
}
}
for (let i = 1; i <= 5; i++) {
computerPlay()
const playerSelection = prompt("Please enter your choice");
const computerSelection = computerPlay();
console.log(computerSelection);
console.log(playerSelection);
playRound(computerSelection, playerSelection);
}
I'm creating the javascript for a rock-paper-scissors game. (Full link to the code below with comments to explain.)
https://jsfiddle.net/rueeazy/8b5nw2ce/15/
I'm building a RPS game that runs 5 different times and displays the winner of me v the computer after 5 rounds. Right now the game is being played in google chrome dev tools with the results being logged through the console.
let myScore = 0
let pcScore = 0
function playRound(playerSelection, computerSelection) {
if (computerSelection == 'Paper' && playerSelection =='paper') {
return 'It\'s a tie!';
} else if (computerSelection == 'Paper' && playerSelection == 'rock') {
return 'You lose! Paper beats rock!';
pcScore ++;
} else if (computerSelection == 'Paper' && playerSelection == 'scissors') {
return 'You win! Scissors beats paper!';
myScore ++;
} else if (computerSelection == 'Rock' && playerSelection == 'paper') {
return 'You win! Paper beats rock!';
myScore ++;
} else if (computerSelection == 'Rock' && playerSelection == 'rock') {
return 'It\'s a tie!';
} else if (computerSelection == 'Rock' && playerSelection == 'scissors') {
return 'You lose! Rock beats scissors!';
pcScore ++;
} else if (computerSelection == 'Scissors' && playerSelection == 'paper') {
return 'You lose! Scissors beats paper!'
pcScore ++;
} else if (computerSelection == 'Scissors' && playerSelection == 'rock') {
return 'You win! Rock beats scissors!'
myScore ++;
} else (computerSelection == 'Scissors' && playerSelection == 'scissors')
return 'It\'s a tie!'
}
function winner() {
if (myScore > pcScore) {
return 'You Won!';
} else if (myScore = pcScore) {
return 'You tied!';
} else pcScore > myScore
return 'The computer won!'
}
I am supposed to track the score via the [console.log] after each round and display the winner. And I loop this process in function game() 5 times and keep a tally of who won more rounds - and display the winner at the end. But when I call function game() in the console - it ALWAYS displays "the computer won" so I don't believe winner() is receiving the updated result of myScore/pcScore from playRound().
function game() {
console.log(playRound(playerSelection, computerPlay()));
console.log(playRound(playerSelection, computerPlay()));
console.log(playRound(playerSelection, computerPlay()));
console.log(playRound(playerSelection, computerPlay()));
console.log(playRound(playerSelection, computerPlay()));
return winner()
}
The part I'm having trouble with is getting the new results of pc/my score from the function playRound() to winner() so that I can display the true winner in game().
I've tried making myScore and pcScore global variables that apply to every function in hopes that they would first be effected in playRound() and then from playRound() to winner() but that didn't seem to work. So I put myScore and pcScore inside the playRound() function - but don't know the correct way to define myScore and pcScore inside winner() and game().
I hope this makes sense - I appreciate the help!
you try to increase score after returning from the function ;
...
else if (computerSelection == 'Paper' && playerSelection == 'rock') {
return 'You lose! Paper beats rock!';
pcScore ++;
}
...
this should be
...
else if (computerSelection == 'Paper' && playerSelection == 'rock') {
pcScore ++;
return 'You lose! Paper beats rock!';
}
...
So I have been working on this for awhile and can't figure out why my if/else statement does not console.log the correct response based on the computer and player selections. It seems like it will return a random statement regardless of the input from player or computer. Also, I don't understand why it will prompt me for input twice.
I get that there are other ways to build a simple RPS game in the console, but I don't understand why this won't work specifically. I'm more worried about what steps I'm missing in building a simple game that are essential for other projects later. I'm obviously new at this and am working on this through the Odin Project website, for reference. Thank you so much in advance for the help! Anyway, here's the code:
<script>
function computerChoice() {
let choices = ['rock', 'paper', 'scissors'];
let result = choices[Math.floor(Math.random() * choices.length)];
return result
};
let playerSelection = function() {
let playerChoice = prompt('What do you choose, young Padawan?')
return playerChoice.toLowerCase()
};
let computerSelection = computerChoice();
console.log(computerChoice());
console.log(playerSelection());
function play(playerSelection, computerSelection) {
if (playerSelection === 'rock' && computerSelection === 'paper') {
console.log('Paper beats rock! Computron wins!');
} else if (playerSelection === 'rock' && computerSelection === 'scissors') {
console.log('Rock smash scissors! You win!');
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
console.log('Paper covers rock! You win Starlord!');
} else if (playerSelection === 'paper' && computerSelection === 'scissors') {
console.log('Scissors cuts paper! Thanos is king!');
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
console.log('Scissors cuts paper! The Avengers avenge!');
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
console.log('Rock smash! Avengers suck!');
} else {
console.log('Tie! You must select a different weapon!');
}
};
play();
</script>
You have a combination of different ways of defining and calling function here. You define your player selection function but do not call it in a single instance, like you do with your computer selection. To make the player selection be consistent for the results, define your player selection as a function and then assign the results to a variable before logging it.
function computerChoice() {
let choices = ['rock', 'paper', 'scissors'];
let result = choices[Math.floor(Math.random() * choices.length)];
return result
};
function playerChoice() {
let playerChoice = prompt('What do you choose, young Padawan?');
return playerChoice.toLowerCase();
}
let playerSelection = playerChoice();
let computerSelection = computerChoice();
console.log("Player selection", playerSelection);
console.log("Computer selection", computerSelection);
function play(playerSelection, computerSelection) {
if (playerSelection === 'rock' && computerSelection === 'paper') {
console.log('Paper beats rock! Computron wins!');
} else if (playerSelection === 'rock' && computerSelection === 'scissors') {
console.log('Rock smash scissors! You win!');
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
console.log('Paper covers rock! You win Starlord!');
} else if (playerSelection === 'paper' && computerSelection === 'scissors') {
console.log('Scissors cuts paper! Thanos is king!');
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
console.log('Scissors cuts paper! The Avengers avenge!');
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
console.log('Rock smash! Avengers suck!');
} else {
console.log('Tie! You must select a different weapon!');
}
};
play(playerSelection, computerSelection);
EDIT
Also, you define two parameters for your play function but never pass them in to the function, make sure you pass in both playerSelection and computerSelection
You were calling your function with console.log, I added a promise to make sure nothing runs until user input is selected. Then showed you were to restart if it is a tie.
console.log(computerChoice()); // re-runs function
console.log(playerSelection()); // re-runs function
I also make sure the page is loaded before we start throwing some alerts to the user for curtesy.
document.addEventListener("DOMContentLoaded", function(event) { })
For computerChoice function let's remove the redundant variable, since we are returning what the variable value is. We do this instead.
return (choices[Math.floor(Math.random() * choices.length)]);
We used a promise for the user input, a promise basically is a function that promises a value or rejects something. When you call the function, you use .then((value)) to get the value.
let playerSelection = function() {
return new Promise((resolve) => {
let playerChoice = prompt('What do you choose, young Padawan?')
console.log(playerChoice); // we log the player choice here instead
resolve(playerChoice.toLowerCase());
})
};
We get the promise value like this
playerSelection().then((value) => { })
function computerChoice() {
let choices = ['rock', 'paper', 'scissors'];
return (choices[Math.floor(Math.random() * choices.length)]);
}
let playerSelection = function() {
return new Promise((resolve) => {
let playerChoice = prompt('What do you choose, young Padawan?')
console.log(playerChoice); // we log the player choice here instead
resolve(playerChoice.toLowerCase());
})
};
// Remove console.log(playerChoice); calling the function, causes two prompts
function play() {
playerSelection().then((playerChoice) => {
let computerSelection = computerChoice(); // We want new one each time.
if (playerChoice === 'rock' && computerSelection === 'paper') {
console.log('Paper beats rock! Computron wins!');
} else if (playerChoice === 'rock' && computerSelection === 'scissors') {
console.log('Rock smash scissors! You win!');
} else if (playerChoice === 'paper' && computerSelection === 'rock') {
console.log('Paper covers rock! You win Starlord!');
} else if (playerChoice === 'paper' && computerSelection === 'scissors') {
console.log('Scissors cuts paper! Thanos is king!');
} else if (playerChoice === 'scissors' && computerSelection === 'paper') {
console.log('Scissors cuts paper! The Avengers avenge!');
} else if (playerChoice === 'scissors' && computerSelection === 'rock') {
console.log('Rock smash! Avengers suck!');
} else {
alert('Tie! You must select a different weapon!');
play() // Tie-have user re-enter choice
}
})
};
// Make sure page loaded
document.addEventListener("DOMContentLoaded", function(event) {
//do work
play();
});
I have created a Rock Paper Scissors game that plays 5 rounds in the console and am now trying to refactor it to work in a browser with buttons using DOM manipulation.
The button and round functions are:
rock_btn.addEventListener('click',function(){
round('rock');
})
paper_btn.addEventListener('click',function(){
round('paper');
})
scissors_btn.addEventListener('click',function(){
round('scissors');
})
function round (playerSelection) {
let computerSelection = computerPlay();
if (playerSelection === 'rock' && computerSelection === 'scissors') {
playerScore++
userScore_span.innerHTML = playerScore;
result_div.innerHTML = 'You Win\! Rock beats Scissors\!';
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Rock beats Scissors\!';
} else if(playerSelection === 'paper' && computerSelection === 'rock') {
playerScore++;
userScore_span.innerHTML = playerScore;
result_div.innerHTML ='You Win\! Paper beats Rock\!';
} else if(playerSelection === 'rock' && computerSelection === 'paper') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Paper beats Rock\!';
} else if(playerSelection === 'scissors' && computerSelection === 'paper') {
playerScore++;
userScore_span.innerHTML = playerScore;
result_div.innerHTML ='You Win\! Scissors beats Paper\!';
} else if(playerSelection === 'paper' && computerSelection === 'scissors') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Scissors beats Paper\!';
} else {
result_div.innerHTML = ('A draw! Please play again!');
}
}
the game function used to count the rounds worked when called in the console but now has no effect:
let playerScore = 0;
let computerScore = 0;
function game () {
while (playerScore <= 5 || computerScore <= 5) {
round();
if(playerScore === 5) {
result_div.innerHTML = 'Player Wins!!!';
}
if(computerScore === 5) {
result_div.innerHTML = 'Computer Wins!!!';
}
}
}
Could someone please advise me how I can insert the game function into the sequence so the counter works?
Welcome to Stackoverflow.
Since you're relying on the game being played with buttons on your DOM, you should check for the win condition at the end of our round function:
Win condition:
function win_condition () {
if(playerScore === 5) {
result_div.innerHTML = 'Player Wins!!!';
}
if(computerScore === 5) {
result_div.innerHTML = 'Computer Wins!!!';
}
}
in your round function:
...
else if(playerSelection === 'paper' && computerSelection === 'scissors') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Scissors beats Paper\!';
} else {
result_div.innerHTML = ('A draw! Please play again!');
}
win_condition();
}
You could refactor a bit of your code by DRYing it up, maybe abstract the rules away (i.e. rocks win against scissor but loses against paper, etc.)
I did something like this on another post. See this CodePen:
lines 66 to 79 define the win conditions;
lines 93 to 99 how it's used.
Mind you, it's in ReactJS, so you'd need to apply it a bit differently, but the principle stays: abstract the logic away and DRY up your code.
(BTW: global mutable state will bite you eventually, you'd improve your code a lot by making your functions pure)