Spelchan.com Logo

From Scratch Web Games: A Beginners Guide to Game Development using HTML, CSS, and JavaScript

Chapter 4.10: If (Conditional statements)

The conditional statements we worked with in the last section are the building block of the conditional statement. The basic idea is that we want our code to run different parts of itself based on the state of one or more variables. An example of this would be allowing people eighteen or older to vote. The diagram below, known as a flow chart, demonstrates the flow of the program.

If flowchart

One reason for having a scripting language is to be able to react to what the user does. To control the flow of the program requires making decisions. This is what the if statement does. The if statement uses the following format:

if (condition)
   statement_to_perform_if_condition_is_true
// continue with program

You will notice that we are specifying a statement. Only a single statement after the if statement is considered to be what to do if the condition is true. We indent this statement to make it easier for humans to read the program. The computer does not care whether we indent the code or not. It only cares that there is a statement after the if statement. This leads to an issue. What if we want to have more than one statement as part of the condition?

The solution to this problem is to have a block of code. We have already been using blocks, as the { and } symbols we used to indicate where our main method started and stopped are a block. The same concept works with if statements.

if (condition)
{
   // zero or more statements go here
}

There is no rule as to where to place the start of the block so you will often see the block start on the same line as the if statement. This more condensed form of formatting is the preferred way for most JavaScript programmers, even though the first way is more readable due to the simple fact that the braces line up.

if (condition) {
   // zero or more statements go here
}

Sometimes we may want one action to occur when the condition is true and a different action to occur when the condition is false. This is where the optional else statement comes into play. This flowchart shows how the program works through the decision.

If/then flowchart

The code for doing this takes the following format:

if (condition)
   statement_to_perform_if_condition_is_true
else
   statement_to_perform_if_condition_is_false
// program continues here

As with the if statement, if you wish to have more than one statement after the if or the else, you should place the block of statements into a block by using a pair of curly braces {}. Here is the flowchart example above represented as code.

if (age >= 18) {
   System.out.println("You can vote");
} else {
   System.out.println("Too young to vote");
}

The condition is simply a mathematical condition, but two equal signs are used together to indicate equals while a != combination is used for not equal. The greater than and less than symbols (<, <=, >, >=) can also be used. Be careful not to use a single equals in a condition as this will assign that value to the variable which can lead to hard to track bugs. Many languages, such as Pascal, use equals for equality and use something else (:= in Pascal) for assignment.

Conditions can be combined to form more complex conditions. This is done by placing each condition in it's own set of brackets and then placing an and (&&) or an or (||) symbol between them.

The and (&&) operation means that both conditions must be true if the condition is to be true. If either or both conditions are false then the condition is false. For example, to make sure a player is in the bounds of a 100x100 square they must be within all four sides. We may have the following code to check this:

if (
   (playerX >= 0) &&
   (playerX < 100) &&
   (playerY >= 0) &&
   (playerY < 100)
)
console.log("Player is within the bounds");

Note that the range for the square is 0 through 99 inclusive. This is a programmer thing that makes a lot of sense once you start doing a lot of programming but can be confusing for non-programmers. This makes even more sense when you do machine language programming.

The or (||) operation just requires that one of the conditions is true, though both conditions being true is also acceptable. For example, to check if something is not within the bounds of a square we can check to see if any of the bounds have been violated with the following code:

if (
   (playerX < 0) ||
   (playerX >= 100) ||
   (playerY < 0) ||
   (playerY >= 100)
)
console.log("Player is outside of the bounds");

It is also possible to assign a condition result to a Boolean variable which can be useful if you have to check the results of some condition multiple times. To demonstrate this, the inside box check could be written as follows:

Let inBox = (
   (playerX >= 0) &&
   (playerX < 100) &&
   (playerY >= 0) &&
   (playerY < 100)
);
if (inBox)
   console.log("Player is within the bounds");

You will notice that we are assuming that the player is a single point. This may not be the case, so a bit more advanced logic would need to be used here. While this is a bit complicated, lets look at how we would check if there was an overlap between two rectangles.

This can be simplified to two separate checks as if there is horizontal overlap but no vertical overlap, or vice-versa, then there is no overlap. This greatly simplifies this problem. This can now be thought of two number-line comparisons. As can be seen in the following image, there are several different ways two lines can overlap.

Overlapping ranges on a line

We can see that one line may completely overlap the other line, or only either end may be overlapped. In the near miss cases on the right we will notice that if the end point of the line is less than the start point of the other line then there is not an overlap. Likewise, if the start point of a line is greater than the end point of the other line then there is no overlap. However, in the three collision situations on the left, one, or both, of these two conditions is not true. So if we have the horizontal start position of the player as playerX1 and the horizontal end position being playerX2 we could use the following code to see if there is a horizontal overlap between the player and an object that spans the range 50 to 100.

if ((playerX2 < 50) || (playerX1 > 100))    console.log("Not overlapping");

We can then apply the same concepts to the y location, and combine them to get the following:

if ( ((playerX2 < 50) || (playerX1 > 100)) ||
       ((playerY2 < 50) || (playerY1 > 100)) )
   console.log("Not overlapping");
else
   console.log("Overlapping");

We will be delving more into collision logic in future chapters. We are not quite finished with condition statements yet, however. The statement or block that follows an if statement can itself contain if statements. This is known as nested if statements and is what we will explore next.

Chapter contents

Chapter 4 Contents

4.1 Cheat Sheets

A quick summary of the basics of JavaScript.

4.2 History of JavaScript

A brief look at how JavaScript was written in 10 days.

4.3 Comment Controversy

Comments. Why programmers don't write them, and how they should be written

4.4 Variables

Variables are used to store the state of a program.

4.5 (extra) How Computers Represent Data

Bits, Bytes, and data types.

4.6 Math

Math on the computer similar but some symbol differences.

Math functions

Various math operations can be used through the Math class.

4.8 Strings

Strings are what we call blocks of text and are used extensively.

4.9 Calculating true and false

Determining if a conditional expression is true or false

4.10 if (Conditional statements)

Conditional code using the if statement.

4.11 Nested conditions

If statements can contain other if statements, this is called nesting.

4.12 Switch statement

Switch statements are a way of replacing large number of else if statements.

4.13 Functions

Functions let you put common code into a named function that can be called anywhere.

4.14 Looping

Loops allow you to repeat sections of code until conditions are met.

4.15 Nested loops

Just like conditional statements, loops can be nested but this has some special considerations.

4.16 Accessing the Web page

Scripting languages give us the ability to dynamically change the web page.

4.17 Events

Reacting to the user actions is done by handling events.

4.18 Project: Where’s Wendy

Coming June 23rd, 2024

4.19 Project: Where’s Wendy implementation

Coming June 30th, 2024

← previous section
Calculating Truth
next section →
Nested conditions
Table of Contents