Saturday, April 21, 2018

3.6 Arrays


Simply stated, an array is a list. The size of the list determines how many pieces of information, known as elements, can be put into it. Any part of the list can be accessed, if you know where in the list it is stored.

There are several ways of creating an instance of an array, as follows:

x = new Array();
x = [];
x = new Array(size);
x = new Array (element1, element2, ..., elementN);
x = [element1, element2, ..., elementN)];

The first two methods create an array that has no elements. While this may not seem useful, it is possible to add new elements to an array, which we will discuss later. The third method creates an array with a specific number of elements. These elements are initially empty, but new values can be assigned to them, as we will discuss later. The final two methods creates a populated array. The size of the array will depend on the number of elements that are declared, but in theory any number of elements can be specified. This type of constructor is very useful in cases when you want to have some type of table of predefined values that can be accessed.

The power of an array comes from the ability to access and modify the elements of the array. Elements of an array have an index number associated with them. The first element of an array is referenced with the number 0, the second is 1, and so on. Some people find using element 0 confusing, so will simply ignore that element and start storing stuff in element 1. If you are going to do this, remember that the last element of an array is one less than the size of the array.

To access the element, you simply use the array variable's name, followed by the index number in square brackets. The index does not have to be a number, but can be a variable that contains the index number. For example, the following program adds the third and fourth elements (index values 2 and 3) and places the result in the first (index 0) element.

index = 3;
list = new Array(0, 1, 2, 3, 4, 5);
result = list[2] + list[index];
list[0] = result;

The Array class has functions for modifying and getting information about the array. It also has a read-only property variable named length that holds the current length of the array. Action Script allows you to change the size of the array at any time. Many other programming languages are not quite as flexible. The Action Script Dictionary that is included with Macromedia Flash covers these functions in detail.

Now we come to a rather interesting additional for statement that is included with Action Script, the for..in statement. This is what is known as an iterative for function. It is used to iterate through all the variables of the indicated object. The format for this command is for (variable_holding_index in object) The variable_holding_index is simply the name of the variable that holds the index. Here is a sample to illustrate how this can be used.

var cntr;
testArray = new Array("A", "B", "C", "D");
for (cntr in testArray) {
console.log("Element " + cntr + " is " + testArray[cntr]);
}

Saturday, April 14, 2018

3.5 Looping

Looping is a very common programming task. A loop is essentially a block of code that executes until certain conditions are met. JavaScript supports three types of looping statements. The while statement, the do ... while statement, and the for statement. The first two types of loops are very similar so we will look at them together.

The While statement always has a statement or block of statements tied to it. The condition of the while statement is tested. If the condition is true then the statement or block of code gets executed. When the block of code is finished executing the while statement condition is tested again. If it is still true, the statement or block gets executed again. This continues until the condition is false, at which point the program continues execution on the line after the statement of block of statements. Here is a use of the while statement to see how long an object will fall before hitting the ground.

var distRemain = meters_to_fall;
var vel = 0;
var time = 0;
while (distRemain > 0) {
     vel += 9.8;
     distRemain -= vel;
     ++time;
}

One thing that starting programmers must watch out for is the infinite loop. This is a loop that will never end, meaning that the program is stuck until stopped by the user. Most web browsers will only let loops run a certain amount of time before brining up a dialog box telling the user about the problem and letting the user cancel the script.

The problem with the while loop is that it’s possible that the statement or block after the while statement will never be executed. Sometimes you always want the statement or block to be executed at least once. This is what the do ... while statement does. In this example we want to find the length of time an object will decay rounded up to the nearest half life interval. A half life is the length of time a decaying object takes to be reduced to half of it’s original mass.

var life = startinglife;
var duration = 0;
do {
     life /= 2;
     ++duration;
} while (life > 1);
console.log ("Lifespan of object is " + (duration * halflife));

The most common type of loop in programming is the for loop. The purpose of this type of loop is to count through a series of numbers. The format of the for statement is:
for (start_condition; end_condition; increment){ /*loop action*/ }

The start condition starts the variable that will be counting to it's initial value. This will generally be 0 or 1, but can be any value. If there is no need to initialize a variable, you can skip this part of the statement by simply having the semicolon. I would consider having a /*none*/ comment before the semi-colon so you know that there is no loop initialization.

The end condition is simply a boolean statement like you would use with an if statement. The loop continues until this condition is no longer true. The condition can be any boolean condition, and could even consist of a function call.

