Convince your Brain to Inspire you with a Memory Palace

September 10, 2015 at 11:22 am (Innovation, Rant, Teaching, Thinking) (, , , , )

If you haven’t heard yet, memory palace techniques are amazing ways to store vast amounts of information in your brain! It has even made its way into popular culture through the BBC show Sherlock and the CBS show Elementary, although the good news is that it’s accessible enough that you can use it without being Sherlock Holmes.

The basic idea of it is that your brain is really great at remembering places; just think about how well you know your own house, your place of work, and the routes to get from one to the other. The trick is that you associate images of things you’d like to remember with difference areas of these locations or routes. The technique is known as the “Method of Loci” and has been used for centuries, although I won’t bore you with the details right now.

I highly encourage you to try out the “Method of Loci” when you get some time, but I’d like to share a specific version of this technique that I make use of every day; I call it the “inspiration room”. You know how some things can get you fired up with ideas? Have you ever walked out of a movie and thought to yourself “wow, that really got me fired up about that concept”? If you have no idea what I’m talking about, I probably sound foolish, but you should probably find more things in this world that interest you.

Anyway, I’ve built up a room in my “memory palace” where I store all of these images that inspire me and make me feel creative. Whenever I need to come up with an original idea or I need to get into a mindset to be creative, I just imagine myself walking around this place and looking at all of the interesting things in this room. It makes sure that I will never forget the things that inspire me and that I can recall them whenever I need to.

Here’s an example of what I’m talking about in case what I’m talking about makes no sense. I begin by thinking about a specific building that I’ve worked in at one point in my life. I’ve spent a lot of time in this building, so I know the hallways and rooms pretty well. I know what the cubicle walls feel like and how sound seems to get absorbed by them. Essentially in my memory I’ve made this place very real by remembering the smells, the sounds, and the feel of things.

So I walk through the hallways of this building, and look in each room; the rooms are where I store my inspiring memories. For example, in one of my rooms I store a scene from the film Iron Man. There is a scene where the main character is building out an upgraded version of his suit of armour that can fly, and he is assisted by his computerized assistant J.A.R.V.I.S. When I first saw this movie, I stayed up until 4am attempting to build my own version of his AI assistant so I could have him organize my life. My memory from that movie and my experiences are something that help me to stay focused and productive. I store Tony Stark in one of the rooms in my mind so I can watch him work productively on his armour.

In case you were curious, I actually did build a basic version of an AI assistant that used natural language processing to activate various tasks. It was fairly successful, but I eventually abandoned the project a couple weeks later. Now it seems that AI assistants are all the rage… whoops…

Hopefully by now I’ve sold you on how useful this idea is. It’s something that I use to stay productive with my time and to get rid of those “blah” feelings when I’m tired. The actual technique of building up this type of room is actually pretty straightforward. First, write down the images that inspire you; you need to know what you’re building before you start. Then pick a location that you know very well. It should be fairly large so you can add new images later on, but it needs to have memorable features such as windows, furniture, or colours.

The last step is probably the hardest one: you have to practice walking through this location in your mind. You have to vividly remember the location and as you walk through it, you need to connect rooms or features with your images by imagining they are there. These instructions may sound a little vague, but your brain actually knows how to do this for you. It just needs to be programmed, and you do this by repeatedly walking through the room and looking at the images.

I hope to tell you about other mental techniques I use on a regular basis in the future. These are really useful for so many aspects of life, and don’t require that much effort to use. Let me know what you think about these or if you have any questions about the technique. I spend a lot of my time practicing these techniques and reading about how others do similar things.

Permalink Leave a Comment

Efforts Update: December 6, 2014. Psychoanalysis and Statistics

December 6, 2014 at 12:37 pm (Art, Rant, Teaching, Thinking) (, , , , , , , , , , )

Lately I’ve been reading a lot about the works of Carl G. Jung; a titan in the field of psychoanalysis, and psychology in general. I picked up one of his books on Amazon for my Kindle: The Theory of Psychoanalysis. I’ve been curious about his actual work and theories for some time as my prior research has shown that probably all personality analysis theories are derived from his writing.

