Saturday, March 9, 2019

Blazing Games Life after Death


It has been no secret that the Blazing Games site is going away in April. This may lead to the question about what I am going to do with this blog after the site shuts down? I have been thinking about dropping this blog keeping only my Homebrew Gamejam blog but I am slowly porting the Flash and Java games from BlazingGames into HTML5 and hosting the new versions on Spelchan.com. There are a lot of games that I had created on BlazingGames so this process will take a very long time so it makes sense to continue to keep this blog running. Besides, I have to finish posting the chapters from my Making HTML5 Games using Animate eBook.

I will continue posting the sections of the book each fortnight with updates on game ports made between the chapters. In addition to Spelchan.com, I also have my 2600Dragons.com and will soon have TarotRevealed.com which is where I plan on hosting my tarot games. There are a lot of pages that make up the site as well as a lot of features that I would like to add to the site so this is going to be a process that will take a fair amount of time. I am going to spread this work out adding new layouts or features every month with the site being updated on the 15th of each month.

Right now I am running into some issues setting up the site (adding it to my hosting is still pending) but hopefully the site will show up shortly and I will be able to have the first version of the site ready by the 15th of this month.

I would like to be porting games much quicker than I currently am but at the moment am working on my Masters degree so my spare time is very little. The few hours a week that I allocate to working on both blogs, porting games, and developing my emulator should probably be used for study but I consider this my time so try to allocate some time for these projects. Naively I was hoping to get ahead of the release schedule so that I wouldn’t need to worry about hitting release dates but that has not been the case. My summer schedule is lighter but as we are expected to work on our thesis at that time I suspect that my tune situation will be just as bad in the summer. The Coffee Quest engine isn’t too bad so I should have no problem releasing content for that series but I was really hoping to do my revamped One of those Weeks and Ultimate Retro Project games.  

Needless to say, my focus for the larger project will be Coffee Quest  and once that project is done I will have to make a decision between Ultimate Retro Project and One of those Weeks. What I want to do with OotW is very time consuming but I should be finished my Masters degree so unless I decide to go for a PHD I should have more spare time. More on this once I have finished posting the next chapter of the eBook, which will be starting next fortnight.

Saturday, February 23, 2019

5.7 Closures

The bind function takes advantage of something in JavaScript known as a closure. This takes advantage of the way that scope works within JavaScript and can be used to hide variables within a function. For binding it is making sure that the reference to the object that created the object is tracked.

Scope simply is a term that describes which variables are known to a particular piece of code. The visibility of a variable depends on where it is declared. When declared outside of a function it is global and is visible to everything, including other scripts running on the same web page, which is why you do not want to have global variables in your code if you can help it. Variables declared within a function are only visible to code within that function. Variables declared within a loop are only visible to code within that loop, and so on. The code within the loop, however, can see all the variables in the scopes leading up to it.

The purpose of scope is two-fold. First, each layer of scope can be considered it's own name-space. Second, and more importantly, this allows JavaScript to know which variables are no longer needed and can be garbage collected so that the memory it used can be reclaimed for use by other things. There is an exception to this garbage collection rule, any variable that is still being referenced by another variable that is still in scope will not be garbage collected.

Functions within another function have access to the parent function's variables. This information is stored in a scope chain, the details of which are a bit beyond the scope of this chapter but the nutshell is that the function has access to the information contained within the function that created. This means that if we have a case where there is a reference to the inside function then even if the outside function goes out of scope, the outside functions data will not be garbage collected as it is still referenced by something that is still in-scope.

Here is a simple demonstration:

// General function for printing to the web page so results can be seen// without requiring the console
function printTestLine(s) {
// we are grabbing an html element
var results = document.getElementById("testResults");
// now append the new line to this element
results.innerHTML = results.innerHTML + "
" + s

}

function HiddingVariables(p, v) {
this.publicValue = p;
var hiddenValue = v;

this.getHiddenValue = function() {
return hiddenValue;
}

this.bindPrint = function() {
var owner = this;
return function() {
printTestLine("The hidden value is " + owner.getHiddenValue());
}
}
}

