JavaScript Learning Notes 1
1. Number guessing games
1.1 Requirement: Design a guessing game
Choose a number randomly within 1 to 100, and then challenge the player to guess the number within 10 rounds. Each round should tell the player the right or wrong. If there is a mistake, tell him whether the number is low or high, and also tell the player what the number was guessed before. Once the player guesses correctly, or they run out of rounds, the game will end. After the game is over, players can choose to start again.
1.2 Thinking from Programmer's Thinking
Generate random numbers between 1 and 100.
Record the player's rounds. Start from 1.
Provide a way for players to guess numbers.
Once a guess is submitted, it is first recorded somewhere so that users can see their previous guesses.
Next, check if it's the right number.
-
If it is correct:
- Show congratulations.
- Prevent players from entering more guesses (which can confuse the game).
- Display control allows players to restart the game.
-
If it's wrong and the player has the remaining rounds:
- Tell the players they're wrong.
- Allow them to enter another guess.
- Increase the number of cycles by 1.
-
If it's wrong and the player has no remaining rounds:
- Tell the player the game is over.
- Prevent players from entering more guesses (which can confuse the game).
- Display control allows players to restart the game.
Once the game is restarted, make sure that the game logic and user interface are completely reset, and then go back to step 1.
1.3 Converting ideas into code
1.3.1 Initial Settings
Create a simple form to enter the description and form segments of the guess, as shown in Figure 1:
1.3.2 Add variables to save data
<script>
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
</script>
This part of the code sets the variables of the data that the stored program will use. Variables are basically containers of values, such as numbers or text strings.
You can create a variable using the keyword var and the name of the variable. Then you can assign variables using the equal sign (=) and the value you want to assign.
In the above example:
The first variable, random Number, is assigned a random number between 1 and 100, which is calculated using a mathematical algorithm.
-
The next three variables are used to store references to result paragraphs in HTML and to insert values in subsequent paragraphs of code:
<p class="guesses"></p> <p class="lastResult"></p> <p class="lowOrHi"></p>
-
The next two variables store references to form text input and submission buttons and are used to control future submission guesses:
<label for="guessField">Enter a guess: </label><input type="text" id="guessField" class="guessField"> <input type="submit" value="Submit guess" class="guessSubmit">
The last two variables store a guess count of 1 (used to track how many guesses players have) and a nonexistent reference (but later).
1.3.3 function
A small example:
function checkGuess() {
alert('I am a placeholder');
}
Functions are reusable blocks of code that can be "written once, run everywhere" to save a lot of duplicate code. There are many ways to define functions, but now let's focus on the current simple way. Here we use the keyword function to define a function, followed by a name, followed by brackets. Then we put two braces ({}). Inside braces, there is all the code you want to run when you call the function.
1.3.4 Operator
1.3.5 condition
The new checkGuess() function:
function checkGuess() {
var userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = '!!!GAME OVER!!!';
setGameOver();
} else {
lastResult.textContent = 'Wrong!';
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
The intent of this code is:
- The first line (line 2 above) declares a variable named userGuess and sets its value to the current value entered in the text field. The value is also run through the built-in Number() method just to ensure that it is absolutely a number.
- Conditional block (lines 3 - 5 above). A comparison is included in parentheses. If the comparison returns true, the code placed in curly brackets is executed. Conversely, the code in curly brackets is skipped to execute the next line of code. In this case, the comparison is to test whether the guessCount variable is equal to 1, that is, whether the player guessed the number for the first time: guessCount === 1, if so, let the text content of the guesses paragraph equal to "Previous guesses:". If not, it means that we have executed the text settings, so there is no need to set them again.
- Line 6 appends the current userGuess value to the end of the guesses paragraph with a space, so there will be a space between each guess value.
-
In the next block of code (lines 8-24 above), several checks are made:
- The first if() {} checks whether the user's guess is equal to the random Number value set at the top of the code. If so, then the player guessed right, the game won, we will show the player a beautiful green congratulations message, and clear the content of the guess information box, call setGameOver() method.
- Then we write an else if() {structure. It checks whether this turn is the player's last. If so, the program will do the same thing as the previous block except that it displays Game Over instead of congratulations.
- The last block is else {}, which contains the code that the first two comparisons will only be executed by false, that is, the player still has the number of games, but this time did not guess right. In this case, we will tell the players that they guessed wrong, and perform a conditional test to determine and tell the players whether the guess is big or small.
The last three lines of this function (lines 26 - 28 above) prepare us for the next guess submission. We put the guessCount variable value + 1, so the player consumes an opportunity (++ is an incremental operator - the value + 1), then we empty the value of the text segment, re-focus the text segment, and prepare for the next round of the game.
1.3.6 incident
Now, the checkGuess() function has implemented most of the functionality, but it won't do anything now because it hasn't been called yet.
Ideally, we want to call it when we press the Submit guess button, so we need to use events.
Events are actions that occur in browsers, such as clicking on buttons, loading pages or playing videos, and we can call code to respond.
The construction method of listening for event occurrence is called event listener, and the code block that runs in response to event triggering is called event processor.
Add the following code after the closing braces of the checkGuess() function:
guessSubmit.addEventListener('click', checkGuess);
A listening event is added here for the guessSubmit button. This method contains two input values (parameters), the type of listening event (click in this case), and the code we want to execute when the event occurs (checkGuess() function in this case) -- note that when the function is a parameter of the event listening method, the function name should not be bracketed.
Save the code and refresh the page. Some of the functions of the example should now work properly. The only problem now is that if you guess the correct answer or the number of games used up, the game will be confused, because we have not defined the setGameOver() function that should run after the game is over.
1.3.7 Further Improve the Game
Add the setGameOver() function to the bottom of the code, and then look at it:
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Start new game';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
The first two lines disable form text input and buttons by setting their disable attribute to true. This is necessary, if not disabled, users can submit more guesses after the game is over, which will break the rules of the game.
The next three lines create a new button element, set its text to "Start new game" and add it to the bottom of our document.
- The last line sets up an event listener on the new button, and when it is clicked, a function called resetGame() is called.
resetGame() function. Add the following code to the bottom of the code:
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for (var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
This code block completely resets everything:
- Reset guessCount to 1.
- Clear all information paragraphs.
- Remove the reset button from the code.
- Enable form elements and clear and focus text fields to prepare for new guesses entered by users.
- Remove the background color from the lastResult section.
- Generate a new random number, so next time you're guessing a new number!
Now, a complete (simple) game is complete.
Next, I'll discuss other important code functions.
1.3.8 Some things about functions
Let's make one final improvement before we discuss it. Add the following line under var resetButton, near the top of JavaScript, and save the file:
guessField.focus();
This line uses the focus() method to automatically place text cursors in the input box immediately, which means that when the page is loaded, users can immediately start their first game without clicking on the input box. It's just a small improvement, but it improves usability -- providing users with visual clues to how to start the game.
Let's look at more details here. In JavaScript, everything is an object.
Objects are collections of related functions stored in a single grouping.
In this particular case, we first create a guessField variable to store references to text input form fields in HTML - the following lines can be found in variable declarations near the top:
var guessField = document.querySelector('.guessField');
This reference is obtained using the querySelector() method of the document object. querySelector() requires a parameter -- use the CSS selector of that element to select the element you want to refer to.
Because guessField now contains references to <input> elements, it now stores attributes of the number of accesses (some of the underlying variables that will not change their values in the internal object) and methods (the underlying functions stored within the object). One way to input elements is focus(), so we can now use this line to set text input::
guessField.focus();
Variables that do not contain references to form elements will not have focus() methods for them to execute. For example, include pairs
The guesses variable referenced by the element and the guessCount variable containing a number.
1.4 Source Code
<!DOCTYPE html>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Number guessing game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
</style>
<style type="text/css" abt="234"></style>
</head>
<body data-gr-c-s-loaded="true">
<h1>Number guessing game</h1>
<p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.</p>
<div class="form">
<label for="guessField">Enter a guess: </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses">Previous guesses: 10 </p>
<p class="lastResult" style="background-color: red;">Wrong!</p>
<p class="lowOrHi">Last guess was too high!</p>
</div>
<script>
// Your JavaScript goes here
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = '!!!GAME OVER!!!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = 'Wrong!';
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Start new game';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
</script>
</body>
</html>