The book is surprisingly well written and easy to understand. I’m still only 30% through the book right now, but he covers Freud’s theories and where the line of separation is from his own. He actually goes as far as to defend Freud’s more controversial theories on psycho-sexuality in children, although most of his frustration was clearly with the scientific community at the time. Apparently Freud had received responses that were more emotionally-driven than factually, however I think that this is understandable and even expected given the subject matter. I haven’t yet investigated Freud’s work and prior life to understand where his approaches came from, but there are only so many minutes in a day.

Getting back to Jung, I’ve also picked up the Kindle copy (text only) of his Red Book. He kept a secret book filled with notes, illustrations, and illuminations describing his self-analysis during a period where he wrestled with what he thought to be his own unconscious. I’ve only gotten through the biography chapter so far, but even that part sheds a LOT of light on why his work developed the way it did.

His artwork is extremely well done; he was an accomplished painter and you can see the influence of the Mayan and Inca art that he studied while he was in France. It actually reminds me of the Sharpie artwork created by one of my friends. He uses a similar style of geometric forms in his work as well.

Outside of the study of Jung’s work, I’ve also been spending a fair about of time studying statistics and the R programming language. Hosted on Coursera, there is a great course with video lectures created by the biostatistics lab at Johns Hopkins University. It’s coming along slowly because I’ve been bouncing between several courses to pick out the most interesting and immediately useful stuff, but they’re nicely done.

Permalink Leave a Comment

Book of Knowledge

August 18, 2014 at 10:58 am (Rant, Teaching, Thinking) (, , , , , )

I am starting a new notebook. While reviewing some information from one of the online courses I’m taking right now, I realized that I am back in an old habit of assuming I’m smarter than I am. This usually means that I read stuff and learn about stuff and assume I’ll just remember it, or assume that I understand it completely. This notebook is meant to write down summarized information on whatever I am learning at the time. It will also include mnemonic tips and other stuff.

This will allow me to quickly review whatever is in the book and solidify it in my mind. I want to keep it concise enough so I can glance through it, but have enough details so that I don’t lose context or have no clue what things are.

Work in progress.

Permalink Leave a Comment

Diffusing Diffuse Thinking

August 5, 2014 at 9:22 am (Rant, Teaching, Thinking) (, , , , , , , )

On the weekend I was following along on an online course I signed up for at Coursera (free online courses, you have no reason not to go there). The subject was focus vs diffuse thinking. Essentially they discussed the difference between when you focus your concentration on something and what your brain looks like during that as opposed to day dreaming and sleep thinking. I’ve known about the differences between thinking while awake and while asleep, but it’s been a self-taught concept. I used to put a lot of effort into dreaming and lucid dreaming several years ago. I used the creativity for designing out game concepts and new ideas about things.

One of the techniques I eventually picked up however, was this idea of tricking your mind into solving problems for you. I used this for my thesis whenever I was stuck or didn’t know where to go with my idea. The trick is essentially to guide your sleep. I would set an alarm for a precise time; I had worked out approximately how long I typically needed (it was around 10-15 minutes), and I would “gently” think about my problem enough to guide my dreams, but not prevent sleep. When I would wake up, it would feel like someone smarter than me worked out the problem or that I’ve been thinking about it for days.

This is one of the concepts they covered in the course. They mentioned some famous names that used to do exactly this thing: Salvadore Dali and Thomas Edison. They would each hold a heavy object and fall asleep. When they’d nod off, they’d drop the object and it would wake them up. Edison apparently had even done sleep research in addition to this to try and figure out just how much sleep the human brain needed.

Anyway, it’s interesting how these sorts of ideas pass through history at different times. It’s sort of like the idea of Calculus: two different people discovering and refining the same idea at the same time. I figured if it’s important enough for those two guys to do, it’s important enough to share to others. Hopefully this helps someone out.

Permalink Leave a Comment

Automation 4 U

