Hot or Cold Number Guessing Game

The number guessing game project design and the initial html was provided to allow students to focus solely on the logic behind the game.

I’ve created a similar game through Sinatra before and the logic I used was very similar to that. Instead of a post request to the server, a submit function captures the input and calls several functions to check which feedback to use. The event.preventDefault was not placed in the end because the next if statement checks if an input is valid and could subsequently exit out of the function before the rest of the methods are called.

1
2
3
4
5
6
7
8
9
10
$( "#guess" ).submit(function( event ) {
  var input = +$("input").val();
  event.preventDefault();
  if (input > 100 || input <= 0) {
    return invalid();
  }
  increaseCount(input);
  var feedback = checkGuess(input);
  $('#feedback').text(feedback);
});

The invalid function sets the feedback message to tell the user to enter a valid guess.

1
2
3
function invalid() {
  $('#feedback').text('Please make a guess between 1 and 100');
}

A new game button restarts the process when clicked or when the maximum allowed guesses is reached. This function is also responsible for setting the new secretNumber and resetting the count to 0. This function also tells the user that the count has been reset and removes all of the old guesses.

1
2
3
4
5
6
function newGame() {
  secretNumber = Math.floor(Math.random() * 100) + 1;
  count = 0;
  $('#count').text(count);
  $('#guessList li').remove();
}

The increaseCount function raises the count variable by 1 and appends the previous guess to the page. This function is always called by the submit button unless the user inputs an invalid number.

1
2
3
4
5
function increaseCount(guess) {
  count += 1;
  $('#count').text(count);
  $('#guessList').append('<li>'+guess+'</li>');
}

The checkGuess function handles the game logic by giving a specific feedback based on how far the guess is from the secretNumber.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function checkGuess(guess) {
  if (Math.abs(guess-secretNumber) >= 50) {
    return 'Ice cold';
  } else if (Math.abs(guess-secretNumber) > 30) {
    return 'cold';
  } else if (Math.abs(guess-secretNumber) > 20) {
    return 'warm';
  } else if (Math.abs(guess-secretNumber) > 10) {
    return 'hot';
  } else if (Math.abs(guess-secretNumber) > 1 ) {
    return 'very hot';
  } else {
    newGame();
    return 'You got it right!';
  }
}

In the future, I would like to further refactor the game so that there are less responsibilities in the submit handler. Also, instead of Math.abs(), the game should be able to say if the guess us too high or too low.

Comments