Saturday, August 11, 2018

4.4 Limiting Layers


In theory Animate lets you have as many layers as you desire. However, you should try to limit the number of layers that you use to make managing the movie easier. Designer overload is caused by the designer having to deal with a huge number of layers. When you have too many layers to deal with, it becomes harder to find the layer you need and if there is interaction between layers that are of substantially different levels, then work can be frustrating.

To layout the game, we need to get the 40 gems to appear. If you look at screenshots for the game you will see what the final layout looks like. The problem here is that 40 gems would result in 40 layers. That is a lot of layers to keep track of. So instead of forty layers, let us group each row into a layer. Extra conservative designers would probably have all forty gems in a single layer, but I originally designed this around four layers.

Those of you familiar with Animate CC probably already know that Animate CC tends to act funny when you try having animation on a layer that contains more than one object. It wants to only deal with one object for a tween so when it has many to deal with it automatically generates its own movie clips to hold intermediate tweens. This is almost never what you want so it is best to avoid that situation. As that is the case how are we going to animate the gems? After a bit of thought, I realized that at any given time, I would only need five gems animated at a time. This can be handled by creating five animation layers.

The animation is simply handled by assigning gems to animation layers. When the gem reaches its final position, the layer it belongs to then adds that gem to it's objects. The animation layer is again free to hold another gem.

To demonstrate, lets deal with the first few gems. We create the gems outside the screen in a pattern that wraps clockwise around the screen. The first gem gets assigned to GemAnim1, which is our first animation layer. It uses simple position keyframe animation to move (the first keyframe is where the animation starts, the last keyframe has the gem where the animation ends and a motion tween is placed between the two keyframes). The second gem uses GemAnim2, the third uses GemAnim3 and so fourth. Gem number 6 has no layer, but as it will not start to be animated until gem 1 is in it's final position, it can use GemAnim1. It can do this because there is no longer an object in this animation layer as a gem has been added to the appropriate gem layer. Gem 7 is not needed until gem 2 has been placed in it's layer, so it will use the GemAnim2 layer. And so on, until all forty gems have been animated.



Saturday, July 28, 2018

4.3 The Play Game Button

The play game button is made by just typing the words "Play the Game" in a large font, converting the font into vector objects by using the break apart command twice and then coverings the whole group of objects into a button symbol. The color of the text is changed for the over and down frames of the button. A solid box that covers the text is used for the hit button.

The appearance of the play game button is easily handled by having a keyframe with the button outside the screen and a second keyframe with the button in the final position. A motion tween is added between the two frames. Likewise, the same thing is done with the other two buttons.

For a button to do something, some JavaScript is needed. Typically, a button needs three pieces of JavaScript which are letting the system know you want to listen to the event, an event handler for handling the event, and letting the system know you no longer care about the event.

The first piece is simply some code to let the system know what function is going to handle the button. It is possible for the same handler function to handle multiple buttons, but that will be covered in the future. The code can be placed in several places with no strict rules on where you want to place it. For this game, I have created a layer on the main timeline called “Code” where I can add code to frames.

To associate code with the button, the button must be given a name. This is done by typing the name into the instance name section of the properties panel (in the left corner of the properties panel). In our case, we are calling the button “play_btn”. The code to let the system know you want to do something when the button is clicked is simply:

this.playGameBtn.addEventListener("click", playTheGame);

The method addEventListener tells the button that when the indicated event, in this case the Click event though other events can be listened for, it is to call the function playTheGame. This is where our approach to handling multiple scenes becomes an issue. Multiple scenes need a way of communicating with each other. The easiest way of dealing with this issue is to have some global code that all the scenes can access. Animate provides such a script, so the code for handling clicking the play game button will be placed there.

This global script needs access to the main scene movie. To do this we simply have the main movie call a registerStage function which stores the stage movie into a variable movie which gives us the ability to change scenes and access functions within any of the movie clips that we are using as scenes.

function registerStage(stg) {
    gameStage = stg;
    gamestate = GAMESTATE_PLAYER_PLAYING;
    gemsRemaining = 40;
}

The playTheGame is the function we will be writing to handle the start of the game. The function simply is a function that contains the code that is to be run when the event happens. In our case this is very simple:

function playTheGame() {
            gameStage.gotoAndPlay("Game");
}

