Scripting for animation coding 2
This will be a somewhat short lesson, we will work on creating a simple game with javascript in order to practice the basics of scripting with javascript.
Before we do anything else let’s set up our coding environment.
# Resources
Below is a link to a repo that has a bunch of examples that you can play around with.
benshurts/javascript-practice-templates
# Javascript Practice
# IDE Setup
It’s worth taking note that the standard naming convention for javascript is camelCase. But you can read more about conventions here
# Guessing Game
Once you have your IDE setup with an html file and javascript file, open the javascript file.
The point of creating this game is practice logic and control flow. So I will provide the boilerplate of less important code.
Below is the html for your main page.
|
|
And here is the boiler plate for the javascript.
|
|
The first thing you need to do is create some variables.
We want to store a value for the player guess, that value should be randomly generated.
Remember there are many ways to solve problems in programming. Often there are no right or wrong ways to do it. It all depends on your project and the specifications and needs of that project.
There are few ways you could do this. First it may be helpful for you to look at the Documentation for the random function in javascript.
Math.random() - JavaScript | MDN
Let’s add a constant called targetNumber where I commented //variables
in the boilerplate.
|
|
This line of JavaScript code defines a constant variable called targetNumber
, which is assigned a random number between 1 and 100, rounded down to the nearest integer.
Here’s how it works:
Math.random()
generates a random decimal number between 0 (inclusive) and 1 (exclusive).Math.floor(Math.random() * 100)
multiplies the random number generated byMath.random()
by 100, then rounds down to the nearest integer usingMath.floor()
. This will produce a number between 0 and 99.Math.floor(Math.random() * 100) + 1
finally adds 1 to the result ofMath.floor(Math.random() * 100)
, which results in a random number between 1 and 100, inclusive.
So targetNumber
will hold a random number between 1 and 100, both inclusive, and will be rounded down to the nearest integer.
Next let’s add another variable:
let numberOfGuesses = 0;
This will store the number of guesses the player makes.
Your code should now look like this:
|
|
Now things get a little more interesting. Before moving on here’s an explanation of the next boilerplate.
submitBtn.addEventListener('click', function() { //code here });
submitBtn
: A reference to the element that the event listener will be attached to. It’s assumed that this element has already been defined elsewhere in your code and can be selected using JavaScript (e.g.document.getElementById('submitBtn')
).addEventListener
: A method that allows you to attach an event listener to an element. It takes two arguments:- The first argument is the type of event to listen for, which in this case is
'click'
. - The second argument is the function that will be executed when the event is triggered.
- The first argument is the type of event to listen for, which in this case is
'click'
: The type of event to listen for. This tells the event listener to listen for aclick
event.- Anonymous function: A function without a name that is defined inline with the call to
addEventListener
. The function will be executed when theclick
event is triggered on thesubmitBtn
element.- The code inside the anonymous function will be executed whenever the
submitBtn
is clicked.
- The code inside the anonymous function will be executed whenever the
The code sets up an event listener for the submitBtn
element that listens for a click
event. When the click
event is triggered on the submitBtn
element, the anonymous function will be executed, and the code inside it will be executed.
Now it’s time to fill in the button function with the guessing-game logic.
You can pause here to try it on your own if you want.
Inside the button function let’s start by incrementing the guess number like so:
numberOfGuesses++;
The ++
is syntactic sugar or shorhand for numberOfGuesses = numberOfGuesses + 1;
|
|
Next we will declare another variable.
const guess = parseInt(guessInput.value, 10);
This line of code declares a constant guess
and initializes it with the value entered by the player into the guessInput
element. The value of guessInput.value
is first converted from a string to an integer using parseInt()
.
The parseInt()
function takes two arguments:
- The string to be parsed
- The radix (base) for the conversion (in this case, 10)
So in this line of code, parseInt(guessInput.value, 10)
returns the integer representation of the string stored in guessInput.value
, and the result is stored in the guess
constant.
Next we will add an if statement
if (guess === targetNumber) { ...
This line of code is an if
statement that tests whether the value stored in the guess
variable is equal to the value stored in the targetNumber
constant. The equality operator === is used to compare the values of guess
and targetNumber
.
If the values are equal, meaning that the user’s guess is correct, then the code inside the if
statement will be executed. Otherwise, the code inside the if
statement will be skipped and the next step of the program will be executed.
The if
statement is a fundamental control structure in programming that allows for branching based on a condition. It allows a program to make decisions and execute different code paths depending on whether a certain condition is true or false.
In JavaScript, the difference between
== == , ===
is as follows:
=
is the assignment operator, used to assign a value to a variable. For example,x = 10
assigns the value 10 to the variablex
.==
(double equals) is the equality operator, used to compare two values for equality. This operator performs type coercion, meaning that it will try to convert the values to a common type before comparison. For example,10 == "10"
returnstrue
because both values are converted to a string type before being compared.===
(triple equals) is the strict equality operator, used to compare two values for equality without any type coercion. This operator only returnstrue
if the values are of the same type and equal in value. For example,10 === "10"
returnsfalse
because the type of10
isnumber
while the type of"10"
isstring
.In general, it’s recommended to use the strict equality operator === in your code, as it can help avoid unexpected results caused by type coercion.
Next within that if statement block let’s add the following:
|
|
- The assignment operator (=) is used to assign a value to a variable or an object property. In this case, it is used to set the “textContent” property of the “resultDiv” object to a string value.
resultDiv.textContent = 'You win! It took you ' + numberOfGuesses + ' guesses.';
- The “+” operator is used for string concatenation, which allows multiple strings to be combined into one string. In this case, it is used to combine the string literal
'You win! It took you '
with the value stored in the “numberOfGuesses” variable, and then with the string literal' guesses.'
. The result of this concatenation is then assigned to the “textContent” property of the “resultDiv” object.
'You win! It took you ' + numberOfGuesses + ' guesses.';
- The “.” operator is used to access an object’s properties or methods. In this case, it is used to access the “textContent” property of the “resultDiv” object and the “disabled” property of the “submitBtn” object.
resultDiv.textContent submitBtn.disabled
- The “;” operator is used to end a statement in JavaScript. Each statement in JavaScript must end with a semicolon.
resultDiv.textContent = 'You win! It took you ' + numberOfGuesses + ' guesses.'; submitBtn.disabled = true;
Ok next we should add an else if statement.
|
|
and in context:
|
|
- The “else if” statement is used to specify an alternate set of instructions to be executed if the conditions of the preceding “if” statement are not met. In this case, the condition being tested is
guess < targetNumber
.
else if (guess < targetNumber) {
- The comparison operator “<” is used to test if the value stored in the “guess” variable is less than the value stored in the “targetNumber” variable.
guess < targetNumber
- If the condition
guess < targetNumber
is true, the code inside the curly braces{ }
will be executed. In this case, the “textContent” property of the “resultDiv” object is set to the string value'Too low. Guess again.'
.
resultDiv.textContent = 'Too low. Guess again.';
- The code inside the curly braces
{ }
specifies the instructions to be executed if the conditionguess < targetNumber
is true. In this case, the instructions set the “textContent” property of the “resultDiv” object to the string value'Too low. Guess again.'
.
{ resultDiv.textContent = 'Too low. Guess again.'; }
Next, let’s add an else statement.
|
|
And in context:
|
|
Here’s what it does:
- If none of the conditions in the preceding “if” or “else if” statements are true, the code inside the curly braces
{ }
will be executed.
else { resultDiv.textContent = 'Too high. Guess again.'; }
- Inside the curly braces
{ }
, the “textContent” property of the “resultDiv” object is set to the string value'Too high. Guess again.'
.
resultDiv.textContent = 'Too high. Guess again.';
So, in summary, if the “guess” variable is not equal to the “targetNumber” variable and is not less than the “targetNumber” variable, the code inside this “else” statement will be executed, and the “textContent” property of the “resultDiv” object will be set to the string value 'Too high. Guess again.'
.
The completed code:
|
|
# Challenge
Now on your own you can try any of the following:
- Modify the code to allow the player to keep guessing until they correctly guess the target number.
- Add a reset button that sets a new target number and resets the number of guesses.
- Keep track of the player’s previous guesses and display them in a list on the page.
- Implement a hint system that tells the player whether the target number is odd or even.
- Allow the player to select a difficulty level (easy, medium, hard) that changes the range of possible target numbers.
- Add a timer that counts how long it takes the player to correctly guess the target number.
- Make the game responsive to different screen sizes and display nicely on both desktop and mobile devices.
- Store the player’s high score and display it on the page.
- Add a leaderboard that displays the names and scores of the top players.
- Allow the player to input their name before starting the game, and display their name in the leaderboard.