June 28, 2014 at 2:29 pm (Computer Science, Game Development, Games, Graphics, Java, JavaScript, Processing, Programming, Rant, Teaching) (, , , , , , , )

So, this will be nothing new for some of you. This isn’t even something new to me; I have a day job where I’m a professional software engineer and we do this at my job all the time. I’m talking about automation and automated processes. This could be anything in your project development process where you have the computer automatically do something for you. An example could be a script that backs up your files to a different drive that you can just run when you want. It could be as complex as a build step that automatically deploys your binaries or runs unit tests.

My disclaimer: A lot of this is technical stuff and directed towards programmers, but even if you’re a graph artist, you can still benefit from this. Everybody that uses computers for projects will need to back up their files for instance.

I’ve only recently realized just how important this all is for regular, personal projects. I’ve always known that it saves time, but my initial mindset was that I’d rather get my project up and running and THEN waste time implementing the time-saving stuff after I get it together. I’ve been reading this book I bought from Amazon that talks about indie gaming from a business, “get your act together” perspective. The book can be found here. I’m still reading it, and some may or may not agree that it’s a good book, but it provides some good ideas for how to take your hobby projects to the next level and keep your process renewable. This means saving time and money on mundane processes, etc.

I am still in the process of automating many aspects of my project, but it really crept up on me just how much time I was wasting on manual things. Here are some of the processes I perform just for my Zombie Mansion project:

  • Backing up files from two areas on my system to my external hard drive
  • Deploying JAR files from my Eclipse solution to my Processing solution to use in my game
  • Removing alpha channels from sprite sets (I built a tool to do this, but it’s still manual)
  • Putting together standalone builds of the game software
  • Packing and compressing image resources for game builds
  • Merging animation sequences together for access by the game engine

These are just things I thought of off the top of my head this morning. Some of them will be easier to do than others, and some of them are specific to my project. All of them eat up time though and are tedious things. Here are a few tips and ideas for how I plan on solving some of these issues though. Please read through just in the off chance that it inspires something or gives you an idea or two.

Deploying JAR files to another solution

For this, I intend on using ANT with Eclipse. This is pretty much a standard for serious Java projects, but it’s taken me a long time to start to improve my processes (usually I want to work on the fun stuff or the stuff that has a visual out-come). Visual Studio has its own build steps and things you can run. Alternatively, you could write a script/BAT file that will grab the files from your output directory and deploy them. This doesn’t require a full set-up of a 3rd party tool and it should be quick to do. It just might break and won’t be as robust.

Backing up project files

This is something I’m already part way through implementing. I’ve written most of a BAT script that will grab the project files from specific directories and dump them in one area so I can back them up (it will optionally zip them as well). To make it a bit easier, I’ve started using virtual drives, but this isn’t necessary. If you’re interested in what virtual drives are or how to set them up easily, email me or post a comment. I can give you some resources or just write an article. Here is a snippet of what I have so far (I’ve been taking bits and pieces from the interwebs, so most of it is borrowed code anyway).

I wanted to dump the files into a folder that would be timestamped so I wouldn’t have to worry about overwriting anything. This is one way of how you’d accomplish it using a BAT script in Windows:

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
set year=%date:~-4%
set month=%date:~3,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set datetimef=%day%-%month%-%year%_%hour%-%min%
echo %datetimef%
xcopy "C:\Test\A" "C:\Test\B\Backup\%datetimef%" /E /I

This will copy everything in your source directory (the first argument) and store them in a custom folder with a timestamp. You can use multiple source directories as well if you have things spread out like I do by just putting in an extra line. The last two arguments are switches to tell XCOPY to use the full source directory (and children) and to assume I mean the destination should be a folder.

Removing alpha channels from image resources

