I’m trying to build a Rock Paper Scissors game in JavaScript, but also have it where the computer outputs images to the HTML document. I’ve tried everything I know, and it won’t work. Here’s the HTML:
<!DOCTYPE html> <html> <head> <script src="Rock Paper Scissors.js"></script> </head> <body> <p>Your choice:<img id="myImage" onafterprint="userImgDisplay()" src="blank.png" width="250px" height="250px"/>The computer's choice:<img id="myImage" onload="comImgDisplay()" src="blank.png" width="250px" height="250px"/> </p>`
And here’s the JavaScript:
var userChoice = prompt("Do you choose rock, paper or scissors?","Don't use articles (i.e. the, a, etc.)").toLowerCase(); var computerChoice = Math.random(); if (computerChoice < 0.34) { computerChoice = "rock"; } else if(computerChoice <= 0.67) { computerChoice = "paper"; } else { computerChoice = "scissors"; } function userImgDisplay() { var image = document.getElementById('myImage'); if (userChoice = "rock") { image.src = "rock.png"; }else if (userChoice = "paper") { image.src = "paper.png"; }else if (userChoice = "scissors") { image.src = "scissors.png"; } } function comImgDisplay() { var image = document.getElementById('myImage'); if (computerChoice = "rock") { image.src = "rock.png"; }else if (computerChoice = "paper") { image.src = "paper.png"; }else if (computerChoice = "scissors") { image.src = "scissors.png"; } }
The “rock.png”, “paper.png”, and “scissors.png” are based on their respective items, and “blank.png” is just a transparent image. This program will always display “rock.png” for my choice and nothing for the computer’s. What am I doing wrong?
Advertisement
Answer
Your logic is not right, you are using =
where it should be ==
For example look at my changes to this method, you have issues like this in all your methods.
function comImgDisplay() { var image = document.getElementById('myImage'); if (computerChoice == "rock") { image.src = "rock.png"; }else if (computerChoice == "paper") { image.src = "paper.png"; }else if (computerChoice =="scissors") { image.src = "scissors.png"; } }
For simplicity you could just do this:
function comImgDisplay() { var image = document.getElementById('myImage'); image.src = computerChoice + ".png"; }