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.

Saturday, March 3, 2018

State of Blazing Games Porting March 2018


Last week we finished off chapter two. My plan for this blog is to have site update information and making of/postmortems for released games between chapters. The only games that have been released since chapter two is NIM and Video Poker. The creation of both of these games are part of the book so they will be covered in the book.

For porting work, I am in the process of porting Coffee Quest to Unity. I am doing this the hard way by porting my Coffee Quest FS engine that has been started and stopped many times to Unity. Having an engine contained within another engine may not make the most sense, but using the data format I developed for the FS engine will make porting the first four games easier then redoing them in pure Unity and will allow for me to move away from Unity in the future if necessary. Using Unity will give me a lot of features that I need to finish the FS engine so effectively lets me get the games done quickly while giving me the option to create my own pure engine in the future.

Another feature that it gives me is the ability to create a high-def version of One of those Weeks. This is something that is heavily under consideration with the decision to be made once I am further along with the FS port. Sadly the number of hours I have devoted to this are very few but as I don’t need to finish CQ until later this year (if I am to stick to the rough schedule I set up in January).

For those wondering, FS does stand for Five-Six and was the engine that I was developing for Coffee Quest Five and Coffee Quest Six. If the port of the first four games in the series goes well, then it is extremely likely that my CQ5 curse will be ended and I will finally be able to finish that game! More on this when I know, but don’t hold your breath.

Speaking of my schedule, I realize that my plans for posting Nightmare Maze in October may not be the best plans as it is the second game I create in the book, not the last like the original book. For that reason, I am going to use it as my Friday the 13th game in April, so July will be the original 13 spikes and October will either be thirteen spikes unlimited or another horror game which I will decide later.

The next 8 weeks will be chapter 3 followed by my next state of the site update and a couple of making of posts. Chapter 3 is a very quick course on JavaScript!

Saturday, February 24, 2018

Script Soup


Games are not movies. Movies are linear with no interaction. Games may have a linear story, though often that is not the case, but they have interaction. Interaction means that the application will behave differently based on what the user is doing. The best example of this would be the user clicking on a button. The Animate movie has no idea when the user is going to click on the button. Likewise, if there is more than one button, the animate app is going to need to know what to do based on what button is pressed. To deal with this, we need a scripting language.

A scripting language is just a programming language that is was created specifically for handling domain specific activities. In other words, scripting languages tend to be specialized. Often, a simple scripting language grows over time and you will end up with what could be a full-blown programming language if only it didn’t require the application it was attached to. This is pretty much the case with JavaScript.

JavaScript is loosely based on the Java language, which itself is based on the C++ language which is an object-oriented version of the C language. In other words, understanding JavaScript will make it easier to learn real programming languages like Java or C++. One of the (many) downside to JavaScript is that it is slow because it was designed as an interpreted language. Explaining the difference between compiled, virtual machine, and interpreted languages is a bit beyond this book but essentially computers only know their specific machine language (which depends on the processor being used). Compiled languages, such as C++, convert their source code into machine language. Virtual machine languages, such as Java, compile into an intermittent machine language which then gets converted into the machine language of whichever machine is running the code. Interpreted languages convert the script into machine language as it is being run.

The scripting language itself is not enough for Animate, it also has a library of functions that are used to actually do the work. Originally Flash used a JavaScript variant called ActionScript which was JavaScript but with proper types and classes. The scripting language had a library of classes for manipulating movie clips and other aspects of the animation. When HTML5 started appearing, several Flash-like libraries started appearing for JavaScript. One of the more popular ones was Create.js. Adobe decided to migrate to Create.js instead of writing their own JavaScript library so when you are using an HTML5 canvas in Animate, you are creating a Create.js JavaScript application.

Create.js is actually a collection of four different libraries. These libraries can be used individually, but tend to be grouped together. As Animate generates a lot of the code for you, the bulk of the code that will need to be written is game logic code with direct manipulation of the Create.js very rare and often only to adjust already existing objects.

Easel.js is the heart of Create.js. This is the stage that the animation occurs on. The library tracks sprites and movie clips and is able to take the scene graph that results from the position of these objects and is able to draw a frame on the HTML5 Canvas. The HTML5 canvas is a special API for drawing things in JavaScript but is only for 2D images. There is an extension to this canvas called WebGL which lets the canvas take advantage of accelerated 3D graphics. An experimental version of Stage.js using WebGL is available and is distinguished from Stage.js by being named Stage.gl. I may cover StageGL in a future book.

