Javascript console not printing called function - javascript

I just started learning JavaScript and I am trying to improve a "Rock, Scissors, Paper" game I built(see code below).
I try to build the game without the last function, input(). But I learnt that I can only use "return" in a function. When I print the function using console.log() it worked without the input() function.
I want to learn how I can do this making use of the input() function and as well as be able to call the gamePlay() inside the input(). Any help will be appreciated.
var gamePlay = function (userGameChoice) {
var computerChoice = Math.random(0, 1);
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
} else {
return "paper wins";
}
}
if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
} else {
return "scissors wins";
}
}
if (choice1 === "scissors") {
if (choice2 === "rock") {
return " rock wins";
} else {
return "scissors wins"
}
}
}
compare(userGameChoice, computerChoice);
}
var input = function (userChoice) {
if (userChoice === "rock") {
return gamePlay("rock");
} else if (userChoice === "paper") {
return gamePlay("paper");
} else if (userChoice === "scissors") {
return gamePlay("scissors");
} else {
return "Invalid input";
}
}
input(prompt("Do you choose rock, paper or scissors?"));

Your gamePlay function does not return a value. It calls compare which does return a value but because gamePlay doesn't have a return statement it actually return undefined.
If you were to console.log(gamePlay("rock")); you would see undefined.
Side notes: also the input function could use a switch statement instead of if/then/elses.

I think you want to do something like this:
var options = ["rock", "scissors", "paper"];
var userinput = prompt("Do you choose rock, paper or scissors?");
var gameResult = "Invalid Input";
if (options.indexOf(userinput) > -1) {
gameResult = gamePlay(userinput);
}
alert(gameResult);
This takes the user input and compares it to a list of valid options. If it exists (>-1) then it will run the gamePlay method, storing the result in the variable gameResult

Related

Javascript function does not run when called

var gameFunction = function()
{
var userChoice = prompt("What do you choose: rock, paper, or scissors?")
var computerChoice = Math.random();
if (0 < computerChoice < 0.33)
{
computerChoice = "rock";
}
else if (0.33 < computerChoice < 0.67)
{
computerChoice = "scissors";
}
else
{
computerChoice = "paper";
}
console.log("Computer choice: ",computerChoice)
if (userChoice === computerChoice)
{
return "The result is a tie! Enter a new result?"
gameFunction();
}
else if (userChoice === "rock")
{
if (computerChoice === "scissors")
{
return "rock wins"
}
else if (computerChoice === "paper")
{
return "paper wins"
}
}
else if (userChoice === "paper")
{
if (computerChoice === "rock")
{
return "paper wins"
}
else if (computerChoice === "scissors")
{
return "scissors win"
}
}
else if (userChoice === "scissors")
{
if (computerChoice === "paper")
{
return "scissors wins"
}
else if (computerChoice === "rock")
{
return "rock win"
}
}
}
gameFunction();
This is the 9/9 section of the "Rock paper scissors" game from Codecademy: Javascript.
My problem is this:
When the User and Computer ties, it's supposed to re-run the entire "gameFunction" function, meaning it should ask a new input from the user and get a new input from the computer.
However, the program just prints out "The result is a tie!" without re-running "gameFunction." How can I fix this?
No line executed after return statement.. try
gameFunction();
return "The result is a tie! Enter a new result?"
The return statement exits the "gameFunction" function so it doesn't execute the next line. Try using a prompt instead like this:
if (userChoice === computerChoice)
{
prompt("The result is a tie! Enter a new result?");
gameFunction();
}
This way the user can respond to your prompt and you can use it to decide if the game is to continue. You could always just use an alert as well :)
Change return to alert(), like below:
From:
return "The result is a tie! Enter a new result?"
To:
alert("The result is a tie! Enter a new result?");
what about this: https://jsfiddle.net/41gcfL6g/
The thing here is adding a parameter to the function, so you can determine if have been a tie the last time you played. And then in the case of tie, instead of calling the function after the return, you return the result of the gameFunction
The recusive gameFunction() method inside the gameFunction() because the
control returns to the first calling function.
if (userChoice === computerChoice)
{
return "The result is a tie! Enter a new result?"
gameFunction();
}
So instead of return you can print a message there showing there is a tie.
if (userChoice === computerChoice)
{
alert("The result is a tie! Enter a new result?")
gameFunction();
}
and when the above condition is not met then it simply returns to the calling area and stop.
see fiddle, don't use return, console.log https://jsfiddle.net/o62vda05/
var userChoice;
function startGame()
{
userChoice = prompt("What do you choose: rock, paper, or scissors?");
gameFunction();
}
function gameFunction()
{
var computerChoice = Math.random();
if (0 < computerChoice < 0.33)
{
computerChoice = "rock";
}
else if (0.33 < computerChoice < 0.67)
{
computerChoice = "scissors";
}
else
{
computerChoice = "paper";
}
console.log("Computer choice: ",computerChoice)
if (userChoice === computerChoice) {
console.log( "The result is a tie! Enter a new result?");
startGame();
} else if (userChoice === "rock") {
if (computerChoice === "scissors")
{
console.log( "rock wins");
}
else if (computerChoice === "paper")
{
console.log( "paper wins");
}
} else if (userChoice === "paper") {
if (computerChoice === "rock") {
console.log( "paper wins");
} else if (computerChoice === "scissors") {
console.log ("scissors win");
}
} else if (userChoice === "scissors") {
if (computerChoice === "paper") {
console.log ("scissors wins");
} else if (computerChoice === "rock") {
console.log( "rock win");
}
}
}
startGame();

