Knowledge Garden

Search

Search IconIcon to open search

Scripting for animation coding 2

Last updated Jan 31, 2023 Edit Source

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

IDE Setup for javascript

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Guess the number between 1 and 100:</h1>
    <input type="text" id="guess">
    <button id="submit">Submit</button>
    <div id="result"></div>
</body>
<footer>
    <script src="guessing-game.js"></script>
</footer>
</html>

And here is the boiler plate for the javascript.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const guessInput = document.querySelector('#guess');
const submitBtn = document.querySelector('#submit');
const resultDiv = document.querySelector('#result');

// variables

//This is the button function
submitBtn.addEventListener('click', function() {

// code

});

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.

1
const targetNumber = Math.floor(Math.random() * 100) + 1;

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:

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const guessInput = document.querySelector('#guess');
const submitBtn = document.querySelector('#submit');
const resultDiv = document.querySelector('#result');

// these are new
const targetNumber = Math.floor(Math.random() * 100) + 1;
let numberOfGuesses = 0;

submitBtn.addEventListener('click', function() {
	//code here
});

Now things get a little more interesting. Before moving on here’s an explanation of the next boilerplate.

submitBtn.addEventListener('click', function() { //code here });

  1. 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')).
  2. 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.
  3. 'click': The type of event to listen for. This tells the event listener to listen for a click event.
  4. Anonymous function: A function without a name that is defined inline with the call to addEventListener. The function will be executed when the click event is triggered on the submitBtn element.
    • The code inside the anonymous function will be executed whenever the submitBtn is clicked.

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;

1
2
3
submitBtn.addEventListener('click', function() {
	numberOfGuesses++;
});

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:

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:

  1. = is the assignment operator, used to assign a value to a variable. For example, x = 10 assigns the value 10 to the variable x.
  2. == (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" returns true because both values are converted to a string type before being compared.
  3. === (triple equals) is the strict equality operator, used to compare two values for equality without any type coercion. This operator only returns true if the values are of the same type and equal in value. For example, 10 === "10" returns false because the type of 10 is number while the type of "10" is string.

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:

1
2
3
resultDiv.textContent = 'You win! It took you ' + numberOfGuesses + ' guesses.';

submitBtn.disabled = true;
  1. 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.';

  1. 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.';

  1. 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

  1. 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.

1
2
3
else if (guess < targetNumber) {
    resultDiv.textContent = 'Too low. Guess again.';
  }

and in context:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
submitBtn.addEventListener('click', function() {
  numberOfGuesses++;
  const guess = parseInt(guessInput.value, 10);
  if (guess === targetNumber) {
    resultDiv.textContent = 'You win! It took you ' + numberOfGuesses + ' guesses.';
    submitBtn.disabled = true;
  } else if (guess < targetNumber) {
    resultDiv.textContent = 'Too low. Guess again.';
  }
});
  1. 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) {

  1. 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

  1. 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.';

  1. The code inside the curly braces { } specifies the instructions to be executed if the condition guess < 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.

1
2
3
else {
    resultDiv.textContent = 'Too high. Guess again.';
  }

And in context:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
submitBtn.addEventListener('click', function() {
  numberOfGuesses++;
  const guess = parseInt(guessInput.value, 10);
  if (guess === targetNumber) {
    resultDiv.textContent = 'You win! It took you ' + numberOfGuesses + ' guesses.';
    submitBtn.disabled = true;
  } else if (guess < targetNumber) {
    resultDiv.textContent = 'Too low. Guess again.';
  } else {
    resultDiv.textContent = 'Too high. Guess again.';
  }
});

Here’s what it does:

  1. 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.'; }

  1. 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const guessInput = document.querySelector('#guess');
const submitBtn = document.querySelector('#submit');
const resultDiv = document.querySelector('#result');

const targetNumber = Math.floor(Math.random() * 100) + 1;
let numberOfGuesses = 0;

submitBtn.addEventListener('click', function() {
  numberOfGuesses++;
  const guess = parseInt(guessInput.value, 10);
  if (guess === targetNumber) {
    resultDiv.textContent = 'You win! It took you ' + numberOfGuesses + ' guesses.';
    submitBtn.disabled = true;
  } else if (guess < targetNumber) {
    resultDiv.textContent = 'Too low. Guess again.';
  } else {
    resultDiv.textContent = 'Too high. Guess again.';
  }
});

# Challenge

Now on your own you can try any of the following:

  1. Modify the code to allow the player to keep guessing until they correctly guess the target number.
  2. Add a reset button that sets a new target number and resets the number of guesses.
  3. Keep track of the player’s previous guesses and display them in a list on the page.
  4. Implement a hint system that tells the player whether the target number is odd or even.
  5. Allow the player to select a difficulty level (easy, medium, hard) that changes the range of possible target numbers.
  6. Add a timer that counts how long it takes the player to correctly guess the target number.
  7. Make the game responsive to different screen sizes and display nicely on both desktop and mobile devices.
  8. Store the player’s high score and display it on the page.
  9. Add a leaderboard that displays the names and scores of the top players.
  10. Allow the player to input their name before starting the game, and display their name in the leaderboard.