Tween.js handles the animation aspects of the program. As explained earlier, tweening is simply changing an aspect of an object over time so it is possible to use Tween.js for non-animation related aspects of a program.

Sound.js handles the sounds that a program makes. JavaScript sound handling is a mess so having a simple API for getting sounds to play is nice. The downside to this API is that the sounds need to be loaded before they can be played. This is the reason the final API in the Create.js suite exists.

Preload.js is an asset preloader. This simply means that you give it a list of assets that you want your program to use and it will load them in. The preloader generates events to let your program know when it has loaded assets so you can even create a fancy loading screen if you wish.

We will cover the Create.js API as we need to, with my follow-up book going into much greater detail. As games require interaction to be playable and interaction requires some code to handle it, we are going to have to at least learn the basics of JavaScript. Still, in many cases you can get away with a minimal amount of simple JavaScript if the game is not too involved and by the end of this book you will have a good grasp of what games will require the most code and can pick your projects accordingly.

Saturday, February 17, 2018

The Key to Animation

Animate uses a layer based keyframe animation system. For people who are not familiar with the creation of animation, this sounds complicated. It is a very quick and effective way of creating animation as the animator is just setting up guidelines for the computer to generate the majority of the  frames.

A keyframe is essentially a frame of the movie. Within the frame you place objects where you want them to be. Every time you want to change the contents of the frame you create a new keyframe. This by itself is not that powerful. Where the power comes from is with tweening. Tweening is a method where you let the computer animate the object for you. The word tweening is a concatenation of the term “inbetweening” which is where the lead animator would draw the key frames and junior animators would draw all the frames between the keyframes. Animate has two types of tweening. Motion Tweening and shape tweening.

Motion tweening moves an object from the location it is on the starting keyframe to the location it is when it is on the ending frame. You can also apply rotation to the object that is moving. While technically not motion, you can also adjust any color adjustments (such as the alpha level) and the adjustment will smoothly transition between the frames. As objects in nature don’t move at steady rates, you can use leading to have the object start the motion at a faster rate and slow down as it approaches the end keyframe or have it start slow and speed up as it reaches the keyframe. The image below illustrates the difference between the three types of tweening.




For even more advanced animation effects, you can have guides. Guides let you specify the path that a moving object will follow. You can have the object follow the path while maintaining the same orientation or you can have the object orient itself to the path. My April Fool series of games has a title sequence where each letter has a winding path to it’s ultimate location. The screenshot below illustrates the different paths that the letters follow to reach their final location.


Shape tweening is a bit complicated. Shape tweening is when you have one shape and it transforms itself into the second shape. This is easy to do, but hard to do well. You simply need two shapes, a starting shape on the start keyframe, and an ending shape on its ending keyframe. To make sure the shape morphs the way you want, you add key points to the shapes. These points help Animate determine where the lines and points that make up the shape should line up after the end of the tween. Here is an example of a square turning into a star with the red shapes being the onion skin outlines of the frames between the square and the star.



An Animate movie consists of one or more layers. Layers go from back to front with closer layers overlapping further layers. Every layer is independent of the other layers. In other words, you can have keyframes in one layer but not any of the other layers. Animate lets you define as many layers as you need and lets you group the layers into folders. It is advisable to keep each animated object on its own layer as not doing so will result in animate creating a separate tween object in the library which often leads to problems.

The animation system is the primary reason why you would choose to create a game in Animate instead of creating it from scratch using the free Create.js libraries. While everything listed above can be done manually in Create.js, having a tool that generates all the source code for you is nice. If your game is a very heavy animation-oriented project, then using Animate makes sense.

Using animate to create the animations for a game project but then doing that project manually using Create.js or some other library (or even another language) can also be a consideration. In a team environment, this approach can be very cost effective as you would only need creative cloud for your art team while the development team can have other development tools.

Saturday, February 10, 2018

Symbolizing things


Animate revolves around symbols. Symbols are a very efficient way of building movies, as a symbol only needs to be loaded once. After it has been loaded, you can create as many copies - known as instances - as you want to. More importantly, every instance of a symbol can have properties independently applied to it. You can adjust the size, orientation, and skew. You can also apply tinting, control the brightness, adjust the alpha (transparency) level. There are three basic types of symbols that Animate uses. The Graphic symbol, the Movie symbol and the Button symbol.