Newbie Javascript function returning undefined, rock paper scissors game

As a newbie, following the code academy course, I've come across a problem building a rock paper scissors game.
I've created 2 functions which contain the whole program, the program runs fine when the 2 choices are different but it returns undefined when the choices are the same and I can't understand why.
I can see that when the choices are tied, new choices keep being assigned until they are different and then the compare function is called on these different choices, which should return a winning result.
Just to add, I'd like to fix the code as it is, not rewrite the entire thing, I've completed this exercise on codeacademy but I'm just trying to do it in a different way as 2 self contained functions.
Thanks
var makeChoices = function() {
userChoice = "";
computerChoice = "";
userChoice = prompt("Do you choose rock, paper or scissors?");
computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice + " " + "User: " + userChoice);
};
var compare = function(choice1, choice2) {
if (choice1 === choice2) {
makeChoices();
compare(userChoice, computerChoice);
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";
}
}
else if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";
}
else {
return "scissors wins";
}
}
else {
return "invalid choice by user";
}
};
makeChoices();
compare (userChoice, computerChoice);
You have to return the result of the recursive call. Try changing
...
compare(userChoice, computerChoice);
...
to
...
return compare(userChoice, computerChoice);
...
When it is equal, you have "compare(userChoice, computerChoice);". The variables userChoice and computerChoice were defined in the makeChoices() function. They won't be available in compare() function. You can make them as global variables or consider moving you the compare() function calls to the bottom of makeChoices().
We all start the same way this impressive language!, do not worry about being a novice, you will soon be a teacher if you do not surrender!,here is the complete code for this exercise below:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
var compare = function(computerChoice, userChoice) {
if (computerChoice===userChoice) {
return("The result is a tie!");
}
if (userChoice === "rock"){
if (computerChoice === "paper") {
return("paper wins");
}
else if (computerChoice === "scissors") {
return("rock wins");
}
}
if (userChoice === "scissors") {
if (computerChoice==="paper") {
return("scissors wins");
}
else if (computerChoice === "rock") {
return("rock wins");
}
}
if (userChoice === "rock") {
if (computerChoice==="scissors") {
return "rock wins";
}
else if (computerChoice=== "paper") {
return "paper wins";
}
}
if (userChoice === "paper") {
if (computerChoice ==="scissors") {
return "scissors wins";
}
else if (computerChoice==="rock") {
return "paper wins";
}
}
};
compare();
I made such a game before:
var prsStatements = {
paperBeatsRock: 'Paper Beats Rock',
rockBeatsScissors: 'Rock Beats Scissors',
scissorsBeatsPaper: 'Scissors Beats Paper',
seperator: ' - ',
player1: 'Player One',
player2: 'Player Two',
wins: ' Wins!',
tie: "It's a Tie!",
tally: 'Final Tally: '
}
function PaperRockScissors(player1, player2){
var p = /^paper$/i, r = /^rock$/i, s = /^scissors$/i, prss = prsStatements, sep = prss.seperator, win = prss.wins;
var pbr = prss.paperBeatsRock+sep, rbs = prss.rockBeatsScissors+sep, sbp = prss.scissorsBeatsPaper+sep;
var plr1 = player1 ? player1 : prss.player1;
var plr2 = player2 ? player2 : prss.player2;
var p1w = plr1+win, p2w = plr2+win;
this.p1 = 0; this.p2 = 0;
this.rand = function(){
switch(Math.floor(Math.random()*3)){
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
}
this.play = function(in1, in2){
var i2 = in2 || this.rand();
if(in1.match(p) && i2.match(r)){
++this.p1;
return pbr+p1w;
}
else if(i2.match(p) && in1.match(r)){
++this.p2;
return pbr+p2w;
}
else if(in1.match(r) && i2.match(s)){
++this.p1;
return rbs+p1w;
}
else if(i2.match(r) && in1.match(s)){
++this.p2;
return rbs+p2w;
}
else if(in1.match(s) && i2.match(p)){
++this.p1;
return sbp+p1w;
}
else if(i2.match(s) && in1.match(p)){
++this.p2;
return sbp+p2w;
}
else if(in1.match(i2r)){
return prss.tie;
}
else{
return this;
}
}
this.tally = function(){
var pt = prss.tally;
if(this.p1 > this.p2){
return pt+p1w;
}
else if(this.p2 > this.p1){
return pt+p2w;
}
else{
return pt+prss.tie;
}
}
}
var pr = new PaperRockScissors('Joe', 'Bob');
console.log(pr.play('paper', 'rock'));
console.log(pr.play('rock', 'Paper'));
console.log(pr.play('scissors', 'paper'));
console.log(pr.play('rock', 'Paper'));
console.log(pr.play('paper', 'rock'));
console.log(pr.play('Paper', 'Scissors'));
console.log(pr.play('Paper', 'paper'));
console.log(pr.play('paper', 'Rock'));
console.log(pr.tally());
If you want to make this web-functional you would simply pass user input values, like:
pr.play(someElement.value, anotherElement.value);
Of course, you would want to use an Event and pass the correct values of either 'paper', 'rock', or 'scissors'.
Computer play might look like:
var pc = new PaperRockScissors('Joe', 'Comupter');
console.log(pc.play('paper'));
console.log(pc.play('rock'));
console.log(pc.play('scissors'));
console.log(pc.play('rock'));
console.log(pc.play('paper'));
console.log(pc.play('Paper'));
console.log(pc.play('Paper'));
console.log(pc.play('paper'));
console.log(pc.tally());

Why is this javascript function call not working?

Calling my function yields a syntax error, everything else works on its own. The error is thrown on.
console.log(compare(userChoice, computerChoice));
The error is:
SyntaxError: Unexpected token {
Any ideas?
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34)
{
computerChoice = "rock";
}
else if(computerChoice <= 0.67)
{
computerChoice = "paper";
}
else
{
computerChoice = "scissors";
}
var compare = function(choice1, choice2)
{
if (choice1 === choice2)
{
return "The result is a tie!";
}
else if (choice1 === "rock")
{
if (choice2 === "scissors")
{
return "rock wins";
}
else
{
return "paper wins";
}
}
else if (choice1 === "paper")
{
if (choice2 === "rock")
{
return "paper wins"
}
else
{
return "scissors wins"
}
}
else if (choice1 === "scissors")
{
if (choice2 === "paper"
{
return "paper wins"
}
else
{
return "scissors wins"
}
}
}
console.log(compare(userChoice, computerChoice));
Yes, you forgot the ) at if (choice2 === "paper".
As others have pointed out, one of your closing )s was missing.
With lots of nested if-else blocks, it's easy to lose track of your ()s and {}s. You can write much shorter, nicer, easier to read code if you utilise other conditional statements and expressions, namely the switch statement and the ? operator:
function compare(choice1, choice2) {
if (choice1 === choice2) {
return 'The result is a tie';
}
switch(choice1) {
case 'rock':
return choice2 === 'scissors' ? 'rock wins' : 'paper wins';
case 'paper':
return choice2 === 'rock' ? 'paper wins' : 'scissors win';
case 'scissors':
return choice2 === 'paper' ? 'scissors win' : 'rock wins';
}
}
As you can see, this code has much fewer ()s and {}s.

I'm learning Javascript, I'm trying to find out why my "Rock paper scissors" game wont work . .

Ok, so I'm sure this code is FILLED with inaccuracies, but I got really confused when I finished this lesson on the CodeAcademy website and then tried to copy/paste it into my own javascript.html file (where I keep stuff I'm learning) and the code wouldn't work! Then I plugged it in to jsfiddle to play with it and still couldn't get it to work.
here is the original code that I copy/pasted from CodeAcademy:
http://jsfiddle.net/p46pnwvx/
Javascript:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Player: " + userChoice);
console.log("Computer: " + computerChoice);
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "Rock Wins!";
}
else {
return "Paper Wins!";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "Paper Wins!";
}
else {
return "Scissors win!";
}
}
else if (choise1 === "scissors") {
if (choice2 === "paper") {
return "Scissors win!";
}
else {
return "Rock wins!";
}
}
}
console.log(compare(userChoice, computerChoice));
When this loads, the PROMPT box comes up, but nothing else happens.
Here is what I was playing around with, trying to make the game start and reset with a button, which I thought would be more useful (and educational) than having a game just up and start on it's own.
http://jsfiddle.net/o9ckcy52/
HTML
<h1>Rock, Paper, Scissors Game!</h1>
<button id="start" type="button" onclick="startGame()">Wanna Play?</button>
<p id="choice"></p>
<p id="result"></p>
Javascript
function startGame(){
document.getElementById("start").innerHTML = "Play again?"; // reset's button
return prompt("Do you choose rock, paper or scissors?");
var userChoice = startGame(); // stores result of startGame as user's choice
var computerChoice = Math.random(); // randomly creates computer's choice
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
function compare(choice1, choice2) { //compares user's choice and computer's choice
if (choice1 === choice2) {
return "The result is a tie!";
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "Rock Wins!";
}
else {
return "Paper Wins!";
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
return "Paper Wins!";
}
else {
return "Scissors win!";
}
}
else if (choise1 === "scissors") {
if (choice2 === "paper") {
return "Scissors win!";
}
else {
return "Rock wins!";
}
}
}
document.getElementById("choice").innerHTML= // prints user and computer selections
"Player: " + userChoice + /r
"Computer: " + computerChoice;
document.getElementById("result").innerHTML = // prints result of selection comparisons
(compare(userChoice, computerChoice));
}
Here the html works, but nothing happens when you click the button.
Any help given would be appreciated.
I updated your code. There were just some minor issues that were fixed. For example, the userChoice should be assigned to the prompt. Also, your regex /r is invalid and should also be wrapped in quotes, which becomes "\r". You also mispelled one of your choice1's.
Run the snippet below:
function startGame() {
document.getElementById("start").innerHTML = "Play again?"; // reset's button
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random(); // randomly creates computer's choice
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
function compare(choice1, choice2) { //compares user's choice and computer's choice
if (choice1 === choice2) {
return "The result is a tie!";
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "Rock Wins!";
} else {
return "Paper Wins!";
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
return "Paper Wins!";
} else {
return "Scissors win!";
}
} else if (choice1 === "scissors") {
if (choice2 === "paper") {
return "Scissors win!";
} else {
return "Rock wins!";
}
}
}
document.getElementById("choice").innerHTML = // prints user and computer selections
"<pre>" +
"Player: " + userChoice + "\r" +
"Computer: " + computerChoice +
"</pre>";
document.getElementById("result").innerHTML = // prints result of selection comparisons
(compare(userChoice, computerChoice));
}
document.getElementById("start").onclick = startGame;
<h1>Rock, Paper, Scissors Game!</h1>
<button id="start">Wanna Play?</button>
<p id="choice"></p>
<p id="result"></p>
1- Use http://jsbeautifier.org/ to clean up your js code, you are mixing Spaces and Tabs. Also it will clean your code alignment.
2- return prompt("Do you choose rock, paper or scissors?");
will always return before any code get's executed.
3- You are calling startGame() from the button click right? then why you are calling it again from inside the function it self?
Which indicates that you have a missing closing bracket } for the function.
var userChoice = startGame();