The gotoAndPlay() method simply tells the main movie that it is time to start playing from a different frame. If we had multiple buttons that went to distinct parts of the movie, we could easily set up each button to go to a different frame of the main movie.

Saturday, July 14, 2018

4.2 Title Screen

Normally when I create a game, the title and menu screens are the last screens that are created. For this chapter, however, I am going to create the games title sequence first. This demonstrates one of the big differences between Flash games and Animate HTML5 Canvas games. As of Animate 2017, there is only a single scene so switching between scenes is not allowed. The normal approach to creating a game is to break up the different screens of the game into separate scenes. For Animate, this can’t be done but there are several different alternatives. The approach that I will be taking in this book is to break the game up into separate movie clips that act like scenes and have a single master movie that contains the movie clips as separate frames of the main movie.


 The screen starts off blank. Seven gems then grow onto the screen in what at first seems to be a random pattern. Once the gems are fully grown the letter N fades in behind the gems. This is followed by three gems appearing to create the letter I and another 7 gems to form the M. If you look at the screen shot of the final logo  you will see what the final screen looks like.


To create this sequence, many layers are used. While the number of layers could be reduced (you will see a technique for that later in this chapter), I figured that for a title sequence, the extra layers wouldn't hurt.

Each gem is on its own layer. When I created this title, I first laid out all the gems into a rough NIM pattern. To make sure that people could read the title, I then used the line tool to create an outline of the letters. I filled the outlines with a solid color and turned each of the letters into a symbol.



The appearance of the gems is stepped so that they don't all appear at once, with additional delays for the appearance of the letters added. Each gem is animated using two keyframes. The first keyframe is scaled to 10% of the original size. A motion tween between the two keyframe's is then added.

The fading letters is a simple alpha blending tween. You start by creating a second keyframe of the letter. The first keyframe is then set to an alpha level of 0. A motion tween is then placed between the two keyframe's.



Saturday, June 30, 2018

4.1 NIM Design

While NIM is a very simple game, it is a good game to start learning game development with. The game is very straight forward in its presentation. The rules of game play are very easy to implement. Most importantly, at least for beginning Animate developers, the game requires only a minimal amount of JavaScript.

While I personally have no problem with JavaScript, I know a lot of Flash and now Animate developers who fear scripting languages. Games, by their interactive nature, require scripting. There is, however, no need to jump right into extensive JavaScript use. Our first project will attempt to keep JavaScript to a minimum.

We already know what the game is about from the description in the previous section, so what is needed is specific details on the game. There are three things that must be decided. What is the object that is being removed, how many objects are there to be removed, and how does the player remove them?

All of the questions can be answered pretty much any way the designer wanted and the game will still work fine. For the object, anything could work, though I look at the object as something valuable that the person would want the last one. To me I think of jewels or gems when I think of something valued. The reason that gems are valued is because they are rare. The bigger the gem the rarer it is. This means that if the last gem is a big gem then it is a very valuable gem.

The number of objects is simply a matter of how many can fit on the screen. Four rows of ten seemed to make sense, so for this version we will have 40 gems. This would also leave room for a space where the user could specify how many gems to take. As the only interaction the user has is select how many gems to take, the user interface is simply three buttons, with a text area to describe what is happening.

Using buttons to remove the gems is not the only way this could have been handled. An alternative interface would be to have the player click on the gem to be removed. This would be intuitive, especially if the allowable selections were highlighted in some way, but without use of JavaScript would be a huge amount of work.

Saturday, June 16, 2018

Chapter 4 NIM

For the next few months I will be posting Chapter 4 of my "Creating HTML5 Games Using Animate" eBook, which is broken into 8 sections. Once that has been completed, I will post an update for my spelchan.com plans. With my Masters program starting in September, I am not sure how much time I will have to devote to the site so hopefully will have a better idea once this chapter has been finished being posted. I do plan on continuing porting a game a month from Blazing Games to Spelchan.com but may focus on the simpler games. I am planning on blocking out time for both porting and my emulator project but obviously if I need the time for my course work and TA/RA duties then those hours will be sacrificed.

While I have seen this game go by other names, I was introduced to the game as NIM. I have no idea why it was called that, but figured that I would stick with the name I am familiar with. The game is a very simple game where you have a set number of objects. Each turn the players can take from one to three objects. The goal of the game is to be the player who grabs the last object.

