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:
JavaScript
x
9
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<script src="Rock Paper Scissors.js"></script>
5
</head>
6
<body>
7
<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"/>
8
</p>`
9
And here’s the JavaScript:
JavaScript
1
34
34
1
var userChoice = prompt("Do you choose rock, paper or scissors?","Don't use articles (i.e. the, a, etc.)").toLowerCase();
2
3
var computerChoice = Math.random();
4
5
if (computerChoice < 0.34) {
6
computerChoice = "rock";
7
} else if(computerChoice <= 0.67) {
8
computerChoice = "paper";
9
} else {
10
computerChoice = "scissors";
11
}
12
13
function userImgDisplay() {
14
var image = document.getElementById('myImage');
15
if (userChoice = "rock") {
16
image.src = "rock.png";
17
}else if (userChoice = "paper") {
18
image.src = "paper.png";
19
}else if (userChoice = "scissors") {
20
image.src = "scissors.png";
21
}
22
}
23
24
function comImgDisplay() {
25
var image = document.getElementById('myImage');
26
if (computerChoice = "rock") {
27
image.src = "rock.png";
28
}else if (computerChoice = "paper") {
29
image.src = "paper.png";
30
}else if (computerChoice = "scissors") {
31
image.src = "scissors.png";
32
}
33
}
34
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.
JavaScript
1
11
11
1
function comImgDisplay() {
2
var image = document.getElementById('myImage');
3
if (computerChoice == "rock") {
4
image.src = "rock.png";
5
}else if (computerChoice == "paper") {
6
image.src = "paper.png";
7
}else if (computerChoice =="scissors") {
8
image.src = "scissors.png";
9
}
10
}
11
For simplicity you could just do this:
JavaScript
1
5
1
function comImgDisplay() {
2
var image = document.getElementById('myImage');
3
image.src = computerChoice + ".png";
4
}
5