Graphic symbols are just a drawing converted into a symbol. The drawing can be as simple or complex as you desire, and can even contain other symbols as part of it. These tend to be vector based, but it is possible to use bitmaps for graphics. Flash used a very compact binary format for vector images making them take significantly less space than bitmaps in many cases. Animates’ HTML5 exporting converts these vectors into Create.js shapes which take up significantly more space, especially if you are not letting Animate compress the images.

A movie symbol is essentially a movie within the main movie. You have as much control over an Animate movie symbol as you do over the resulting movie. You are not limited to having a single level of movie clip as movie symbols can contain other movies as part of them, which can contain movie symbols within them which can contain movie symbols within them and so on. While this recursive nature of movie clips adds a lot of flexibility to creating animations, movie clip objects are fairly heavy in memory and processing requirements so having too many nested movie clips can slow things down substantially.

A Button is simply a special symbol that has special actions associated with it whenever the mouse is over it or the mouse has been clicked while over it. To be more precise, a button has 4 frames associated with it. The up frame is simply the normal appearance of the button. The over frame is how the button looks when the mouse is over it. The down frame is what the button looks like when the mouse is over it and the mouse button has been pressed. Finally, the hit frame defines the over/hit areas.

The hit frame may seem confusing to people new to Animate. This frame is not actually seen by the viewer, but is instead used by Animate. How it works is any area in the hit frame that is solid will react to the mouse being over it while an area that is not solid will be ignored. While touch users will not get the mouse over effect, the hit area is used for determining if a touch results in a down event.
Some of you may be wondering why you would want or need such a thing? Couldn't you just use the existing button image? The answer to that is you could, but then the button would only work if the user had his or her mouse positioned in a solid part of the image. In some cases, such as with our Play the Game button, we want the button to react if the mouse is within a block or an area that covers more than the frames cover. Conversely, you may not want a rectangular region or even the entire button to be clickable. The hit mask gives you total control over where the button can be clicked.


As an example, here is a button that I use for switching a sound from enabled to disabled. The top right image is the normal image and is what the user will see normally. The top-middle image is what will be shown to mouse users who move the mouse pointer over the image. The top-right image is what is shown when the button is clicked or touched. Finally, the bottom image is the hit map that is used for determining if the mouse is over the image.

Symbols can be created in animate simply by drawing something and then selecting the drawing and choosing the “convert to symbol” option from the right-click menu or the modify menu from the menu bar. Creating a symbol adds it to the library. Empty symbols can also be created from within the library, though personally this is not something I do. The library is a file-folder structure allowing you to easily arrange your symbols to make finding and working with them much more efficient. This is especially true when you get to larger projects that contain hundreds or thousands of objects.

Libraries also have the benefit of being sharable between projects. Animate makes it easy to move symbols between different libraries allowing you to create a standard set of library symbols that can be copied between libraries. There are also built in tools for converting a selection of library symbols into image atlases or stand alone files which can come in handy for environments where animators create assets in animate then hand them off to developers who are using pure JavaScript (or other language for non-HTML projects) for creating the application.

Saturday, February 3, 2018

Drawing Things Out

Animate, as mentioned earlier, is a vector based drawing and animation tool. All drawing in Animate is built around shapes. Shapes are made up of a series of connected lines and curves. You create the shapes by using basic building blocks such as lines, rectangles and ovals. You also have text, which can be treated as text or converted into a shape so that you can modify the shape. By breaking apart text twice you are given the vector shape of each character and can then use the arrow manipulation tools to alter the letters which can be great for creating title text quickly.

Shapes can have an outline and a fill, or can be just one of the two. The outline has a color, a thickness, and a pattern associated with it. One of the most unique thicknesses is the hairline. This is a special thickness as it will always be drawn as thinly as possible.

The fill of a shape can be a solid color, a gradient, or a bitmap fill. Gradients are a series of colors that gradually change from one color to the next color in the series. You may have as many colors in a series as you desire and can vary where in the gradient range the colors will change. Gradients can be linear or radial and the orientation, scale, and center spot can be adjusted. A bitmap fill is a bitmap image that is used to fill the shape. Bitmap fills are tiled, though you can adjust the orientation, scale, skew, and center spot.

For more complex shapes you can use a pencil tool. The pencil tool takes whatever shape you draw and turns it into a series of lines and curves. You can control how close to what you draw the pencil will be, with the more accurate the representation, the more anchor points in the object. The pencil tool is supposed to be intelligent, so it will try to figure out the shape you are drawing picking the most appropriate approximation it can come up with. The pen tool is just like the pencil tool except instead of lines it deals with fills.

