Compare generated letter with user input - javascript

My problem is as followed: I want to realise a (really) small application in which I want to generate a letter (between A and E) and compare it with the user input made afterwards. If the user input is not the same as the generated letter a message should pop up, which tells the user that he made the wrong choice. If the user made the right choice, a counter gets +1 and if the user reaches at least 3 of 5 points, he wins a prize. The user has 3 tries before the script ends.
The hurdle is that my main focus lies on php. My knowledge in JavaScript is not that much.
So my script won't do anything when the user types his answer in.

SOLVED!
The Code beneath is the solution.
String.prototype.last = function(){
return this[this.length - 1]
}
;(function() {
var score = 0;
var text = "";
var possible = "ABCDE";
var noOfTries = 5;
function generateCharacter() {
var index = Math.floor(Math.random() * 100) % possible.length;
text = possible[index];
possible = possible.slice(0, index) + possible.slice(index+1);
alert(text);
return text;
}
function validate(string) {
return (string || "").trim().last() === text.last();
}
function handleChange(){
var valid = validate(this.value);
if(valid){
score++;
alert("Richtig!");
}else{
alert("Das war leider falsch. Die richtige Antwort wäre " + text + " gewesen!");
}
console.log(this.value.length === noOfTries)
this.value.length === noOfTries ? notify() : generateCharacter();
}
function notify(){
if(score == 0) {
alert("Schade! Sie haben " + score + " Punkte erreicht! Nochmal?");
}else if(score >= 1 && score <3){
alert("Schade! Sie haben lediglich " + score + " von 5 Punkten erreicht! Nochmal?");
}else if(score >= 3 && score <= 5) {
alert("Herzlichen Glückwunsch! Sie haben " + score + " von 5 Punkten erreicht!");
}
}
function registerEvent(){
document.getElementById('which').addEventListener('keyup', handleChange);
}
registerEvent();
generateCharacter();
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="which">Antwort? </label>
<input type="text" name="which" id="which" placeholder="#" style="width: 9px;">
And here's the fiddle: Compare generated string with user input

Related

Page doesn't load when I set variable to 0 in Javascript

var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
while (attempts < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
while learning how to use a random number generator, I wantd to add a while loop and give 3 attempts to choose from a random number.
When I create a variable to set the number of attempts, if I make the variable equal to 0, my page doesn't load, but if I leave the variable empty without a value, the script doesn't run.
Any ideas of why this may be happening?
var randomNumber = Math.floor(Math.random() * 6);
var x = 0
var maximum = 3
while (x < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
Your while loop runs synchronously, during pageload. The script never finishes, because the while loop's condition is never negated, so control is never yielded back to the browser to repaint the page, so the user never has a chance to input a number or click on the button.
While you could keep using while by promisifying the onclick and awaiting a Promise, it'd be better to create the handler outside, once, and have it check if the attempts are maxed out.
You also need to use consistent variable names: either use x or attempts, not both:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
document.getElementById("submit").onclick = function() {
if (attempts >= maximum) return;
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
You could disable the button after the maximum number of attempts has been reached, like:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0;
var maximum = 3;
document.getElementById("submit").onclick = function(e) {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
if (attempts === maximum) e.target.disabled = true;
};
<input type="text" id="input" />
<button id="submit">Submit</button>

Trying to reset my variables to their starting value javascript

This is actually my first beginner project. I wrote the whole code myself. It's about buying phones through 3 different methods. You can tell the program to automatically buy all phones and phone masks for all money you got, to manually buy one by one or to enter a number of phones and masks you wanna buy. Together with all that I set a number of phones and masks available at the stop together with user's bank balance.
The problem's coming from eraseData function. It simply doesn't work. Actually, the first part of it works but the second where I'm trying to reset my variables to their original value isn't working.
I have problems with using this editor to put in my code so I will use Pastebin.
const PHONE_PRICE = 150.00;
const MASK_PRICE = 50;
var bankBalance = 1983;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
function eraseData(){
var bankBalance = 1800;
var aPhones = 11;
var aMasks = 11;
var boughtPhones = 0;
var boughtMasks = 0;
var check = false;
var quantity = 0;
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
function updateData(){
document.getElementById("money").innerHTML = "Money left: $" + bankBalance;
document.getElementById("phones").innerHTML = "Amount of phones: " + boughtPhones;
document.getElementById("masks").innerHTML = "Amount of phone masks: " + boughtMasks;
}
checkOptions();
function checkOptions(){
var check = prompt("There is three different ways to buy a phone. (A)utomatically, (M)anually and by (Q)uantity. Choose one option.")
if(check == "A"){
buyPhoneA();
}
else if(check == "M"){
buyPhoneM();
}
else if(check == "Q"){
buyPhoneQ();
}
else{
alert("That's not a valid option!");
}
}
function buyPhoneA(){
alert("With this option you automatically spend all your money ($" + bankBalance.toFixed(2) + ") and buy all available phones and phone masks! (take in notice that you can't buy one if you don't have money for the other!)");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE" && aPhones >= 1 && aMasks >= 1 && bankBalance >= 200.00){
while(bankBalance >= PHONE_PRICE + MASK_PRICE){
aPhones--;
aMasks--;
boughtPhones++;
boughtMasks++;
bankBalance = bankBalance - PHONE_PRICE - MASK_PRICE;
updateData();
var check = false;
}
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have phones left or you don't have enough money!");
console.log(aPhones + " phones left");
console.log(aMasks + " masks left!");
console.log(boughtMasks + " bought masks!");
console.log(boughtPhones + " bought phones!");
console.log(bankBalance + " money left in the bank");
checkOptions();
}
}
function buyPhoneM(){
alert("With this options we will ask your over and over again to buy a phone! You can decline or agree to buying a new one! No accessories included");
var check = prompt("Type I AGREE if you agree to do this option!");
if(check == "I AGREE" && bankBalance >= 150.00 && aPhones >= 1){
aPhones--;
boughtPhones++;
bankBalance = bankBalance - PHONE_PRICE;
updateData();
buyPhoneM();
var check = false;
}
else{
alert("Something went wrong! Either you didn't type I AGREE correctly, we don't have any phones left or you don't have enough money!");
checkOptions();
}
}
function buyPhoneQ(){
var quantity = 0;
alert("With this option you will be asked to input a number of phones and accessories you want to buy!");
var check = prompt("Type I AGREE if you agree to use this option!");
if(check == "I AGREE"){
var quantity = prompt("Input a number of how many phones and accessories you want to buy!")
if(bankBalance >= 200.00 && aPhones >= 1 && aMasks >= 1){
aPhones + aPhones - quantity;
aMasks = aMasks - quantity;
bankBalance = bankBalance - ((PHONE_PRICE + MASK_PRICE) * 2);
boughtPhones = boughtPhones + quantity;
boughtMasks = boughtMasks + quantity;
updateData();
var check = false;
}
else{
alert("Something went wrong! Either the message your typed is not a number, you don't have enough money, we don't have enough masks or phones!");
buyPhoneQ();
}
}
}
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<p id="money">Money left: $1800</p>
<p id="phones">Amount of phones: 0</p>
<p id="masks">Amount of phone masks: 0</p>
<br><br>
<button onclick="eraseData();">Erase Data</button>
<script type="text/javascript" src="script.js"></script>
</body>
CSS's not really important for this..
(I don't remember why exactly put script tags below my button tag but I think it's because of something weird happening with my code, it didn't work until I did it that way )
I'd be grateful if anyone could help, thanks!
You have used global variable and local variables name same.
Either rename the function variable different from global variables or remove var ahead of function variable.

How do I make a document wait for an assigned input value?

I am writing a number guessing game. Every time I run the document it automatically goes to my outer else statement and I know why, but I can't figure out how to make it wait for an input value of the textbox. I want to set "guess" = to the value of the text box by pressing submit which will then enter the if statements. At the moment it is automatically setting to null and causing the error. Here is the code.
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1><br>
<button onclick = "search(1,100)">Press to play!</button>
</body>
<script type="text/javascript">
var counter = 0;
var randomNumber = Math.floor(Math.random()*100+1);
function search(first, last){
document.open();
document.write("<h1>Number Guessing Game</h1><br>");
document.write("<input id = 'guessBox' type = 'text'> ");
document.write("<input type = 'submit' id = 'submit' value = 'Submit'><br>");
document.write("<h2>Numbers Left</h2>");
for(var i = first; i <= last; i++){
document.write(i + " ");
}
document.write("<br><br><h3>Number of tries: " + counter + "</h3>");
document.close();
var guess = document.getElementById('guessBox').value;
//var guess = prompt("Guess!");
myguess = parseInt(guess);
if(myguess <= last && myguess >= first && cont == true){
if(myguess == randomNumber){
counter++;
if(counter <=3){
alert("WOW, that was amazingly quick! You found it in " + counter + " tries.");
}
else if(counter < 6 && counter >= 4){
alert("Not bad! You found it in " + counter + " tries.");
}
else if(counter < 10 && counter >= 6){
alert("Ouch! You found it in " + counter + " tries.");
}
else{
alert("Having a bad day aren't you? You found it in "+ counter + " tries");
}
}
else if(myguess < randomNumber){
first = myguess+1;
alert("Try again! The number is higher.");
counter++;
search(first, last);
}
else{
last = myguess-1;
alert("Try again! The number is lower.");
counter++;
search(first, last);
}
}
else{
alert("Invalid Number, try again.");
search(first, last);
}
}
</script>
Have you tried to disable the button, then add an onChange event to your text box so that you can enable the button once you have the desired input? You will need to add an ID or Name value to your button so it can be accessed? And to add what #LGSon added:
if(myguess <= last && myguess >= first && cont == true){, you check the variable cont, which I can't find in your code, so if it is not declared and set somewhere, you code will always take the outer route.
Second, you need to split your search function into 2 functions, one that generates the input, one that runs when someone entered a value (which can be fired on keypress or with a button)

Verify ID Number using javascript

I am trying to verify the south african ID NUMBER. I am not fluent with javascript.
I have the following code:
The HTML and Javascript
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
<title>the man</title>
<script>
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
</script>
</head>
The Body:
<body>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
Unfortunately I am not getting any error output. Please Assist
If this is the entire code, you are missing the closing head tag after script, I ran it and it worked as far as displaying different error messages with that cleaned up.
Edit- also added compiled code below which has document.ready shorthand.
<!DOCTYPE html>
<head>
<title>the man</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
});
</script>
</head>
<body>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
There were two proposed solutions and both of them would work.
First to remove script from the head section. (I guess you both placed </head> in different places, and that's why for one of you the submit attached correctly but not for the other)
<HTML>
<head>
<title>the man</title>
</head>
<body>
<script src="jquery-1.12.0.min.js"></script>
<script> //your code</script>
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
</body>
</html>
And the other to wrap all your code in
$(document).ready(wrapper);
function wrapper(){
function Validate() {
//your code
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
}
Why does the first solution work? First we render <head> so when your code is run
$('#idCheck').submit(Validate);
cannot be attached because the dom element does not exist yet. If we place the code in the execution is delayed.
Why does the second solution work? We wait until all page is rendered; only then do we execute our function that contains the same event attachment ($('#idCheck').submit(Validate);).

Problems with Javascript Game

I'm working on what should be an extremely simple "guess my number" game in Javascript, however, I can't get it to work correctly.
The program is supposed to choose a random integer between 1 and 10 and allow the user to try and guess that number as many times as it takes to get it right. If the user guesses a number that's lower than the correct one, the program is supposed to display a "your guess is too low" message, this is the same for when the guess is too high, or correct. The program must display the message on the webpage, not in an alert or any type of pop-up. Also, the program is supposed to keep a running list of the numbers that have been guessed by the user and display them on the page each time the user makes a guess (I want this list to display below my heading "Here are the numbers you've guessed so far:"). And finally, the program is supposed to display a "you already tried using that number" message if the user tries to input a number that they've already used.
Here is my code, along with a JSfiddle I've created and am still playing with.
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Guess My Number</title>
<script type = "text/javascript">
var tries = [];
game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random(), 10) + 1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess, 10);
}
catch (e) {
document.getElementById("guess").value = "Enter a guess.";
this.turns++;
return false;
}
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1 {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
}
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
}
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<div id = "result">
<input type = "text" id = "result" size = "20" />
</div>
<h3>Here are the numbers you've guessed so far:</h3>
</body>
</html>
http://jsfiddle.net/v09ttL74/
As you should be able to see from the fiddle, nothing is happening when I click either one of the buttons, so I'm not really sure where the problem is. I am getting a few errors when I select the JShints option on the fiddle, but most are things like "Missing semicolon" in places where there's not supposed to be a semicolon, like an one line where all I have written is
else {
Any suggestions would be greatly appreciated. I feel like this is just a really simple project that I am over-thinking since I'm stressed about it not working.
There's a lot of issues in your code. Just to mention a few...
1- Unclosed parenthesis here
tries.push(document.getElementById("guess").value;
it should be...
tries.push(document.getElementById("guess").value);
2- Expression not terminated with a close parenthesis here
else if(tries.indexOf(guess) != -1 {
it should be...
else if(tries.indexOf(guess) != -1) {
3- Wrong declaration of functions inside a function
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
I could be going forever but, really, the errors are a bit obvious
Alright as some of the answers must have already given you an idea of how many mistakes your Script as well as HTML code had.. from missing parenthesis to same ids to missing elements. Well i have corrected them and it's working now:
<h1>Would You Like To Play A Game?</h1>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<input type = "text" id = "result" size = "20" />
<h3>Here are the numbers you've guessed so far:</h3>
<p id='tries'></p>
Script:
var tries = [];
game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random() * 10) + 1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess, 10);
}
catch (e) {
document.getElementById("guess").value = "Enter a guess.";
this.turns++;
return false;
}
alert(guess+ ' '+this.num);
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
else if(guess < this.num){
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
}
}
function display() {
var number = "";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
See the DEMO here

Categories

Resources