Apparently this game has been used within the mathematics of Game Theory to demonstrate certain principles. I have also heard that the game has been mathematically solved and that there is a way of playing the game that will guarantee winning the game. I have not researched either of these things, but readers who are interested in this game may want to do research on these topics.

The game has already been posted on my Spelchan.com site for February (NIM). Here is a screen shot of the game:



This chapter starts out with a look at the design behind the game in the section “NIM Design Overview”. Normally when I am developing games, I focus on the game play and getting the core game working before getting to things such as title screens but for this game I am developing the game in sequence. The ”Title Screen” section then covers the creation of the animated title logo sequence with the “The Play Game Button” section explaining how the start game button was created and how to write the JavaScript to activate the button.


With the title screen out of the way, we need to start work on the game so the “Limiting Layers” section covers the laying out of the playfield in such a way that we don’t need to use 40 different layers for handling the layout. As the game is controlled by the player, the “Player Panel” section covers how the user interface element of the game works. Having buttons to remove gems doesn’t do very much unless you are able to remove gems so “Gem Removal” covers removing gems from the game screen. The removal of gems is refined by adding different game states and a computer-controlled player in the “State of the Game” section. Finally, we have “Winning and Losing” which covers ending the game.

Saturday, June 2, 2018

Fleet Postmortem

Fleet is one of the first Java games that I wrote. As the game was written in Java, and Kotlin is a replacement to Java which can compile to JavaScript, I decided to see how well Kotlin works for HTML5 games. The create.js library was used for handling the GUI aspects of the game. To make the game more playable on tablets, I had to rework the user interface quite a bit which makes this more of a re-write than port.

Fleet was released on Spelchan.com on June 1st and is based on the classic pen and paper game that is now played on a board with easily lost plastic pieces. You control a fleet of ships. You have an opponent who also controls a fleet of ships. Your goal is to destroy your opponents fleet of ships before your opponent can destroy your fleet of ships.



What Went Wrong

In the original Fleet, ship placement was done one ship at a time with the player using the space bar to rotate the ships. As I wanted this to work on touch-only devices this meant that requiring a key stroke was out of the question. Dragging the ships around to move them seemed like the ideal touch-based controls. Double-clicking on a ship to rotate the ship became the obvious solution for ship orientation.
While create.js does have some support for drag-and-drop, I still had to write a fair bit of code to get this to work. Getting it working with the mouse was easy but for some reason it would not work on the tablets that I have access to. I finally searched on-line for any information where I discovered that you had to enable touch by using the Touch class. Seconds later I was running it fine on my tablet, but my Dad's older tablet ran very poorly and inconsistently. While I suspect that this is predominantly due to the age and slow speed of the device, I decided it would be a good idea to have the initial layout of the player's ship be randomly generated just like the AI ships so that if a player was having problems moving ships around, they could just go with the default random layout.
Testing the dragging and dropping of ships resulted in the ship often not going where the player was expecting due to the way the sprite snapped to the grid. One solution to this problem was to simply have the grid snapping happen as you dragged the ship but this simply did not feel right. The original version would highlight the grid squares where you were going to place a ship in white or red so I figured that I would do the same thing here but opted for yellow and red. This took a bit of work to accomplish but I think the results are quite nice.

Mixed Blessings

Kotlin is a rather new language that came to the scene more as an alternative to Java programming on Android but with the ability to compile to JVM, JavaScript, or Native it has a lot of potential. I started my Atari 2600 project to try out the language where I found myself enjoying the language. I wanted to see if it could be used for porting games so decided that as Fleet was originally written in Java, it would be a good contender.
One of the nice features of Kotlin is that you are able to use the "native" features of the platform you are compiling to so a JavaScript project can make use of JavaScript libraries and other native features. This has to be specified using the external designation but there is a utility to convert TypeScript definition files into Kotlin definitions so it was simple enough to get a create.js definition. Using create.js with Kotlin always felt like a kludge and its JavaScript nature made working with it awkward for many activities such as tweening.
The biggest downside to using Kotlin and Create.js together is that both are large libraries making the loading time a bit larger than I would like. For a larger project this would be okay, but startup time for Fleet seemed to be way too long.

What Went Right