The fountain pen tool lets you build a spline shape. The mathematics and techniques behind splines are interesting but way beyond this book so I will try to explain in simplified terms. A shape is made up of several points that define the basic shape. These points are connected via lines which can each be edited separately. For shapes made of straight lines this is fine, but for curved shapes, splines are used. Each line has additional points (weights) that control how much the line curves between two points. Curves can be controlled by adjusting the weight points for that line segment. You can adjust these points by using the sub-selection tool which looks like a white pointer.  While editing a shape this way can be painful, it gives you extreme control of the resulting shape.

The basic drawing tools within Animate are enough to do quite a bit and may be all that an artist needs. If better tools are needed, a vector package like Illustrator can be used. It is even possible to import a bitmap image and use a tracing tool that will convert the image into a vector shape.


Saturday, January 27, 2018

The Road to Animate

Younger readers may not fully appreciate how much the internet has changed over the years. When I started using the internet in the nineties it was done with a device called a modem which plugged into your phone line meaning that when you were connecting to the internet you were making a phone call to your internet service provider. The modem I originally had was a 28000 baud modem which means it was able to send and receive 28000 bits or 0.028 megabits which is roughly 3k per second under optimal conditions. This is really slow so video was not really something that you would have on a website. Even images were really slow where with large images you could actually see the image being loaded. This is why vector based animation systems actually made sense and why Future Splash was pretty impressive for its time. Instead of sending the bits that make up the image, vector systems would just send the points and edges that make up the shapes. For simple shapes, like those in early internet animations, this was significantly less information than the bitmap representation of the image so could be transmitted much faster.

Future Splash was competing with a technology that Macromedia was pushing called Shockwave which was acquired by Macromedia when they purchased MacroMind for their Director game making software. Macromedia acquired Future Wave, the company that was behind Future Splash, so they could add the vector animation tool to their shockwave platform. This is the reason why Flash binary files have the swf extension which stands for ShockWave Flash.

When Java arrived on the scene Java applets (note that Java and JavaScript are not the same thing) were still thought to be the future of interactive web pages. Browsers were being shipped already loaded with Java while Flash required a plug-in program be downloaded and installed into your browser. The Java craze was so strong that even Macromedia had an optional Java version of their Flash player. I was hired to see if it would be possible to have a Flash game where the animation was handled by the Java-based Flash player and game logic would be written in Java. This proved to be clumsier than expected and pure Java solutions were chosen for the project.

While I think Java could have taken control of the browser, this ultimately failed due to a conflict between Microsoft and then Java-owner Sun Microsystems. Sun wanted Java to be a standard that would work the same on all browsers while Microsoft wanted to be able to make Windows the operating system of the internet and added extensions to the internet explorer version of Java that made it work better on Windows due to the ability to access Microsoft APIs such as Direct X. A court battle ensued, Java on the browser stagnated, and alternatives for Java started being looked for.

This is roughly the time that ActionScript was added to Flash. While not the greatest scripting language, this made the product useful for games and other interactive web content and ultimately replaced Java as the go-to technology for interactive web sites.  I started using Flash and wrote the original Flash Game Development book that this book is based on and everything was good with the exception of the occasional exploit, too many sites having intro movies created in Flash, and many extremely annoying interactive ads which happened to be written in Flash though would have also existed in any other alternative had there been an alternative with a large enough market share.

Flash was still a very strong standard when Adobe bought out Macromedia. Unfortunately for Adobe, things were about to change thanks to a fruity company releasing a phone a couple of years later. While saying that iPhone not supporting Flash was the cause of its demise is not the full story, it was certainly a big factor. The idea of plug-in for browsers was starting to be looked on as a negative factor as plug-ins were increasingly the target that hackers used to attack browsers.

The ultimate nail, in my opinion, was the release of HTML5 and the Canvas API (which if I recall correctly was an API designed by Apple for their browser). This allowed for web developers to do everything that Flash could do right within the browser knowing that all users with a browser could run the program. Granted, the HTML5 apps were slower and larger than the equivalent Flash files, but they worked without any plug-ins.