var hiddenVar = new HiddingVariables(21, 42);
printTestLine("Attempting to read public variable: " + hiddenVar.publicValue);
printTestLine("Attempting to read hidden variable: " + hiddenVar.hiddenValue);
printTestLine("Getting through method: " + hiddenVar.getHiddenValue());
setTimeout(hiddenVar.bindPrint(), 1000);

When the HiddingVariables function runs, the public value is stored as part of the object. The hidden variable is a local variable which means that it will go out of scope as soon as the function finishes running. As the function has a reference to this value, it is still visible to it. If you still don't quite understand how a closure works, don't worry too much as it is not necessary to understand them to use them.

Now that we have a basic understanding of classes we use some of these concepts in the next chapter when we create the Nightmare Maze game.

Sunday, February 10, 2019

5.6 Binding Events

The one really nice thing about classes is that they are a nice way of grouping data with the code that manipulates that data. This leads to a very common situation in programming where you want to do something with the data when an event happens. Event-driven programming is where the behavior of a program is structured around events instead of sequences and is the way you typicality approach user-interface related tasks. Combing objects with events seems like a no-brainer but this is where JavaScript starts showing some strangeness. To understand lets write a simple event.

// General function for printing to the web page so results can be seen
// without requiring the console
function printTestLine(s) {
// we are grabbing an html element
var results = document.getElementById("testResults");
// now append the new line to this element
results.innerHTML = results.innerHTML + "
" + s

}

// The timeout method uses a callback which gets called asyncronously
function tickTest(){
printTestLine("Tick Test was called!")
}
setTimeout(tickTest, 1500);

Timing events in JavaScript can be controlled by using a timeout. SetTimeout simply takes a function and a duration in milliseconds which are thousandths of a second. After the duration has expired it will call the function. Note that the timer is not precise and that the delay can be more than the specified amount bur for general usage timeouts are adequate. Running the above would result in a second-and-a-half delay before something was printed.

Now lets write a simple class that will store a value and when a function is called will display that value back.

// A simple class that stores a value and can display the currently stored value when asked to.function Demo() {
this.setValue = function(n) {
this.storedValue = n;
}

this.displayValue = function() {
printTestLine("Stored value is " + this.storedValue);
}

this.displayWithMessage = function(s) {
var str = "NO MESSAGE PROVIDED ";
if (s !== undefined)
str = s;
printTestLine(str + this.storedValue);
}
}

// as this shows, the class works as expected
var demo = new Demo();
demo.setValue(42);
demo.displayValue();
demo.displayWithMessage("Custom message before value ");

This works just fine so using it as part of an event seems trivial but lets try that.

// however, the value does not seem to exist if used as a callback.
setTimeout(demo.displayValue, 2000);
\end{lstlisting}
}

After a couple of seconds delay we get a rather interesting result. This is a byproduct of the way JavaScript calls methods within a function and is something that we will discuss in detail next fortnight. Obviously, this means that we can't use events with classes. But, as this is an obvious necessity, there is a bind function that browsers provide to solve this problem. By simply adding the bind function to the end of the function you are calling you will be able to specify which class the event is for. The function takes the instance of a class to use as it's parameter and does not need to be the calling instance but I can't think of any situation where I wouldn't want to use the same instance.

// this is where binding comes in
setTimeout(demo.displayValue.bind(demo), 2500);

// Binding also helps with parameters.
setTimeout(demo.displayWithMessage.bind(demo), 3000);
setTimeout(demo.displayWithMessage.bind(demo, "Message added in Binding "), 3000);

As can be seen from the demo code, binding can also be used to add additional parameters to a callback function. When dealing with situations such as having multiple buttons being handled by the same logic, this is an incredibly convenient feature of the bind function. But what exactly is the bind function doing? Tune in next fortnight to find out!

Saturday, January 26, 2019

Polymorphism and Duck Typing

Polymorphism is just a fancy way of saying that we can use an inherited class in place of a base class. This is a very important concept in typed languages, but is automatically handled for you in dynamically typed languages like JavaScipt. One of the nicest features of JavaScipt is that you not only can use a child class in place of a parent class, but you can use any class that has the methods and properties that you want to use. This is known as duck typing and is called that from the saying "if it looks like a duck, walks like a duck, and quacks like a duck then it is probably a duck."