The AI that I created for the original version of this game was surprisingly good and yet was fairly simple to implement once the base ideas behind it were worked out.  The version of the AI in this game is essentially the same as the original version except that it was cleaned up. It didn't take too long to port the code over and it just work. If all the code I ported went this smoothly, I would have ported many more games by now.

Summary

I think this version of Fleet is a bit nicer than the original though there is still a lot of things that I would have loved to do had I the time. It is possible that I may revisit this game in the future with a deluxe version of the game, but that will not be for a while.
As for using Kotlin for future HTML games, I am still up in the air. If I could find a good cross-platform library with similar functionality to Create.js, then this would possibly be a good thing. Writing my own cross platform library is not likely in the near term, but after I get my Masters it may be something I would think about. I am still wanting to try out the Rust language, so how much I like that language will determine which of the two languages I will be focusing on in the future.

Saturday, May 19, 2018

Towels for Earth Postmortem

This is a postmortem for the game that I will be posting on May 25th for Towel Day which is the HTML5 port of Towels for Earth. Towels for Earth was a game that I created for a Game Jam back in 2013. The theme of the game jam was towels in honor of Douglas Adams. I suspect that there are several Douglas Adams fans who managed to encounter my Blazing Games site somehow as the polls show that there are quite a few people who wanted to see this game ported to HTML5. It is a fun but short missile defense game where missiles are destructor beams and anti-missiles are towels with the player tossing towels at destructor beams to save the Earth.



What Went Right

This was a game-jam entry so it was very quick to port over. I had a bit of time left over from what I budgeted so I decided to add some sounds to the game. The original game is in space for which there is no sound, but purists can simply turn the sound off via a nifty sound toggle that I added. The speaker artwork was taken from another game I wrote that had a sound slider but I didn’t have enough spare time to try and create a slider, but that is probably something I should be doing in the future if I ever get enough spare time, which won't be in the next couple of years.

I started going through some of the public domain and royalty free sounds that I have collected over the years to find a few sounds that would work with the game. While some people may not like my choices, I think they work well for the theme of the game. Sound in Create.js is very easy to play if the files have been downloaded which I am using preload.js to do so this was trivial to add once the sound files were found.

What Went Wrong

I went a bit overboard with the original game and had created a pixel-perfect collision detection routine. This requires the use of bitmap libraries that Create.js doesn’t have and would have been very painful to do – not to mention excruciatingly slow – to do so I reverted to good old-fashioned bounding circles. The wonderful thing about bounding circles is you just find the distance squared between two objects and see if the squared distance is within the combined radiuses. The problem is that if one of the shapes is not spherical, then the collision results can be a bit inaccurate. I don’t really mind too much but suspect that I may hear some complaints about this. I did try to be a bit generous with my circles feeling it is better to have more false positives than false negatives.

Some of you may be wondering why I am using distance squared. This is an old-school technique to save a bit of CPU cycles. Distance is sqrt( (x1-x2)^2 + (y1-y2)^2) which is a slow routine to calculate since square roots are very slow to calculate. On the other hand, radius*radius is very fast to calculate so by forgoing the square root portion of the calculation you can speed up the check while keeping the accuracy of the calculation.

Mixed Blessings

The original game used a combination of background images and vector artwork, but I opted to go with all images even though I could have saved a bit of space by using some vector images. The tradeoff of a slightly larger file size for slightly faster game rendering and a easier coding was arguably worth it. The images I did want to have as vectors were actually fairly large so it wasn’t that much space that I was using. My original plans were to have the backdrops converted into a separate jpeg file while the other parts were stored in a png file so I could get a bit better compression. When using my image view to see how different compression ratios would affect the image quality, I noticed that the images looked pretty good when converted to 8-bit png files with only a small increase in file size so I put all the images into a single image atlas.

For people who still have slow internet connections, these decisions may have resulted in longer loading times. For that I apologize as I know most people with slow internet don’t have a choice in the matter.

Conclusion

Overall, I am happy with how this game turned out. Sound does add a bit to the game, but sound and music is my Achilles heel. I really have to start trying to add more sound to my games in the future.

Saturday, May 5, 2018

State of the Site May 2018 update