The increment portion is where the counting variable is changed. It is called at the end of every loop iteration. Generally you will be increasing the counter by 1, but it is valid to decrease the counter, or do any other mathematical operation or call any function you wish. The following sample will add the numbers 1 to 10 together.

var cntr, value = 0;
for (cntr = 1; cntr <= 10; ++cntr) {
 value += cntr;
}

The for statement seems complex. When you get right down to it, the for statement is really a macro statement that makes a while loop behave as a counter. One way of better understanding a for loop is to look at the loop as a while loop. By doing this, you will see what the three parts inside the for loop really do. Here is the above example as a while loop.

var cntr, value = 0;
cntr = 1; // the start condition
while(cntr <= 10) // the end condition {
    value += cntr; // the loop action   
     ++cntr; // the increment
}

Repeating things a set number of times is important, but where for loops tend to be used the most is with arrays and objects so we will continue our discussion as part of our look at arrays and objects.

Saturday, April 7, 2018

The Switch Statement


The Switch statement is a convenient way of handling situations where you need to handle many actions based on the value of a variable. The Switch statement starts of with the switch statement which contains an expression that should evaluate into a number. After the switch statement is a block of code which consists of case statements and an optional default statement.

switch (number)
{
     case 1:
           console.log("The number is one");
           break;
     case 2:
           console.log("The number is two");
           break;
     case 3:
           console.log("The number is three");
           break;
     default:
           console.log("The number is not one, two or three");
}

After each of the case statements is the code you want to execute if the variable being switched equals the value of the case. The code should end with a break statement, which causes the program to skip over the rest of the switch block. If there is no break statement, all code in the following case statement will also be executed. In some cases, this is exactly what you want to happen, as it allows you to define a group of numbers that all do the same action. Forgetting the break statement is a very common mistake for beginners to make and is even something that experts have made resulting in devastating results.

The default statement will be executed if none of the case statements match the value of the switch expression. No break statement is needed after the default code, though I usually do have a break statement out of habit. While the default statement is optional, it is a good habit to always have a default action, even if the default is simply a trace statement telling you that you have reached code that should not be reached.

The switch statement we have above could be done with if statements as you can see below.

if (number == 1) {
    console.log("The number is one");
} else if (number == 2) {
    console.log("The number is two");
} else if (number == 3) {
    console.log("The number is three");
} else {   
     console.log("The number is not one, two or three");
}

The choice between using switch and if statements is more of a cosmetic one with JavaScript. Switch statements are a convenience statement designed to replace large numbers of if then else statements in a more readable way.

The switch statement comes directly from the C programming language. While I am a fan of that language, being one of the first programming languages that I learned, I have been bitten by the switch statement too many times and have uncovered bugs in other people’s code due to the forgetting of a break statement frequently. Therefore, I am happy that new languages are replacing the default fall-through behavior with default break behavior requiring a statement to fall through.

Another common bug with the switch statement is not having a default block when a case does not cover all possibilities. The result of not having a default is essentially a default that does nothing which may be what you want. It could also be an indication that you expect only the values in the case to exist. Having a default that reports an error if it is reached is recommended in this situation.

Saturday, March 31, 2018

3.3 The IF statement

One reason for having a scripting language is to be able to control the flow of a movie. Controlling something 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
else
     statement_to_perform_if_condition_is_false

The else part of the if statement is optional. If you wish to have more than one statement after the if or the else, you should place the block of statements into a pair of curly braces {}. Curly braces indicate a block of code so can be used anywhere that a single statement is expected in order to run a block of statements.  Here is an example.

 if (x == 1)  {   
     console.log("x is assigned a value of 1");
     y = 23;
}

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. If you are interested in machine language, you can learn about it from my HomeBrewGameJam blog where I am writing a 6502 emulator for use in an Atari 2600 emulator and later a NES emulator.

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:

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

The statement or block that follows an if statement can itself contain if statements. This is known as nested if statements.

Saturday, March 24, 2018

3.2 Variables and Math


A variable is essentially a name that refers to a bit of information, such as a name. The information that the variable can hold can be changed which is why it is called a variable. While there are different types of variables JavaScript doesn't care what information the variable contains and can change the type of information that a variable contains. This is known as dynamic typing. It is also a big source of errors which is why many languages do require that you have specific types of variables for holding specific types of information. Later versions of the ECMA-Script specification do support optional types which is a good compromise.