This one will be a bit more complicated. I have a tool I wrote to do this, but I want to streamline this. Now, I wrote up a full project plan with a product backlog, but then I realized even that was too ambitious. I plan on taking some items from the list, but I also plan on it being a purely script-based tool. It will run on the command prompt and will use my engine’s scripting engine for customization (as opposed to using config files). At this point in time, it’s cheaper for me to use scripts than config files since I don’t have a streamlined approach to reading them yet. ANYWAY, I will be writing this as a project in my game engine solution and it’ll have a unit test project to go with it. I’m still working out what tests I will need for it since it works with images, but it’ll be centered on testing the RGB values of generated images before and after the script runs. It’ll also test image sizes for when I add the feature to compile multiple animation sequences together.

Anyway! To summarize this; automation is good. It saves a HUGE amount of money (time is money). If you ever have dreamed of selling a game, you NEED to get in the habit of doing this. The more you do it, the easier it will become and the more effective you will be with your time. Be as lazy as possible with your projects; that’s why we’re programmers! (Although you don’t need to be a programmer to benefit from this).



Permalink Leave a Comment

Log4J 4 You

June 9, 2014 at 8:42 am (Computer Science, Java, Processing, Programming, Teaching) (, , , , , , )

Last weekend I added logging to my game engine since I finally got fed up with print logging to console. I’ve waited this long because while it was on my To-Do list, it kept getting pushed back because it isn’t as interesting of a task as rendering a new HUD for example. It is definitely worth investing in though! If you don’t have logging in your game, I suggest you do it now!

In this post, I will talk about setting up Log4J to use in either Java or Processing programs. Furthermore, I will show you how to set up loggers programmatically. Typically you will see guides that reference config files or XML for setting up loggers. I chose to do it programmatically because I wanted to set it up early in my engine code, have it trickle down into all of the other layers, and not have to change the configurations very often. Perhaps this isn’t a good enough reason to do what I did, but at least for my situation I didn’t mind using it.

Before I get into how to do it this way, I will warn you of one of the major drawbacks of doing this: you can’t change the default logging levels without recompiling your code. This is actually a big deal for many projects, but for some not so much. One of the advantages of doing it programmatically however, especially with Processing sketches, is that once you set up a Log4J library you can copy and paste code and it will just work. No configuration files required.

Enough talk! Lets see some how-to!


Add Library (For Processing sketches only)

If you are setting up Log4J for use in Processing sketches, you first need to create a Library. There are many guides on how to do this, so I will just give an overview. After you download a log4j JAR file, navigate to your “libraries” folder (I forget where the default spot is at the moment; I keep mine in the same folder as my sketches). Create a new folder named “Log4J” or if you’d like, put in the version numbers. NOTE: The folder MUST have the same name as the JAR file. Within that folder, create a folder named “library” and dump that JAR file in there. After you restart the Processing IDE, you will see a new entry when you go to import a library.

EDIT: I’ve been informed that you can actually just drop the JAR into the sketch folder! That’s very handy. It makes it even easier to integrate Log4J. The only downside to doing this is that if you work with many sketches, you have to remember to drop the JAR into each folder instead of just referencing your library. Thanks to Nacho Cossio for pointing this out.

Use Log4J

Now it’s time to use it! Here is some code that will set up a logger.

String masterPattern = “[%c{1}], %d{HH:mm:ss}, %-5p, {%C}, %m%n”;
fa = new FileAppender();
fa.setFile(sketchPath(“./Logs/” + “Master.log”));
fa.setLayout(new PatternLayout(masterPattern));

This will give you a logger that will dump out everything to file. The “masterPattern” variable holds the format that each log message will have. This specific line of gibberish tells the logger that I want it to look like this:

[categoryName], time(hour:minute:seconds), Priority (if any), {Class name where message was logged from}, message

The category name in my example will be “Master”. I’ve also put commas in there so that I can optionally open the logs in Excel and have it put each value in its own column. This is very handy as you could then use searching and sorting features with zero effort.

Note that in the last line of code, I add the appender to the root logger. Do this only if you want all log messages to go to one file. In my game engine, I’ve set up multiple loggers for different categories to go to different files, and then I use a master logger to consolidate them to one file.

Log Messages

Logger logger = Logger.getLogger("Master");
logger.debug("Log my message");

