Reputation:
I just recently got into HTML/CSS and Javascript. I am making a website for a rock paper scissors game but first wanted to make sure that the code I had written for the game worked (I'm using JSbin to run it for now). The javascript worked fine when I had the input using prompt(). I then looked around to find a way to make it so that people could type their choice into a box and then have that be the input. My current HTML code looks like this:
<!DOCTYPE hmtl>
<html>
<center>
<title>Rock Paper Scissors</title>
<p1>Welcome to <em>JavaScript</em> Rock-Paper-Scissors! Please type your choice and press continue</p>
<input type="text" id="input"/>
<button onclick="game();">Go!</button>
</center>
</html>
My javascript looks like this:
var input = document.getElementById("input").value;
var userChoice = input.toLowerCase();
var cpuChoice = Math.random();
if (cpuChoice < 0.34) {
cpuChoice = "rock";
}
else if (cpuChoice <= 0.67) {
cpuChoice = "paper";
}
else {
cpuChoice = "scissors";
}
var compare = function(choice1, choice2) {
if (choice1 === choice2) {
confirm("It's a tie!");
}
else if (choice1 === "rock") {
if (choice2 === "scissors") {
confirm("You Win!");
}
else {
confirm("You lost");
}
}
else if (choice1 === "paper") {
if (choice2 === "rock") {
confirm("You Win!");
}
else {
confirm("You lost");
}
}
else if (choice1 === "scissors") {
if (choice2 === "paper") {
confirm("You Win!");
}
else {
confirm("You lost");
}
}
else {
confirm("I'm sorry, that isn't an option. Please try again");
}
};
compare(userChoice, cpuChoice);
I ran the javascript through JSHint and fixed all the errors that It pointed out, put it back into JSbin but it still didn't work. I'm sure that I'm making a really stupid mistake but any help would be greatly appreciated.
Upvotes: 0
Views: 154
Reputation: 61083
As you can see, your code works fine assuming your function is named properly.
http://jsfiddle.net/isherwood/R5GmH/
I've added the following:
function game() {
....
}
Also note that the fiddle is set to load the script in the document head.
P.s. This might work better with a select box: http://jsfiddle.net/isherwood/R5GmH/4
In response to your comment:
<head>
<link rel="stylesheet" type="text/css" href="my-css-file.css"></link>
<script src="my-js-file.js"></script>
</head>
This assumes that all 3 files are in the same directory. Read up on relative URL paths for other scenarios.
Upvotes: 1