The power of polymorphism comes from the ability to call a function that takes a base class with any class that is inherited from that class. For example, lets say we create a function for playing with the pets that we created last section.
 
// Note - See previous section for the Pet classes 

// function for pet class objects
function playWithPet(pet) {
printTestLine("Playing with " + pet.name);
pet.makeNoise();
}

// Pet polymorphism test code
printTestLine("Class polymorphism using inherited pets:");
var cat = new Cat("Abby")
var dog = new Dog("Smokie")
var fish = new Pet("Dora", "Fish")

playWithPet(cat);
playWithPet(dog);
playWithPet(fish);

Notice that we can call this function with any of the pet classes that we created. This is a very important concept as it means that we can create functions that use base classes and they will continue to work with classes that we create in the future giving us a lot of flexibility. Duck typing takes this a bit further by not even requiring the same base type. Lets test this by creating a non-pet duck class.

Duck = function(name) {
this.name = name;

this.makeNoise = function() {
printTestLine(this.name + " Quacks!");
}
}

// Testing duck-typing
printTestLine("---------");
printTestLine("Duck-typing test:");
var duck = new Duck("Daffy");
playWithPet(duck);

As you can see, the only requirement JavaScript has is that the method being called exists. The Duck class did not need to inherit from the pet class nor did it need to implement all the methods in the pet class, just the methods and properties that any function it was being called with requires.

For smaller programs, duck-typing is a very handy feature, but it can result in problems with larger projects. This is why interfaces are often used in place of duck-typing in languages like Java.

Saturday, January 12, 2019

5.4 Inheritance

One of the most powerful and most over-abused features of object oriented programming is the use of inheritance. The basic idea here is that there are a lot of classes of objects that have a lot of features in common. Instead of re-writing the same code repeatedly for similar objects, a hierarchy of related classes can be created. You start with a base class, also known as the parent, that has the base functionality it's children will inherit. To demonstrate this, lets create a base class for pets.

The pet class will have a name for the pet and a species for the pet. Pets will be able to greet their owner, and make a noise. First, lets take a look at the more modern ECMAScript 6 way of doing this. This is set up just like any normal class that we would have created in the previous section.


class E6Pet {
constructor(name, species) {
this.name = name;
this.species = species
}

greet() {
printTestLine(this.name + ", the " + this.species + ", comes to greet you");
}

makeNoise() {
printTestLine(this.name + " makes a noise");
}
}

var fish = new E6Pet("Nemo", "Fish")
fish.greet();
fish.makeNoise();


The old way of creating the base class is also the same way you would create a class using older versions of ECMAScript.

function Pet(name, species) {
this.name = name;
this.species = species;

this.greet = function() {
printTestLine(this.name + ", the " + this.species + ", comes to greet you");
}

this.makeNoise = function() {
printTestLine(this.name + " makes a noise");
}

}

var oldfish = new Pet("Dora", "Fish")
oldfish.greet();
oldfish.makeNoise();

Once you have a class that can be used as a base-class, you can create a new class that inherits the methods and variables of it's parent. This effectively gives you all the code that you have written in the base class. You can then add additional methods and variables allowing the new class to have the functionality of the base class while adding new features to the class. This alone would make inheritance worth doing, but it gets even more powerful. It is possible to override an existing method and replace it with another method that is more appropriate for the class you are creating.

In our example, different pets make different sounds so by overriding  the makeNoise method, we can create species specific noises. We will create a dog and a cat, with each of them having a unique noise and the dog being able to wag it's tail.

ECMAScript 6 makes inheritance very easy as you just use the extends keyword when you are creating a class. Sub-classes can have a different number of parameters, with the super method used to call the original code. Overriding the method is simply the matter of using a method with the same "signature." A method's signature is simply the method name and the particular parameters that make up the method. finally creating a new method is done by having a new method in the class.

class E6Cat extends E6Pet{
constructor(name) {
super(name, "Cat")
}

makeNoise() {
printTestLine(this.name + " Meows!");
}
}

