Random hi/low guessing game in JS

Dec 22nd, 2013
105
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. var check_guess = function (number, guess) {
2.   // Checks the guess against the number. Returns -1 if the guess is low,
3.   // 1 if the guess is high, or 0 if the guess is correct
4.   if (guess < number) return -1;
5.   if (guess > number) return 1;
6.   return 0;
7. };
8.
9. var check_input = function (input) {
10.   // Validates that the user's input is a number from 1 to 100. Returns
11.   // that number, or 0 if the input was not valid.
12.   var number = new Number(input);
13.   if (number == NaN) return 0;
14.   number = number.valueOf();
15.   if ((number < 1) || (number > 100)) return 0;
16.   return Math.floor(number);
17. };
18.
19. var prompt_user = function () {
20.   // Prompts the user for a number between 1 and 100, and continues to do
21.   // so until a valid one has been entered. Returns said number.
22.   var number, user_input;
23.   do {
24.     user_input = prompt("Enter your guess (1 - 100):");
25.     number = check_input(user_input);
26.   } while (number == 0);
27.   return number;
28. };
29.
30. var generate_number = function () {
31.   var random_number = Math.random();
32.   random_number *= 100;
33.   return Math.floor(random_number + 1);
34. };
35.
36. var play_game = function () {
37.   var number = generate_number();
38.   var guesses, check, this_guess = 0;
39.   for (guesses = 0; this_guess != number; guesses ++) {
40.     this_guess = prompt_user();
41.     check = check_guess(number, this_guess);
42.     switch (check) {
43.       case -1:
45.         break;
46.       case 1:
48.         break;
49.       case 0:
51.         break;
52.     }
53.   }
54.   alert("It took you " + guesses + " guesses to get it right!");
55. }
56.
57. // main code follows
58. var prompt_result;
59. while (true) {
60.   prompt_result = prompt("Type 'start' to start, or anything else to quit");
61.   if (prompt_result == "start")
62.     play_game();
63.   else {