With my being accepted into a Master of Science in Computer Science program I will be extremely busy for the next couple of years. I do want to keep up with my site, which is not that time consuming if I predominantly post ports of the games from Blazing Games so both this blog and my homebrewgamejam.blogspot.ca blogs will continue while I am in university. The frequency of the updates is going to be shifted from weekly to alternating between the two blogs with each having an article posted every other Saturday. If things get too hectic, I may cut back to a monthly update but am going to allocate a block of time towards the site and blogs so that things will continue unless something bad happens.

My Easter Egg generator is not really writing a postmortem for. While I did learn a bit about color filters while creating it, this is not enough to warrant a full article.

This month is seeing the release of two games. The first being the HTML 5 version of Four in a Row which is not a new port but does need to be transferred over from the Blazing Games site eventually and as towel day is so late in the month why not this month. The original version was still rough so I decided to clean up the AI a bit and to add animation to the game. There is still a lot that I would like to add to the game before I would consider it to be complete but not sure when I will find time to do that so it may be a decade before this game is properly completed.

Towel day will be the release of my Towels for Earth port. However, I will be posting the postmortem of the game before the actual release of the game. That will be the topic for next fortnight’s post after which I will start posting Chapter 4 of my Animate CC eBook.

Fleet, which I was planning on posting in June, is not quite ready. If it is not ready in time I may post a different game in it’s place but hope to have it finished. If the game is not ready by the 25th then I will go with an alternate post. Either way the site will have information about what I am going to post. If the game is delayed, it will still be worked on so will be posted later in the year. 

July's game will be released on the 13th of the month as that month has a friday the 13th. It is going to be 13^2 Spikes. August is String Along, but I may substitute it for Fleet if a delay is required.September is when CQ is finally suppose to appear but if things go as planned there may be a bit of a surprise with that release.

Saturday, April 28, 2018

3.7 Functions and Objects


Functions, which are known as methods in Java, are named blocks of code that can be called by using the name of the function. This allows you to create a block of code that can be re-used without having to duplicate the code every time it is used. Functions are defined by using the function keyword. Functions can also be given parameters. Parameters are values that the function can use. You can have a function use as many parameters as you need by separating them with commas. Functions may also optionally return a value by using the return keyword. An example of a function would be:

function square(number) {
    return number * number;
}

This function would simply return the square of the number passed to it. To use this function, you simply need to call it, like this:

x = square(2);

The parameter passed can be a variable or it can be a constant value. A constant being any value that will never change, such as the 2 above.

It is also possible to assign a function to a variable, allowing you to pass a function to a another function. In the earlier section you seen a function being created in-line to be assigned to a variable. To assign an already existing function to a variable you simply uses the function’s name without any parentheses and followed by a semi-colon.

 variable_holding_square = square;

Objects are similar to functions. Objects are essentially a combination of variables combined with the functions used to manipulate those variables. This, along with the topic of creating objects, will be covered in chapter 5. However, using existing objects is very common in JavaScript and a requirement of Create.js so we will briefly have to cover using existing objects.

While it is possible to create an empty object and add things to it to make it a unique object, more often you will be creating objects of a certain type called a class. You use a class by creating an instance of it. The variables in every instance are unique to that instance. You can, in theory, have as many instances of a class as you wish (in reality you have a limited amount of memory so you are limited to the number of instances). In fact, your movie is itself an instance of the MovieClip class.
To create an instance of a movie clip you can quite often just use Animate to drag the object (be it dynamic text, a movie clip, or a component) onto the current frame and give it an instance name using the properties panel. Some classes are not visual in nature so you have to manually create them using the new operator as follows.

variable_name = new ClassName();

Objects do take up memory. This memory will continue to be used until all references to an object have been removed. To remove an object (or at least one of the reference to the object) you use the delete keyword. All variables that are assigned to that object need to be deleted (or changed to refer to something else) before the object will be removed from memory.

delete variable_name;

To access a variable or function that belongs to an object, you use periods. An exception to this is if you are writing code within the class in that case, you refer to the object using this. Some classes, such as Math, have what is known as static methods. These are functions that can be called without having to create an instance of the object by simply using the name of the class Here are some examples.

otherMovieClip.gotoAndPlay(1);
Math.cos(angle);
otherMovieClip._x = 23;
otherMovieClip._y = 32;
this.gotoAndPlay(“labelToPlay”);

And that is all there is to basic JavaScript programming. Next chapter we will apply this knowledge to the creation of a simple Animate game.

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.