This will get the logger (which you only need to do once if you store it in a variable) and output a debug message.

There you have it; easy logging for Processing sketches or Java programs. There are likely better and more in-depth tutorials for using Log4J, however I just wanted to give an introduction to get it to pay off quickly without having to browse to nine different sites like I did.


Permalink 4 Comments

Stack-Ranked Lists and You

March 24, 2014 at 9:25 am (Computer Science, Game Development, Programming, Rant, Teaching) (, , , , , )

If you are a professional software developer, you may be familiar with development methodologies. You may have encountered such beasts as “Agile”, “Waterfall”, or if you own a time machine, “Extreme Programming”. These are all just different ways of organizing your work. They let you decide on what to build and give you an idea of when to build it. They’re handy things to utilize and if done right, they’ll make you look younger*.

      *May not actually make you look younger.

So why am I writing this? Well, it isn’t to evangelize the way you should change your life and use what I suggest. It’s more to talk about one specific technique that’s pretty low cost and can help your cluttered development life, even for small side projects. Furthermore, I’ve found that it can help with motivation issues and help you force yourself to finish what you start. You’ve always finished your side projects haven’t you??

What I use now for my projects is a stack-ranked list. This is a list of all of the individual features that I want to implement in my software put in order of importance. Again, if you are a professional developer, you will probably begin to smell the Agile backlog here, but this is just a small slice that can offer a lot of value. First I will talk about the list itself and what that should look like and then I will discuss the idea of importance.

The feature list should be kept fairly granular in order to be things that you can achieve in a relatively short period of work time. You definitely shouldn’t go into such details as “change while-loops to for-loops”, but you should also try to break up tasks as big as “write rendering engine from scratch”. The idea here is that you can track what you need to do in an orderly fashion, but also when you’ve completed them, you get to check them off your list! Don’t sneer at this concept. Having something tangible (I mean, other than working code) that says you’ve completed something is a big deal. It’s a way to trick your brain into thinking it’s being rewarded. I go as far as to not even delete the task from my list, but I mark it in a different colour.

Lets switch gears and talk about importance. It isn’t a difficult subject, but it is ambiguous enough that it should be defined a bit better for this situation. To clear things up, “importance” is whatever you want it to be. I mean it. I choose importance to be not just how important the feature is to my final project, but what order it should be done so that other tasks can be completed. If you give each tasks a proper importance value (or “stack-rank”), then you can even do such exciting things as picking milestones to release demos for.

Now, how do we do this all? What does it actually look like? I use a Google Docs spreadsheet for my feature list. It has auto-save and it is accessible on any computer. I typically use different computers, sometimes in different places, so it makes sense to me to have access and not have to worry that my version is the most up to date one. In my spreadsheet, I have the following columns: Stack Rank, Task Name, Task Status, and Additional Notes.

For the stack rank, I’ve made it be just a number. 1 Is the most urgent, and 50 is the least. The range doesn’t actually matter; it’s just a way to sequence your features. The task name is a short description of what the feature is. Easy. The task status is a column that I’ve written conditional formatting for. When a task is complete, I write in the text “Completed” and the cell turns green to show how awesome I am. If I want to keep track of what I’m currently working on, I write “In-Progress” and it turns orange. I sometimes use a “Bug” status that turns red if I’ve broken something and I want to specify that it’s a regression to previous code, but that’s getting a bit too in-depth. Lastly, I have an “Additional Notes” column for quick ideas on how to complete my task.

Here’s some examples. I’ve been working on a game as a side project. It’s a zombie shooter/puzzle/adventure/overly complicated concept game. Here are some of the tasks I have had in my list:

2, Shootable Urn,  Player can shoot them and they shatter
6, Title screen,  Landing page and player goes here when they die
14, water dripping effect,  Use particle system
25, Melee attack,  Necessary for the game but not to get other things done