Flash was not just used for creating web pages, but was still a popular tool for animation studios. With the death of Flash on the browser rapidly approaching Adobe decided to handle the death of Flash by renaming the tool Animate which reflects the target audience for the tool. To help support browser developers, Adobe did introduce the HTML5 stage which allows the creation of HTML5 projects that convert Flash vector objects and animations in to JavaScript using the Create.js library. The ActionScript code is not currently converted to JavaScript so any interactive code must be written in JavaScript using Create.js library calls.

So while Flash is dead, Animate is not and can be used as a tool for the creation of HTML5 animated content. For people who have used the Flash development tools, things have not changed that much and you will quickly find your way around the tool. For those not familiar with the tool, there are several built-in tutorials and a decent manual that can be downloaded.

Saturday, January 20, 2018

Flash is Dead! Long Live Animate!

The first exposure I had to Flash was when I encountered some FutureSplash animations in the mid-nineties. This was interesting technology at the time as back then most people were using telephone lines and modems to get internet pages so having streaming animated video was simply mind boggling. Back in those days, streaming video was small thumbnails and generally didn’t work well.  In “The Road to Animate” we will look at this history as well as my personal history with the technology.

One of the biggest draws of using Flash, now Animate, was animation. Before you can animate something, however, you first need to draw it. “Drawing Things Out” covers the basics of the drawing functionality that comes with Animate. “Symbolizing things” explores Animates’ symbol and library which is vital to making objects move. “The Key to Animation” explores Animates’ keyframe animation system which really is the reason that you would want to use Animate over writing an HTML5 game purely in JavaScript, even when using a library such as Create.js.

We conclude this chapter with “Script Soup” which takes a look at how scripting is involved in the game making process. This is a rough exposure to ECMAScript, ActionScrpt, and JavaScript with a general overview of the Create.js library.

Personal notes


After finishing my Bachelor degree and looking back at my site I realized that there was a lot on my site worth saving. I was not sure what route to take but essentially knew that I had to at least attempt to salvage some of the games. Finding my old book on Flash and deciding to undertake this book project, which is now a two-book project and I suspect additional volumes may be added in the future (possibly for StageGL, Kotlin, and Web Assembly). The reason I decided to break the book into two separate books was simply that after playing around with Adobe Animate CC, I was disappointed with what the tool has to offer and found that most of my work was being done editing Create.js code. You do not need an expensive tool to do that which is why I broke this book in half. With that said, most of the material in this book is still applicable to people who want to go the pure Create.js route so if you have no plans on getting Adobe Animate CC, you can still benefit from reading this (especially now that it is being freely posted on my Blog).

Saturday, January 13, 2018

HTML5 Games using Animate CC Overview

A long time ago, back in 2003-2006, I wrote a virtual book for Blazing Games which covered the creation of ten Flash games. When we closed down Blazing Games in September of 2014 the IP rights to the games on the site went to me, including the Flash Game Development book. With browsers moving away from Java (right now the Java games won’t work) and Flash (in 2020 support for Flash will cease), all these older games need to be moved to HTML5 which uses JavaScript. Browsers are also starting to support Web Assembly, which may be a book on it’s own depending on how well received this book and the follow up HTML Games using Create.js are received. When I say HTML5 I am talking about the combination of HTML, CSS and JavaScript which happens to be the common usage.

As Flash is dying or dead (depending on when you read this), games created for it need to be ported to another language so I decided that it would be a good idea to revisit the 10 games that made up the book and port them to HTML5. Five of them (NIM, Nightmare Maze, Video Poker, Pent Up Anger, and String Along) were ported taking advantage of Animate CC to port them to HTML5. The other five games in the book will be covered in a second book HTML5 Games using Create.js which can be developed without purchasing any additional tools for your computer. This book will cover Bomb-NIM, Cribbage Square, 3D Tic-Tac-Toe, Lights Out, and “Dragon and the Sword”.

Chapter 1: Introduction – An overview of the book, and what you are reading right now. I am skipping a bunch of less-revevant sections of this chapter.

Chapter 2:Flash is Dead! Long Live Animate – Quick look at the history of Flash, how the new Animate CC is a replacement for Flash, and what Create.js has to do with all of this when creating JavaScript games using Animate CC.

Chapter 3: Procedural JavaScript – A very quick course on the procedural programming aspects of JavaScript with a brief look at how it compares to ActionScript.

Chapter 4: NIM – We finally get to our first game, which is a variant of NIM. This game tries to do as much as possible with Animate and as little as possible with JavaScript.

