Why is this only giving me the computer's output? - javascript

<html>
<head></head>
<body><center><div id="output" style="width:500px; height:500px; background-color:blue;"></div></center></body>
<script>
var printOut = function(text) {
var output = document.getElementById("output");
output.innerHTML = text;
};
var userChoice = prompt("Do you choose Rock, Paper, or Scissors?")
console.log(printOut("You chose " + userChoice + "."));
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Rock";
} else if (computerChoice <= 0.67) {
computerChoice = "Paper";
} else {
computerChoice = "Scissors";
}
console.log(printOut("The computer chooses " + computerChoice + "."));
var compareChoice = function(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return "The result is a tie!";
}
if (userChoice === "Rock") {
if (computerChoice === "Scissors") {
return "Rock smashes Scissors!";
} else {
return "Paper covers Rock!";
}
}
if (userChoice === "Paper") {
if (computerChoice === "Rock") {
return "Paper covers Rock!";
} else {
return "Scissors cut Paper!"
}
}
if (userChoice === "Scissors") {
if (computerChoice === "Paper") {
return "Scissors cut Paper!";
} else {
return "Rock smashes Scissors!";
}
}
return console.log(printOut(compareChoice(userChoice, computerChoice)));
};
</script>
</html>
When I open this in the browser and type in my choice, It only tells me the computer's choice when it should tell mine, the computer's and the end result.
I think it has something to do with my tag, but I'm not sure.

Actually, your choice was also printed in the output area. It just gets replaced by the computer's choice. Try modifying your printOut method to be like this:
var printOut = function(text) {
var output = document.getElementById("output");
output.innerHTML += text;
};

Related

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());

JavaScript SyntaxError: Unexpected token else

I have this code for a rock, paper, scissors game that is basically homework. I have double-checked and it seems to be fine, however, when I run it it says:
SyntaxError: Unexpected token else,
any help will be very appreciated :) Please note that I am a newbie, so if the question is dumb, please be nice and help <3
I just edited the code a bit, since I had many "Overlook" mistakes. I also wanted to clarify that I need all the code located after the function statement to be inside the function, that is why I don't close the first { right away.
PD: Now I get: SyntaxError: Unexpected token =
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("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 if (choice1 ==== "paper") {
if (choice2 === "rock") {
return "paper wins";
else if (choice2 === "scissors") {
return "scissors wins"; }
else {
return "Paper wins"; }
}
}
}
compare(userChoice, computerChoice)
Ok, to stay true to your homework, I kept the same format just fixed the issues.
here it is:
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("Computer: " + computerChoice);
var compare = function(choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
if (choice1 === "paper") {
if (choice2 === "rock") {
return "Paper wins!";
} else {
return "Paper looses!";
}
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "Rock wins!";
} else {
return "Rock looses!";
}
}
if (choice1 === "scissors") {
if (choice2 === "paper") {
return "Scissors wins!";
} else {
return "Scissors looses!";
}
}
}
compare(userChoice, computerChoice)
Consider re-writing it in a little easier way.
See fiddle https://jsfiddle.net/DIRTY_SMITH/c7ww2hmz/1/
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";
}
alert("the computer picked " + computerChoice);
if ((computerChoice === "rock" && userChoice === "papper") || (computerChoice === "papper" && userChoice === "scissors") || (computerChoice === "scissors" && userChoice === "rock")) {
alert("you won");
} else if (computerChoice == userChoice) {
alert("It's a tie");
} else {
alert("you loose");
}
You will find your debugging much easier if you
properly indent,
use braces for any but the simplest if statements
For example:
if (choice1 == choice2) return "tie"; /* simple 1-line if is ok */
if (choice1 == "rock") {
if (choice2 == "scissors") { /* more complex, always use braces */
return "rock wins"; /* always indent nicely */
} else {
return "paper wins";
}
}
/* ... and so on ... */
Always properly format your code. You are missing a bunch of } before the else statements. Always use semi-colons at the end of a line (no, you don't technically need to be it is extremely good practice).
Also, you need to watch your equals. You had one ==== instead of ===
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("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 if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
} else if {
return "paper wins";
} else {
return "Paper wins";
}
}
}
}
compare(userChoice, computerChoice)

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();

Run outside variable from inside a function