These are my tasks. Notice that melee attack seems like a pretty importance feature, but it’s at the bottom. Sometimes my importance value is more based on how fast I can get a feature completed. The idea is to make a complete game, and some features can end up using an open-ended amount of time. The melee feature was an open-ended one in this case. I had to do new character art, I had to add in the game mechanic, I had to playtest it and make sure it made sense, I had to balance the damage, I had to find SFX for it, etc. Shooting an urn ended up being super easy. I subclassed a Billboard Game Object class I already had and whipped up some art for an urn and a broken urn.

To close this lengthy article, what we all want is to work on interesting things and see them in a completed state. It’s fun to make them and if your idea was good enough, it’s probably fun to play with it. Stack-ranked lists could be something that could help you. Keep in mind it’s an open concept, so make this technique yours. Customize it to work better with your workflow. Say you have a small team, perhaps you’d want a column to say what Type of task it is: “Art”, “Programming”, “Music”, etc. Maybe it’s better to just write a developer’s name next to the task for a group project. Whatever. If you struggle with getting things completed and staying motivated, at least give it a try.


Permalink Leave a Comment

Quick and Accessible Inversion of Control

March 14, 2014 at 1:37 pm (Computer Science, Games, Graphics, Java, Processing, Programming, Rant, Teaching, Video games) (, , , , , )

So by now you’ve probably at least heard of the magical beast known as “Inversion of Control”. You may even understand what it is. If you’re in this boat, why aren’t you using it more often?? (if you are, you can read the rest of this article with your head held high).

There are tons of places on the interwebs where you can learn all about Inversion of Control (or IOC), so it doesn’t make sense to write up a detail explanation and then have people correct me on it. The short version of it is that it lets you defer your problems to someone else (future you for example). You allow the implementation to be abstracted in such a way that you can conveniently inject it in such a way that would make your college programming professor proud and/or confused.

For this example, I am going to use PicoContainer and Processing. PicoContainer is an IoC library for Java, although you could implement what it provides yourself through a variety of techniques I won’t tell you about here. The idea is just to show you a brief intro to what it can look like. In my example, I have a Graph object. It is the “M” of our MVC, and we want to separate the “V” from it. This means that the bit of code that draws the graph on the screen is going to be extracted. The kicker is that the way we abstract it will allow us to re-skin the graph in whatever way we want, whenever we want. We just inject a new view without changing the model layer and we’re good to go.

  This is our interface for abstracting the View from the model
public interface GraphView {
  public void draw(PGraphics g, Graph graph); 

  This is our Model: The object we want to abstract the view from.
public class Graph {
  private MutablePicoContainer graphConfig = null;

