I have been working on a “Rock Paper Scissors” game to see if I understand the basics of JavaScript. It all works well until I get to the if statement from lines 30 to 71 in the fight()
: I have adjusted the reply variable to indicate how it may be “if’ing” through. It seems to be returning the default value of every sub “if” in the overall “if”. Am I using the wrong variable for the secondary condition maybe?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/xml; charset=utf-8" />
<title>radioGroup.html</title>
<link rel = "stylesheet"
type = "text/css"
href = "radioGroup.css" />
<script type = "text/javascript">
//<![CDATA[
// from radioGroup.html
function fight(){
var randomChoice = Math.random();
var threeChoice = Math.floor (randomChoice * 3);
var weapon = document.getElementsByName("weapon");
for (i = 0; i < weapon.length; i++){
currentWeapon = weapon[i];
if (currentWeapon.checked){
var selectedWeapon = currentWeapon.value;
} // end if
} // end for
var cpuChoice = new Array("Paper", "Rock", "Scissors")
var reply = "xxx"
if (threeChoice === 0) {
if (weapon === "Paper") {
reply = "11";
}
else if (weapon === "Rock") {
reply = "12";
}
else if (weapon === "Scissors") {
reply = "13";
}
else {
reply = "what1";
}
}else if (threeChoice === 1) {
if (weapon === "Paper") {
reply = "21";
}
else if (weapon === "Rock") {
reply = "22";
}
else if (weapon === "Scissors") {
reply = "23";
}
else {
reply = "what2";
}
}else if (threeChoice === 2) {
if (weapon === "Paper") {
reply = "31";
}
else if (weapon === "Rock") {
reply = "32";
}
else if (weapon === "Scissors") {
reply = "33";
}
else {
reply = "what3";
}
}else {
reply = "hay now?";
}
var output = document.getElementById("output");
var response = "<h2>You have chosen ";
response += selectedWeapon + "<h2>The CPU has chosen ";
"<\\/h2> \
";
response += cpuChoice[threeChoice] + "<\\/h2> \
";
response += reply + "<\\/h2> \
";
output.innerHTML = response;
} // end function
//]]>
</script>
</head>
<body>
<h1>Choose!</h1>
<form action = "">
<fieldset>
<input type = "radio"
name = "weapon"
id = "radPaper"
value = "Paper"
checked = "checked" />
<label for = "radPaper">Paper</label>
<input type = "radio"
name = "weapon"
id = "radRock"
value = "Rock" />
<label for = "radRock">Rock</label>
<input type = "radio"
name = "weapon"
id = "radScissors"
value = "Scissors" />
<label for = "radScissors">Scissors</label>
<button type = "button"
onclick = "fight()">
fight the dragon
</button>
</fieldset>
</form>
<div id = "output">
</div>
</body>
</html>