I'm having trouble with the syntax for my compare function for javascript

I've included a screenshot image of a codeacademy error I made today. I'm trying to create a compare function that randomly picks a number between 0 and 1 (paper, scissors, or rock) that inputs two choices and returns the winner based on how choice1 compares to choice2.
The first part is a comment, but it explains how the original paper scissors rock function was built
Here is the code:
/*var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}*/
var compare = function (choice1, choice2) {if (choice1 === choice2) return("The result is a tie!");
if (choice1 < 0.34)
if(choice2 ==="scissors");
return("rock wins");
} else if(choice2 ==="paper");{
return("paper wins");
};
};
It's telling me that there's an unexpected token else on line 15 (the else if line)
When I erase the else part it gives me another syntax error saying the same thing about a token if. I'm stuck on what part of my syntax is off and how to fix it.
I have a feeling it has something to do with === and the ; after the if() statements, either way, here is a nicer way of comparing them.
function compare(a,b)
{
if(a==b)return "draw";
switch(a)
{
case "rock":return (b=="scissors"?a:b)+" wins";
case "paper":return (b=="rock"?a:b)+" wins";
case "scissors":return (b=="paper"?a:b)+" wins";
}
}
console.log(compare("scissors","paper"));
function compare(choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
if (choice1 < 0.34) {
if (choice2 === "scissors") {
return "rock wins";
} else if (choice2 === "paper") {
return "paper wins";
}
}
}
Check the comments on semicolon related errors below.
var compare = function (choice1, choice2) {
if (choice1 === choice2) return("The result is a tie!");
if (choice1 < 0.34) {
if(choice2 === "scissors") { // remove ; here
return("rock wins");
} else if (choice2 === "paper") { // remove ; here
return("paper wins");
} // remove ; here
} // add another else => what happens when choice1 >= 0.34 (not a rock)
};
With the required else blocks the complete function would look like:
var compare = function (choice1, choice2) {
if (choice1 === choice2) return("The result is a tie!");
if (choice1 < 0.34) { // rock
if(choice2 === "scissors") {
return("rock wins");
} else if (choice2 === "paper") {
return("paper wins");
}
} else if (choice <= 0.67) { // paper
if(choice2 === "rock") {
return("paper wins");
} else if (choice2 === "scissors") {
return("scissors wins");
}
} else { // scissors
if(choice2 === "paper") {
return("scissors wins");
} else if (choice2 === "rock") {
return("rock wins");
}
}
};
EDIT
This is just to help you overcome the confusion over semicolons if any. Usually a function definition is not required to have a ; after its body completes by putting the last closing curly brace }.
function compare (choice1, choice2) {
// ...
}
On the contrary, when we assign a variable a value, the statement is terminated by a semicolon.
var name = "John Doe";
Hence, when we combine the two, we're defining a function and then using it in an assignment statement which needs to be closed by using a semicolon. Hence, the syntax:
var compare = function (choice2, choice2) {
// ...
};

Categories

Resources