Javascript not running - no error message - javascript

I've set up this rock, paper scissors game. However, the Javascript is not running and I'm not receiving any errors. Any suggestions?
function play(humanScore) {
var computerScore = getcomputerScore();
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
human++
} else if (computerScore == "paper") {
computer++
}
} else if (humanScore == "scissors") {
if (computerScore == "scissors") {
} else if (computerScore == "paper") {
human++
} else if (computerScore == "rock") {
computer++
}
} else if (humanScore == "paper") {
if (computerScore == "paper") {
} else if (computerScore == "scissors") {
computer++
} else if (computerScore == "rock") {
human++
}
}
}
function getcomputerScore() {
var randomplay = ["rock", "paper", "scissors"];
var play = randomplay[Math.floor(Math.random() * myArray.length)];
return play
}
This is the code setting up humanScore:
var human = 0;
var computer = 0;
document.getElementById("rock").onClick = pickRock;
document.getElementById("scissors").onClick = pickScissors;
document.getElementById("paper").onClick = pickPaper;
function pickRock() {
play("rock");
}
function pickScissors() {
play("scissors");
}
function pickPaper() {
play("paper");
}

The name of the property is onclick, not onClick; note the lowercase c.
There’s at least one other error (myArray.length, as #RobG points out), but this will make them actually throw.

Probably better suited to a code review section, but here goes…
function play(humanScore) {
var computerScore = getcomputerScore();
variables humanScore and computerScore aren't actually scores, they are symbols the players have chosen to play, so the variables might be better as humanChoice and computerChoice. This also means that the globals human and computer can be better named as humanScore and computerScore.
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
Rather than leaving a blank block, better to either insert a comment to say "no adjustment". Better to test equivalent choices up front, then you're left with binary choices, so you can do something like:
var humanScore = 0;
var computerScore = 0;
function play(humanChoice) {
// IE tends to play with capitalisation of values
humanChoice = humanChoice.toLowerCase();
var computerChoice = getComputerChoice();
// If same choice, no change of score
if (computerChoice == humanChoice) {
return;
}
// Only binary win/lose choices left
if (humanChoice == 'rock') {
computerChoice == 'paper'? ++computerScore : ++humanScore;
} else if (humanChoice == 'paper') {
computerChoice == 'scissors'? ++computerScore : ++humanScore;
} else if (humanChoice == 'scissors') {
computerChoice == 'rock'? ++computerScore : ++humanScore;
}
}
There was an error in this function too:
function getComputerChoice() {
var choices = ['rock','paper','scissors'];
return choices[Math.random()*choices.length | 0];
}
Lastly, make sure the buttons are in the page before adding the listener, and make sure the property names have the correct case (it doesn't matter for HTML attributes, but it does for javascript property names):
window.onload = function() {
document.getElementById("rock").onclick = pickRock;
document.getElementById("scissors").onclick = pickScissors;
document.getElementById("paper").onclick = pickPaper;
}

Related

How do add a reset button to a Rock Paper Scissors game?

I'm learning JavaScript and having an issue trying to make a reset button for my game.
Im assuming the way I have coded it has scope tripping me up. any pointers would help immensely.
I have tried but the best i managed was to make the current score say 0 upon clicking the button, but if rock, paper or scissors were selected again, the score would jump straight back to where it was before + the result of the current round.
here is my code:
let userScore = 0;
let computerScore = 0;
let choice = document.querySelector("#selections");
choice.addEventListener("click", event => {
if (event.target.nodeName == "BUTTON") {
let playerSelecion = (event.target.textContent);
let computerSelection = getCompChoice();
document.getElementById("player").innerHTML = playerSelecion;
document.getElementById("computer").innerHTML = computerSelection;
playRound(playerSelecion, computerSelection);
}
});
function playRound(playerSelecion, computerSelection) {
if (playerSelecion === computerSelection) {
document.getElementById("currentRound").innerHTML = ("tie");
} else if (playerSelecion === "rock" && computerSelection === "scissors") {
userScore++;
document.getElementById("currentRound").innerHTML = ("you win rock beats scissors");
} else if (playerSelecion === "paper" && computerSelection === "rock") {
userScore++
document.getElementById("currentRound").innerHTML = ("you win paper beats rock")
} else if (playerSelecion === "scissors" && computerSelection === "paper") {
userScore++
document.getElementById("currentRound").innerHTML = ("you win scissors beats paper")
} else if (playerSelecion === "paper" && computerSelection === "scissors") {
computerScore++
document.getElementById("currentRound").innerHTML = ("you lose scissors beats paper")
} else if (playerSelecion === "rock" && computerSelection === "paper") {
computerScore++
document.getElementById("currentRound").innerHTML = ("you lose paper beats rock")
} else if (playerSelecion === "scissors" && computerSelection === "rock") {
computerScore++
document.getElementById("currentRound").innerHTML = ("you lose rock beats scissors")
} if (userScore >= 5) {
document.getElementById("result").innerHTML = "You win";
} else if (computerScore >= 5) {
document.getElementById("result").innerHTML = "Computer wins";
}
document.getElementById("userScore").innerHTML = userScore;
document.getElementById("compScore").innerHTML = computerScore;
}
function getCompChoice() {
let a = Math.random();
if (a < 0.34) {
return "rock";
} else if (a <= 0.67) {
return "paper";
} else {
return "scissors";
}
}```
To avoid the previous results to be added with the new score, the scores should be set to 0 in your reset button too.
//create a reset button
<button onclick="resetScore()"> Reset The Game </button>
//reset function
const reset = () => {
useScore = 0;
computerScore = 0;
document.querySelector("#userScore").innerHTML = userScore;
document.querySelector("#compScore").innerHTML = computerScore;
}
I think you want a reset button in your game that should set user and comp score to "0".
You can make a button and add some reset code to that so that when someone clicks on the button the game will reset the user and comp score to "0":
//adding a reset button
<button onclick="reset()">Reset</button>//remember to put () here
//normal function
function reset(){
document.getElementById("userScore").innerHTML = 0;
document.getElementById("compScore").innerHTML = 0;
}
//with arrow function
let reset=()=>{
document.getElementById("userScore").innerHTML = 0;
document.getElementById("compScore").innerHTML = 0;
}

Ties are still running win messages?

I've been messing around with a rock, paper scissors project that codecademy gets you to try, I'm pretty happy with it but I have one problem! When the result is a tie, it logs the tie message (perfect!) but also logs the win message linked with the result!
How do I get it to ONLY log the tie message?
Here's the code:
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === "rock" || userInput === "paper" || userInput === "scissors" || userInput === "gun") {
return userInput;
} else {
console.log(`Sorry! But ${userInput} is an illegal weapon in the bloodythirsty sport of Rock, Paper, Scissors!`)
}
}
const getComputerChoice = () => {
const ranNum = Math.floor(Math.random() * 3);
switch (ranNum) {
case 0:
return "rock";
case 1:
return "paper";
case 2:
return "scissors";
}
};
const determineWinner = (getUserChoice, getComputerChoice) => {
if (getComputerChoice === getUserChoice) {
console.log("It seems it's a tie! You've matched wits!");
}
if (getUserChoice === "rock") {
if (getComputerChoice === "paper") {
return "The computer wins! It has gift wrapped your weapon.";
} else {
return "You beat the computer! They immediately begin crafting bigger scissors.";
}
}
if (getUserChoice === "paper") {
if (getComputerChoice === "scissors") {
return "The computer wins! They claim arts and crafts time as a reward."
} else {
return "You beat the computer! Their puny stone was no match for your paper aeroplane to the eye!"
}
}
if (getUserChoice === "scissors") {
if (getComputerChoice === "rock") {
return "The computer wins! You won't be cutting straight lines any time soon..."
} else {
return "You beat the computer! You cause emotional damage by destroying their robot child's drawing. You're a monster."
}
}
if (getUserChoice === "gun") {
if (getComputerChoice === "rock" || getComputerChoice === "paper" || getComputerChoice === "scissors") {
return "You win. But at what cost?"
}
}
if (getUserChoice === undefined) {
return "Come back when you're ready to take this game seriously."
}
}
//Enter your choice below in getUserChoice brackets
const playGame = () => {
let userChoice = getUserChoice("rock");
let computerChoice = getComputerChoice();
if (userChoice !== undefined) {
console.log(`You have chosen ${userChoice} as your weapon.`);
}
if (userChoice !== undefined) {
console.log(`The computer has brought ${computerChoice} to a ${userChoice} fight.`);
}
console.log(determineWinner(userChoice, computerChoice))
}
playGame();
Instead of logging the tie message, you should return it, leaving the logging to the caller:
if (getComputerChoice === getUserChoice) {
return "It seems it's a tie! You've matched wits!";
}

alert() not working in function

Added buttons to my rock paper scissors game, I was having trouble making the alert show up after the userChoice variable changes, so I used eventListeners for that and the winner stopped showing up with the alert, why is this happening? Is there a better way to do this?
I'm a beginner any help is appreciated.
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){} //picks a random nb and makes it rock paper...
let userChoice;
function userPlay (){
btnRock.addEventListener("click", ()=>{
userChoice="rock";
return userChoice;
});
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
return userChoice;
});
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
return userChoice;
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
theGame(compPlay(),userPlay());
</script>
</html>
The function call will happen during the load of the script.At that time, the compPlay function will return a value whereas the userPlay function will create the elements. Thereafter when the button click is happening, the function will not even be called.
Edit:For your info..This is one way to do it
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){
let comChoice= Math.random();
console.log(comChoice);
if (comChoice<=0.33){
comChoice= "rock";
} else if (comChoice<=0.66){
comChoice= "scissors";
} else {
comChoice= "paper";
}
userPlay(comChoice);
}
let userChoice;
function userPlay (comChoice){//Function for user's click comparison with computer's option
let btnRock = document.createElement("button");
let tRock = document.createTextNode("Rock");
btnRock.appendChild(tRock);
document.body.appendChild(btnRock);
btnRock.addEventListener("click", ()=>{
userChoice="rock";
theGame(comChoice,userChoice);//Main function call to decide the winner
});
let btnPaper = document.createElement("button");
let tPaper = document.createTextNode("Paper");
btnPaper.appendChild(tPaper);
document.body.appendChild(btnPaper);
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
theGame(comChoice,userChoice);
});
let btnScissors = document.createElement("button");
let tScissors = document.createTextNode("Scissors");
btnScissors.appendChild(tScissors);
document.body.appendChild(btnScissors);
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
compPlay();//Basic initialising function call
</script>
</html>
You could call the game function when you click on a button
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
EDIT:
I forgot to said that in order to work to you should change your comChoice to a Global variable.Thanks #Krisna Prashatt

Adding an Image to HTML Based on Outcome of If/Else (innerHTML? DOM?)

I'm doing a basic rock paper scissors game in Javascript, nothing new but I'm trying to fancy it up a little. All of the ones I see just output what the computer selected in plain text via innerHTML and that's fine but I want it to show an image based on what they selected.
The basic game function playGame passes the choice into a compareChoices function. Instead of passing "The computer chose: rock" into my span id="result" I would like to pass an image. I've been reading about DOM and nodes and stuff but I'm having difficulty understanding how to apply it here.
Let's assume I have an image named rock.gif that I want to pass to the result span when the computer selects "rock". How do I do it? If it involves using DOM and not innerHTML please help me to understand and explain a little what is going on. Thanks!
function playGame(userSelect)
{
userOption = userSelect;
var computerSelection = Math.random();
if (computerSelection < 0.34)
{
computerSelection = "rock";
}
else if (computerSelection <= 0.67)
{
computerSelection = "paper";
}
else
{
computerSelction = "scissors";
}
results = compareChoices(userOption, computerSelection);
document.getElementById("result").innerHTML = "<p>The computer chose " +
computerSelection;
document.getElementById("whoWon").innerHTML = results;
}
function compareChoices(userOption, computerSelection)
{
if (userOption == computerSelection)
{
return "It's a tie!";
}
if (userOption == "rock")
{
if (computerSelection == "scissors")
{
return "You win!";
}
else
{
return "You lose!";
}
} else if (userOption == "paper") {
if (computerSelection == "rock")
{
return "You win!" ;
} else if("scissors") {
return "You lose!" ;
}
} else if (userOption == "scissors") {
if (computerSelection == "rock")
{
return "You lose!";
}else{
return "You win!";
}
}
}
HTML
<span id="result"></span>
Ok, so I slimmed down your code to only what I needed.
Basically put an empty image tag on the page and then set the src with the javascript. Take a looks and let me know if there is anything you dont understand. You will have to right click and inspect the image to see the src, until you have th eimages in your project.
user = 0.64;
playGame(user);
function playGame(userSelect) {
userOption = userSelect;
var computerSelection = Math.random();
if (computerSelection < 0.34) {
computerSelection = "rock.gif";
} else if (computerSelection <= 0.67) {
computerSelection = "paper.gif";
} else {
computerSelection = "scissors.gif";
}
document.getElementById("result").innerHTML = "<p>The computer chose " +
computerSelection;
document.getElementById("image").src = computerSelection;
}
<img id="image" src="">
<span id="result"></span>
<span id="whoWon"></span>
Replace the span with the following html:
<img alt="Outcome" id="result">
And update your code so it
function playGame(userSelect) {
userOption = userSelect;
var computerSelection = Math.random();
if (computerSelection < 0.34) {
document.getElementById("result").setAttribute("src", "rock.gif");
} else if (computerSelection <= 0.67) {
computerSelection = "paper"; //do same here
} else {
computerSelction = "scissors"; //and here
}
}

Noobish JavaScript Nested If-Else Statement Help/Advice/Pointers/YouNameIt

I just started learning JavaScript (Today actually) and I'd really appreciate some help with nested if-else statements. I thought I'd write a simple program to practice, and it seems that every if-else statement in my if blocks executes regardless of which parameter I put in. Any pointers or even things you notice that aren't germane to the problem at hand are appreciated. Thanks again. My code is below.
EDIT: I've gotten it now, and learned the error of my ways. Thanks to everyone who commented and gave advice so quickly.
var playerOne = prompt('Choose rock, paper, or scissors');
var playerTwo = prompt('Choose rock, paper, or scissors');
var fight = function (playerOne, playerTwo)
{
if( playerOne == 'rock' || 'Rock')
{
if (playerTwo == 'paper' || 'Paper')
{
alert('Player Two Wins!');
}
else if (playerTwo == 'rock' || 'Rock')
{
alert('Tie!');
}
else
{
alert('Player One wins!');
}
}
if(playerOne == 'paper' || 'Paper')
{
if (playerTwo == 'paper' || 'Paper')
{
alert('Tie!');
}
else if (playerTwo == 'rock' || 'Rock')
{
alert('Player One Wins!');
}
else
{
alert('Player Two wins!');
}
}
if (playerOne == 'scissors' || 'Scissors')
{
if (playerTwo == 'paper' || 'Paper')
{
alert('Player One Wins!');
}
else if (playerTwo == 'rock' || 'Rock')
{
alert('Player Two Wins!');
}
else
{
alert('Tie!');
}
}
};
fight(playerOne, playerTwo);
As several people have pointed out, your if statements need to be in the form of:
if (playerOne == 'paper' || playerOne == 'Paper')
or the more succinct:
if (playerOne.toLowerCase() == 'paper')
The problem is that playerOne == 'paper' || 'Paper' will always return a "Truthy" value (see http://11heavens.com/falsy-and-truthy-in-javascript for more detail on Truthy and Falsy values).
As an aside, while there's absolutely nothing wrong with multiple if statements, if I were coding this exercise my way would involve less if statements (and look a little like this:
var playerOne = prompt('Choose rock, paper, or scissors');
var playerTwo = prompt('Choose rock, paper, or scissors');
var fists = {
"rock": {
"beats": "scissors",
"loses": "paper"
},
"paper": {
"beats": "rock",
"loses": "scissors"
},
"scissors": {
"beats": "paper",
"loses": "rock"
}
}
var fight = function (playerOne, playerTwo) {
playerOne = playerOne.toLowerCase();
playerTwo = playerTwo.toLowerCase();
if (fists[playerOne] === undefined || fists[playerTwo] === undefined) {
alert('Someone threw an unknown fist!');
} else if (fists[playerOne].beats === playerTwo) {
alert('Player One wins!');
} else if (fists[playerTwo].beats === playerOne) {
alert('Player Two Wins!');
} else {
alert('Tie!');
}
};
fight(playerOne, playerTwo);
By objectifying the rock/paper/scissors combinations, the code is IMO significantly easier to read.
The other comments and answer are great, so I won't repeat what they said. But you asked for advice, and mine is to not use so many if statements to begin with. A big part of programming is learning how to cut down on unnecessary or repeated code. Data structures like objects and arrays are good for this:
var win_conditions = { //simple object showing which hands beat which
'rock': 'scissors',
'paper': 'rock',
'scissors': 'paper'
}
var fight = function(p1, p2) {
var result;
if (!win_conditions.hasOwnProperty(p1) || !win_conditions.hasOwnProperty(p2)) {
result = false; //error! user typed something invalid
} else {
if (win_conditions[p1] == p2) {
result = 'Player One wins!';
} else if (win_conditions[p2] == p1) {
result = 'Player Two wins!';
} else {
result = 'Tie!';
}
}
return result;
}
var fight_result = false;
var prompt_text = 'Choose rock, paper, or scissors';
var playerOne = prompt(prompt_text);
var playerTwo = prompt(prompt_text);
//keep asking until the user types a valid option
while (!fight_result) {
fight_result = fight(playerOne.toLowerCase(), playerTwo.toLowerCase());
}
alert(fight_result);
I recommend you to use FireBug to debug your JavaScript Code. When you debug your code change the alert() to console.log() and probably playerOne/playerTwo to simple strings.
(Doesn't fit your question perfectly, but if you continue learning it's a good advice overall.)

Categories

Resources