Chapter 5: Objects in JavaScript – we get into the object oriented nature of JavaScript which will be used for creating our own objects and a library that can be shared between similar games.

Chapter 6: Nightmare Maze – The game that became the first episode of my 46 part One of those Weeks game is created as we look at adventure games.

Chapter 7: Card Classes – Creating code to be shared between multiple games is a common activity so this will be demonstrated by creating a card class.

Chapter 8: Video Poker – The Card class that was created in the previous chapter is used to create a virtual Video Poker machine.

Chapter 9: Pent Up Anger – Making base game of Pent Up Anger

Chapter 10: Pent Up AI – How to create artificial players for a game is demonstrated by adding computer opponents to the Pent Up Anger game.

Chapter 11 String Along – Arcade games are demonstrated using a variant of the classic snake game.

Chapter 12: Conclusion – A summary of what was covered and a look at the second book in this series.

Saturday, January 6, 2018

Calendar NIM Review

Normally I like to have a postmortem or a making of article about the games that I have just released, but the nature of my Calendar NIM game makes an explanation of the twelve months a bit more appropriate. Each image represents a game that I am hoping to release during the year, though it is subject to change. The games chosen are not the only games that I will be releasing, but are simply the ones I am positive that I can finish though are subject to change and unexpected delays. Still these games are pretty certain. For those of you who haven't looked at my Calendar NIM game, it is located at http://spelchan.com/games/y2018/calendarNim.php



January is a 2018 New Years image that was released by LMoonlight for free and is used to represent the Calendar NIM game itself.

February is Video Poker, which was a game that I created for my original Flash Game Development book which is in the process of being re-written for HTML5 development which will start being posted on this blog next week. This game has already been completed so this is a guaranteed release.

March is when I release my Easter game which is the egg generator. While this was really low on the vote, the generator is used in two other easter games so I am going to port the generator first. This will be challenging as the masking technique I used is  not supported in Create.js so I will need to come up with a different approach. As this game is not going to be released until the end of the month, I will probably take the opportunity to release my NIM game as a bonus.

April 1st is Easter so my April Fool games will have to wait until next year. The thirteenth of April is on a Friday so the original version of thirteen squared spikes will be the choice for that month. This game has already been completed so it is a guaranteed release.

May 25th is towel day so it makes sense to release Towels for Earth. I am not sure why this game is so high on the voting chart but this is the most appropriate day to re-release the game. I have not done any work on it at all but it is not a difficult game (it was created in a game jam after all) so this shouldn’t be a problem. As this is late in the month, I may also release Pent Up Anger which I have already finished.

June is really subject to change but I am planning on porting Fleet to C++ and using emscripten to convert it to asm.js or to web assembly. I started playing around with emscripten for my 2600 emulator project but pretty much have gone the Kotlin route with that project so this would be a good project.

July is another month with a Friday the Thirteenth in it so the Thirteen Spikes Unlimited (TSU) port would possibly be ideal. The current version of TSU was written in HAXE and compiled to Flash as there were issues with the JavaScript compilation. I will see if things have changed with that and if so this is simply re-compiling the project. If not, I have the core of Thirteen Squared Spikes to use as the base of this so it should be a very quick port.

August has String Along set up as it’s game which has already been completed so is guaranteed.

September is Coffee Quest which will be a WebGL game. As with Fleet, I will likely port this game to C++ and use emscripten to convert to web assembly and Asm.js. The construction set will not be part of this, but the extra maps may be. At the moment I am thinking of going weekly for september releasing a new map each week. This is just speculation at the moment with a final decision on what I will do to be made in September.

October is Nightmare Maze which happens to be the first episode of One of those Weeks. It is being referred to as Nightmare Maze as it is part of my book. I have big plans for One of those Weeks so there will be additional news about the project later this year (I hope).

Let’s face it. Coffee Quest was a very simple game, with the series only really starting to take of with the release of the second game in the series. This is why November will be Coffee Quest 2. It will be built on top of the Coffee Quest code base so will be in whatever language Coffee Quest ends up being released in. Again, I may release the extra maps every week but that is not certain yet.

Finally, also likely using the Coffee Quest engine, will be the high-def version of Santa’s Snowball. Higher resolution, better graphics, better sound, and 360 degree movement with an automap will make this Christmas game what I wish it was in 2017.

There may be additional surprises throughout the year, hopefully one involving One of those Weeks, but even without the extra releases I don’t think the year is too bad.