if result is tie i need to run this code again by asling "Do you choose rock, paper or scissors?"
but there's a wrong with this code.
after this Massage "The result is a tie! Would you like to play new game?(yes or no)", i used "compare(userChoice, computerChoice);" to run again this code. its not working.
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("Computer: " + computerChoice);
var compare = function(choice1, choice2)
{
if (choice1 === choice2) {
var newChoice = prompt ("The result is a tie! Would you like to play new game?(yes or no)");
if ( newChoice === "yes"){
compare(userChoice, computerChoice);
}
else {
return "Have a nice day!";
}
}
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 ("scissors wins");}
else {return (" rock wins");}
}
};
compare(userChoice, computerChoice);
Well yes, that's because you call again
compare(userChoice, computerChoice);
at the forth line inside compare function.
try this:
var choices = ['rock', 'paper', 'scissors'];
var makeRandom = function() {
return parseInt(Math.random()*3);
}
function game() {
var userChoice = prompt("Do you choose rock, paper or scissors?");
var index = choices.indexOf(userChoice);
if(index === -1) {
var bl = confirm('Your choice is outof range, would you like to play Again?');
if(bl) game();
}
var computerChoice = makeRandom();
if(index === computerChoice) {
var bl = confirm('It is a tie, would you like to play Again?');
if(bl) { game(); }
} else if((index === 0 && computerChoice === 1) || (index === 1 && computerChoice === 2) || (index === 2 && computerChoice === 0)) {
alert('you loose');
} else {
alert('you win');
}
}
game();

Displaying return as text

I have some functions and some variables. I would like to return a variable and the function outcome as text on my browser.
What I have done is I have made a HTML file with the text:
<SCRIPT SRC="rockpaper.js">
</SCRIPT>
And this refers to this javascript file:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Computer chooses rock";
} else if(computerChoice <= 0.67) {
computerChoice = "Computer chooses paper";
} else {
computerChoice = "Computer chooses scissors";
}
console.log(computerChoice);
var compare = function(choice1,choice2)
{
if(choice1===choice2)
{
return("The result is a tie!");
}
if(choice1==="Computer chooses rock")
{
if(choice2==="scissors")
{
return("rock wins");
}
else
{
return("paper wins");
}
}
if(choice1==="Computer chooses paper")
{
if(choice2==="rock")
return("paper wins");
else
{
return("scissors wins");
}
}
if(choice1==="Computer chooses scissors")
{
if(choice2==="rock")
{
return("rock wins");
}
else
{
return("scissors wins");
}
}
}
console.log(compare(computerChoice,userChoice))
However, when I open it with a browser, the text doesn't display, but the prompt does.
It works fine in Codecademy, though.
Here is a jsFiddle that logs data to the screen. I noticed your tie logic is flawed. You are cheking a big-ass string to the users simple one-word string. You need to tokenize; extract the state from the computer choice string.
Javascript
// Helpful utility function...
function logResultToScreen(result) {
var block = document.createElement('div');
var text = document.createTextNode(result);
var output = document.getElementById('output');
block.appendChild(text);
output.insertBefore(block);
}
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Computer chooses rock";
} else if (computerChoice <= 0.67) {
computerChoice = "Computer chooses paper";
} else {
computerChoice = "Computer chooses scissors";
}
console.log(computerChoice);
logResultToScreen(computerChoice);
var compare = function (choice1, choice2) {
var tokens = choice1.split(' ');
if (tokens[2] === choice2) {
return ("The result is a tie!");
}
if (choice1 === "Computer chooses rock") {
if (choice2 === "scissors") {
return ("rock wins");
} else {
return ("paper wins");
}
}
if (choice1 === "Computer chooses paper") {
if (choice2 === "rock") {
return ("paper wins");
} else {
return ("scissors wins");
}
}
if (choice1 === "Computer chooses scissors") {
if (choice2 === "paper") {
return ("scissors wins");
} else {
return ("rock wins");
}
}
}
var output = compare(computerChoice, userChoice);
logResultToScreen(output);
console.log(output);
HTML
<div id="output"><strong>Results:</strong></div>
Your using console.log() so you should see output in the developer console (press F12 and open console tab).
To put it on the page, you have to create a DOM(html) element and add it to the page.
<SCRIPT SRC="rockpaper.js">
</SCRIPT>
<div id="container"></div>
in your script replace
console.log(compare(computerChoice,userChoice))
with
var container = document.getElementById("container");
container.innerHTML = compare(computerChoice,userChoice);
Happy coding!

Categories

Resources