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 |
|
The invalid function sets the feedback message to tell the user to enter a valid guess.
1 2 3 |
|
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 |
|
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 |
|
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 |
|
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.