class E6Dog extends E6Pet {
constructor(name) {
super(name, "Dog")
}

makeNoise() {
printTestLine(this.name + " Barks!");
}

wag() {
printTestLine(this.name + " wags his tail!");
}
}

var cat = new E6Cat("Lexi")
var dog = new E6Dog("Scruffy")

cat.greet();
cat.makeNoise();
dog.greet();
dog.makeNoise();
dog.wag();

The old way of inheritance is a bit more confusing as older versions of ECMAScript does not have a way of directly indicating inheritance so the programmer must manually set this up. JavaScript use prototype based inheritance where every class has a prototype that determines which methods it has. This prototype is used by the new operator to set up the class, but the prototype can be modified manually. The result is that there are many ways of setting up inheritance in JavaScript. The most common way is simply assigning the prototype of the class to the prototype of it's parent by using the new function.

function Cat(name) {
this.name = name;
this.species = "Cat";

this.makeNoise = function() {
printTestLine(this.name + " Meows!");
}
}
Cat.prototype = new Pet();

(Dog = function(name) {
this.name = name;
this.species = "Dog";

this.makeNoise = function() {
printTestLine(this.name + " Barks!");
}

this.wag = function() {
printTestLine(this.name + " wags his tail!");
}

} ).prototype = new Pet();

var oldcat = new Cat("Abby")
var olddog = new Dog("Smokie")

oldcat.greet();
oldcat.makeNoise();
olddog.greet();
olddog.makeNoise();
olddog.wag();

You will notice two slightly different styles for doing this. The cat way is the textbook way while the dog way is the way JavaScript code generated by Animate CC does things. You could also manually copy just the methods you are interested in, which can be a handy way of inheriting functionality from multiple different classes.

Inheritance is not just for reducing code duplication, but allows for a powerful technique known as polymorphism which we will be covering next.

Saturday, December 29, 2018

5.3 Constructing Classes

While I have my January game ready, I am at my parent's place while the game is in a different city so I will not be posting it until January 2nd when I return to University.

JavaScript did not have "proper" classes until ECMAScript 6. The problem is that while there is now a class keyword that makes creating classes much easier in browsers that have an ECMAScript 6 complaint version of JavaScript, this is not all browsers. Eventually there will be so few browsers that do not support ECMAScript 6 that using JavaScript classes will make sense, but before that transition takes place, the old way of creating JavaScript classes must be used. The nice thing is that backwards compatibility means that the old way will still work on new browsers.

The ECMAScript 6 way of creating classes is with a class construct. Within this construct we have a constructor which initializes the class and then methods that the class knows. There is some special support for getter and setter methods which I will not be covering here as this book is more focused on older JavaScript but that may be something I cover in a future book. Here is what a soldier class would look like in ECMAScript 6 versions of JavaScript:

// General function for printing to the web page so results can be seen
// without requiring the console
function printTestLine(s) {
// we are grabbing an html element
var results = document.getElementById("testResults");
// now append the new line to this element
results.innerHTML = results.innerHTML + "
" + s

}

class E6Soldier {
constructor(name, rank, serialNumber) {
this.name = name;
this.rank = rank;
this.serialNumber = serialNumber; 
}

printNRS() {
printTestLine("Name: " + this.name + " Rank: " + this.rank +
" Serial Number:" + this.serialNumber);
}
}

printTestLine("ECMAScript 6 tests");
var soldier1 = new E6Soldier("Bob", "Private", 12345);
var soldier2 = new E6Soldier("Doug", "Captain", 23456);
soldier1.printNRS();
soldier2.printNRS();

You will notice that both soldiers simply used the E6Soldier class to build their object. The creation of an object from a class is called instantiation in object oriented terminology. Every object of a particular class is known as an instant of that class. Instances share the same properties and methods, though object specific properties and methods can be manually added to specific objects if desired, but are otherwise independent.

The old way of creating classes is similar to the new way but instead of grouping things into a class structure you are creating a function. This function sets up the properties just like the constructor above did and then sets up all the methods that are used by the class.

function Soldier(name, rank, serialNumber) {
this.name = name;
this.rank = rank;
this.serialNumber = serialNumber;

this.printNRS = function() {
printTestLine("Name: " + this.name + " Rank: " + this.rank +
" Serial Number:" + this.serialNumber);
}
}