  public Graph() {
     graphConfig = new DefaultPicoContainer();

  public MutablePicoContainer getGraphConfig() {
      return graphConfig; 

  public void draw(PGraphics g) {
     // I'd recommend caching the view ahead of time to remove overhead
     GraphView graphView = (GraphView)graphConfig.getComponent(GraphView.class);
     graphView.draw(g, this);

Now here is the part that makes it all work. I’ve written this in Processing code, but it is essentially simplified Java anyway. In this snippet of code (although it is a working program if you include the previous snippets), I instantiate our Graph object and then inject a View. In this example I’m just showing the power of IoC by including an anonymous implementation of a View object. In the “real world”, you would have written it as a standard Java object.

import org.picocontainer.*;

Graph graph = null;
void setup() {
  graph = new Graph();
  graph.getGraphConfig().addComponent(new GraphView(){
      public void draw(PGraphics g, Graph graph) {
        g.ellipse(25, 25, 10, 10);
void draw() {

Now to summarize, we have accomplished our goal of abstracting the view of the graph from the data represented by the graph object itself. This means that we could completely re-skin the visual representation of our graph without touching any of our previously written code. If we wanted to draw the draw in 3D, we could just inject a new implementation. If we want it to be rendered using only ASCII characters, we got this. In the case that you still don’t see the value of this, consider a game you’re probably writing right now in your spare time:

You have a general “GameCharacter” class that both the PlayerCharacter and AiCharacter classes inherit from (Because you’re object-savy and generally good-looking). Both of these allow you to draw the characters differently. What happens when you decide to add new AiCharacters that act exactly the same, but look different? Well, you could throw in an IF statement and just check a state variable…. OR you could abstract the view, just like in our example! When you construct the AiCharacter objects, you inject a View object that will do all the drawing. As an object-oriented purist, you feel content, and as a game developer you feel pleased that you were able to trim off an “IF” statement from your render loop. You high five yourself.

Permalink Leave a Comment

Javascript Object Inheritance that C#/Java Coders can Understand

February 18, 2014 at 10:22 am (Computer Science, JavaScript, Programming, Teaching) (, , , , , , )

So, at work I’ve been using Javascript as a primary language for a while now. While I am likely not an expert, I’ve picked up some neat tricks. Since I work with an office full of C# coders, I need to write code that they can understand quickly. Therefore, one of my first motivations is to write code that can be understood by non-Javascript purists.

So let’s build a simple example of how to achieve objects and inheritance using Javascript. While there are more than one way to create objects in Javascript, I’ve been using this approach as several good/reputable sources have suggested it, and it resembles C#/Java somewhat. Note: I don’t condone the act of trying to make Javascript into a language it isn’t, but I do support readability. In this case, our reader understands a separate language and they have no reason/incentive to learn ours. So we will commit as few crimes as possible to make our code understandable by people that don’t know Javascript.

So here is our base case: Shape. It holds a position coordinate with a public accessor.

function Shape() {
  var _x = 0,
      _y = 0;  
  This acts as a constructor for us and looks familiar-ish to C# coders. 
  initializeComponent() {
      _x = 5;
  this.getX = function() {
    return _x;

  this.getY = function() {
    return _y;

  Can't forget to call our own constructor.

So this is our base class. We’ve defined X and Y and Javascript will treat them as private variables. When you instantiate the object, you can only access them via the public “GetX()” method (I’ll show instantiation shortly). You will also notice the function “initializeComponent”. This is what I call a constructor, but I stick to this function name just by convention. You can call it whatever you want, within reason; Javascript reserves some keywords. You’ll see at the bottom of the class that we are calling this constructor ourselves. What’s with that?? Well, to Javascript, the whole class is a constructor, but if we had our code spilling everywhere then it would be messy and not at all like C#.

The last thing to notice is that our public accessors are attached to a “this” keyword. “This” will refer to the instantiated object, and the function will attach itself as a property of that object. This is different from our private variables, which aren’t properties of the object, but are accessible from within those public functions. Without getting into details, this essentially lets us mimic the behaviour of C#/Java.

Now to the good part: we want to instantiate our object!

var ourObject = new Shape();
ourObject.getX(); // This returns _x
ourObject._x; // This returns undefined as it is not accessible

So this is how to instantiate the object. Everything works as expected. Now lets talk about how to make a new class that inherits from Shape. Incoming code:

function Circle() {
  var _r = 0;
  this.GetRadius = function() {
    return _r;
Circle.prototype = new Shape;
Circle.prototype.constructor = Circle;

Okay, so we’ve seen everything in Circle already, but what is that noise after the class definition? So again, without getting into details (which are already everywhere on the interwebs), the first line is setting the class to inherit from. This means that if you instantiate Circle, you can do operations such as:


This is a valid operation. Exciting. Now what was that second line? We need to set the prototype’s constructor to point back to our Circle class. This allows us to use the “instanceof” operator and have it work as we would expect. Now, it isn’t necessary to do this step, but it plays nice when other people use our code.

So that’s how we can achieve something along the lines of inheritance with Javascript. I’ve hidden lots of important details, but if you want to know more, ask or search for it. I should also note that my example doesn’t give you the power of protected fields. For example, Circle can’t directly access _x.



Permalink Leave a Comment

Scene Management Article

October 31, 2012 at 9:23 am (Computer Science, Games, Graphics, Processing, Programming, Teaching) (, , )

I’ve posted an article on a separate page on this blog that provides a simple way to manage scenes for larger projects. I use this code for my game engine and it works great!

Here is a link:

Permalink Leave a Comment

Next page »