You set a value to a variable by using the equals sign and can do various operations on the variable. Variables can be set to numeric values, String values, and can even be a function or instance of an object. We will discuss these things in further detail in later sections and chapters. Here is a bit of sample code that shows various variables being assigned values. The optional var keyword is used to indicate the declaration of a variable, but unknown variables will be created the first time they are seen. Variables that are declared without a var statement are assumed to be global in scope meaning that everyone can see the variable. This feature of automatically creating a variable the first time it is encountered makes it easy to write code but also means that a typo can result in very hard to find bugs.

var x = 11;
 y = 7;
 text = "Strings need to be enclosed in quotes";
function_variable = function() { /*code here*/ };

When using variables that use numbers in JavaScript, it is possible to do mathematical operations on the variables. Math in JavaScript uses algebraic order of operations which means that numbers will be multiplied or divided before they are added or subtracted unless brackets are used to group operations. Adding and subtracting uses the plus and minus sign. Multiplication is done by using the asterisk (*) symbol and dividing is done by using the slash (/) symbol. You can also get the remainder of a division by using the percent (%) symbol.

JavaScript also supports special decrement and increment operators. The double minus signs represent the decrement operation and essentially means deduct one from the variable this operator is used on. There is also an increment operator which is represented by double plus signs. The operator can be placed before or after the variable. If placed before the variable, the operation is done immediately. If placed after the operator, the operation will only be performed after any other operations are done. For instance, the statement x=y++ would place the value of y into x and then increase y.

In most programming languages it is valid to have a statement such as x = x + 3 as the = means assignment so the statement would take the value that is currently in x and increase it by 3. Equals is represented by two or three equal signs as will be explained in the next section. Applying mathematics to the value in a variable and storing it back into itself is a very common thing to do in programming so there is a shortcut for doing these operations. By placing a mathematical operator (+, -, *, /) before the equals sign you tell flash to do that operation on the left-hand variable. The statement x *= 2 would be resolved as x = x * 2. While this doesn’t sound like that big of a time saver, if you use long variable names you will quickly come to appreciate this shortcut.

More advanced mathematical operations, such as sin and cosine, can be done by using the Math class. You can call these functions simply by using the format Math.function(). I will explain these functions as we use them, but any book focused on JavaScript programming would have them.

Strings, a term used for a block of text, also can use one particular math operator. That being the + operator. Adding strings, better known as concatenation, simply joins the strings together. Adding a number to a string concatenates the string equivalent of the number to the end of the string. This is a problem area for JavaScript as it will convert types on you so if it thinks the variable num is the string “2” then the statement num = num + 2; would result in the value of “22”.

Saturday, March 17, 2018

3.1-Comments Controversy


Comments are simply blocks of text that JavaScript ignores. While this may not sound useful, the purpose of a comment is to provide a way for the programmer to leave information about what the script does so that when he or another programmer comes back to the script at a future date they will be able to understand what is going on. Some programmers feel that comments are useless, but I personally think this is largely due to the comments explaining how the program works instead of the more important why the code is written this way, what assumptions is the code making, when is this used, where is more detailed information on the algorithm, and who wrote this mess. There are two types of comments. Single line and multi-line comments.