Note that it is not necessary to have all the methods defined within the function. Some people actually like defining the methods of a class outside of the class. This is done by using the function's prototype, which is something we will be talking about in more detail in later sections.

Soldier.prototype.changeRank = function(newRank) {
this.rank = newRank;
}

Using the classes is pretty much the same the old way as it is the new way.

var soldier3 = new Soldier("Pete", "Private", 34567);
var soldier4 = new Soldier("Billy", "Captain", 45678);
soldier3.printNRS();
soldier4.printNRS();
soldier4.changeRank("General");
soldier4.printNRS();

The real power of classes comes from polymorphism and inheritance, but that is also where the biggest problems of object oriented programming come from. Next section we will start our exploration of polymorphism and inheritance.

Saturday, December 15, 2018

5.2 Creating Objects

There are a number of ways to create an object. The standard way of creating an instance of a class is to use the new constructor, which we will be covering in the next section. There is a special class that all classes are based off of called Object. This class can be used to create a new basic object which properties and methods can be attached to. To create an object using the new keyword is done as follows:

var myObj = new Object();

Properties can be added to an object by simply giving the property a value. This adds an interesting quirk to JavaScript programs as null indicates that an existing property has no current value attached to it while undefined means that the indicated property has not been attached to an object. For people use to typed languages this can be confusing as undefined and null are different things. You can check to see if a property is defined by using the following:

if (myObj.variable === undefined) 
// handle undefined variable here

Object Oriented programmers generally refer to functions that are part of an object as methods. As was discussed in Chapter 3, functions can be assigned to a variable. This means that to add a method to an object you simply need to add it as you would any other property. You can create a new function specifically for the object or you can use an already existing function and simply attach it to the object.

// here is a comomon function that will be shared by multiple objects
function printNRS() {
// we are grabbing an html element
var results = document.getElementById("testResults");
// now we are adding the info onto the text contained within the element
results.innerHTML += "
Name: " + this.name + " Rank: " + this.rank +

" Serial Number:" + this.serialNumber; 
}

// Build first soldier by using an object and adding properties to it
var soldier1 = new Object();
soldier1.name = "Bob"
soldier1.rank = "Private";
soldier1.serialNumber = 12345;

// Methods can be added too
soldier1.printNRS = printNRS;
soldier1.makeCaptain = function() { this.rank = "Captain"};

Notice that in order to reference a property of the object that is calling the function, the this keyword is used. Scope works a bit different than in most other languages and is function based. This is why the function printNRS can access the properties of the object as it is called from that object so holds the object's scope. We will come back to this topic in a bit more detail when we cover closures in a later section.

As mentioned earlier, there is more than one way of creating an object. JavaScript has a shorthand way of creating properties and pairing them to values so that it is easier to create objects with multiple properties initialized. This feature of JavaScript was expanded upon to come up with the JSON data transfer format which is why many people refer to creating objects using key : value pairs as being in JSON format. This shorthand method simply lets you define the contents of the object by using {} to indicate the object and then placing the property name followed by a colon followed by the value. It is possible to have functions within this declaration. Once the object is created you can add additional properties or method as you did with the soldier1 object. So, lets create a second soldier:

var soldier2 = { name : "Doug", rank : "Captain", 
serialNumber : 23456, 
makeMajor : function() {
this.rank="Major"

};
// adding addtional methods, such as this common method, is possible
soldier2.printNRS = printNRS;

JSON is an acronym and stands for JavaScript Object Notation. It was originally created as a data transfer standard between JavaScript and whatever language is being ran on the server-side. The idea is that objects get converted into strings to be transferred then converted into objects at the destination. It is much simpler and more condensed than XML so has largely replaced XML usage. If you are receiving JSON strings from a server or other input file you can easily convert the strings into JavaScript by using the built-in JSON class as is done to create our third soldier.

var soldier3 = JSON.parse('{ "name" : "Billy", "rank" : "General", "serialNumber" : 42}');
soldier3.printNRS = printNRS;

Manually creating multiple versions of what is essentially the same object does seem like a lot of work. There is a better way which we will cover in the next section.