Guess My Number Game in JS
First of all let me just give you a demo of what the end result will look like. Watch the video below:
First we need to design the UI (User Interface) of the game. So, in this video I have explained how I have designed the UI of the game. So, go ahead and watch the following video:
Our next job is to implement the logic of the game. So, there are a number of things that we need to consider. So, let’s address them.
We need to have a variable to store the number generated by the computer. We will call it theNumber. Then we will have another variable called userGuess to store the number that the user has guessed. A variable for the number of tries that the user had, called tries.
We will have a function called init() where we will write all the code for resetting the game to the initial state which will include: a) setting the random number, b) setting the input and the tries to 0, c)resetting the hint.
Then we will create a function called checkGuess() where we will have some if conditions and check whether the user’s input is greater than or smaller than theNumber and set the hint message accordingly. However if the user’s input matches the theNumber, then we have to execute a function (that we will call displayWinningMessage()) to show the winning screen. Also note that every time the user presses the Guess button, we have to increase the tries variable by 1.
So, that is basically how we will implement the logic for the game. Watch the video below to see it in action.
Download the Source code
I hope you have enjoyed the video. If you did, please share this article and videos with your friends. And download the source code from here