Single line comments start with a double slash (//). Everything on the line after the slashes is the comment. The double slash can start anywhere on a line and can even be on a line that has other programming statements on it. Just remember that anything on the line after the comment is not going to be seen by the compiler.  Multi-line comments start with a slash immediately followed by an asterisk (/*). The comment ends with an asterisk followed by a slash (*/). Anything between the start of the comment and the end of the comment is part of the comment.
Here is some examples:

// single line comment here
/* A multi-line comment here.
 * Note that the asterisk on this line is not necessary.
 * Asterisks are only included here to make the comment look nice! */
 /* A multi-line comment on a single line is allowed */
x = x /* they can also be in the middle of a line of code */ + 4;

There is another type of comment that you may see that starts with /** and ends with */. This is essentially the same as a multi-line comment but there are documentation utilities that will extract these comments and convert them into some documentation files. Often these comments will contain tags prefixed with @ which indicate to the document generator about what type of information is being presented.

One of the pleasant things about compiled programming languages is that you can have as many comments as you wish and when the program is compiled all the comments will be automatically removed from the resulting file. This is not the case with JavaScript but with a utility called a minifier you can get the same results. The idea here then is you document your code and use meaningfull variable names but when you run it through the minifier you end up without comments and have short meaningless variables so the code will dowload faster.

There are many programmers who do not use comments. The primary reason for not using comments is the amount of time it takes to write comments. If the class is going to be used by other people there really is no reason to not write comments once the code is in a stable state. Things that should especially be noted within comment blocks is any type of restrictions or requirements that a method or method parameters require. To-do and assumptions can also be placed in this comment block.

One interesting argument that I heard for not commenting is that comments can become outdated and therefore be incorrect. What I don't understand, and have yet had explained to me satisfactorily, is how a competent programmer could see a comment that his or her changes is making invalid without him or her altering the comment or making note of the changes. This is a real problem as when there are invalid comments in a project, programmers can be misled. Assuming a piece of code does what the comment says it does is just human nature. When bug-hunting, however, one should be looking at what the code is doing as it is a bug because the code is not working the way it is supposed to be working which means that all code, even well commented sections, should be suspect until proven otherwise.

Sadly, in the real world, unrealistic deadlines make proper documentation of code hard if not impossible to do. If comments are too burdensome to write, then at a minimum you should be attempting to write self-documenting code.  This is code that uses very clear names for functions and variables that makes what the code is doing obvious. The problem here is what is obvious to one person may be a complete mystery to another person. Another problem with self-commenting code is that it is fine for explaining how the code is doing something but does nothing about explaining the who, what, why and when aspects of the code, which is the real reason that comments exist.

Related to the controversy is when should comments be written. My approach is to only write comments while I am coding a section if I am doing pseudo code for the section in which case that pseudo code is written out and then filled in as I write the function. Once I have a section of code working properly I try to go over the code to clean it up where necessary and add comments to explain why the code is the way it is.

My code is not the best example of well-commented code but when I have gone back to some of my older code, I have been shocked by how much just the bare amount of commenting that I put into a project has helped. The key areas missing in my code are assumptions about how methods are going to be used are not listed, allowable ranges are often not listed, and unit types are assumed to be known.  I recommend people who do not document their code look at code they have not had to deal with in a couple of years and see how well they understand it.

Saturday, March 10, 2018

Chapter 3: Procedural JavaScrip


One area where Animate is very different from programming in Flash is the scripting language. Flash used a language based on ECMAScript called ActionScript. As browsers don't natively support ActionScript and HTML Canvas projects need scripting, the language you use to program Animate games has changed from ActionScript to JavaScript. Both languages are based off of ECMAScript so ActionScript programmers will have little problems adapting but there are differences between the two languages.

JavaScript is the scripting language that is used by browsers to allow more complex pages. People often confuse Java with JavaScript but they are not the same thing. The name came about when Java was starting to be added to browsers to allow more complex content. Netscape was working on their own scripting language and there was a decision – sources vary on the details – where the scripting language was altered to be more Java-like so Java programmers would also be able to do simpler scripting using JavaScript.

Programming is interesting as it borrows aspects from science, engineering, and art. As a result, there are many ways of accomplishing the same thing. This has resulted in many different methodologies on how to write a program. In the early days, we had procedural programming in which programs are written with one main block of code that may call subroutines. Object oriented programming adds the concept of classes and inheritance, which we will cover in a later chapter.

The core concepts behind procedural programming happen to be the core concepts needed for other types of programming so it makes sense to learn programming from a procedural methodology before going into other methodologies. This chapter will cover the procedural aspects of the language starting with the surprisingly controversial topic of “Comments Controversy”.

The “Variables and Math” section covers the concept of variables and how they are used in mathematical operations. JavaScript is a dynamic programming language which means that variables can change their type.

The main reason for writing a script is to handle situations which have different outcomes based on the current state of the game. JavaScript handles conditional states using an if statement which we will cover in “The If Statement”.  For complex forms of the if statement, we have an easier to read form known as the “switch”

Expanding upon conditional execution is looping. In the “Looping” section we will examine the evil goto statement, the while statement, the do statement, and the for statement. These statements go together with manipulating blocks of variables which we call “Arrays”.

 We will then conclude this chapter with a very brief look at objects in the section surprisingly named “Objects.” This is entering the territory of object oriented programming but is necessary to cover before we start creating our first game in the next chapter.