Wednesday, 31 July 2013

A Peaceful Interlude

Before we continue with the drawing - I've been thinking about the structure of this blog.  I think it is important first that we talk about how we write code in java-script.  Java-script is powerful.  Java-script can easily become a big mess.  A lot of programmers don't understand object-oriented programming.

I will try and explain it.  It takes a lot of experience to really, really get it.  So the sooner we start, the better.

First of all, there is a reason why object-oriented programming has supplanted procedural programming.  If you're new to this all, procedural programming and modular programming (excuse the grouping together) is what people used to do.  It is what comes most natural to all of us.

A procedural program typically looks like.

step 1.  do something
step 2.  do something else
step 3.  go to step 5
step 4.  show some output
step 5.  go to step 4

They are instructions, commands for the computer to do.  It comes natural, and kids love it because "they" get to give the commands.  So whats wrong with that?  The problem is one of scale.  The first computers were small compared to modern computers.  People found out fast that as computers grew so did their programs.  The problem with procedural programs is usually called "spaghetti-mess".  The more you need to do, the more instructions you need to add, and at some point, you lose control.

Same happened with my first big Indy game.  I ended up with a situation where whenever I made one small change to one part of the program, another part would break unintentionally.  I had lost control over the code.

Don't despair, there is a solution.  Quite a nice one.  Its called object-oriented programming.  Object-oriented actually means "data-oriented".  But since data already meant so many other things, the inventors decided to name it object-oriented instead.

The main difference between the two styles is that you focus on the data first, not the instructions.  The WHAT, not the HOW.  To do that you need to figure out what it is you're "modelling".  In a game typically, you have objects like "people", "vehicles", "weapons", "buildings" etc.  All these things become their own "objects".  In business applications you might have "invoices", "people", "addresses", and "bank accounts" as your objects.

Java-script is an object-oriented language (as well as a procedural language if you wish to use it that way).  Therein lies the danger.  If you decide not to use it in an object-oriented manner, you run the danger of creating spaghetti-mess.  My advice, be disciplined, and don't be lazy.  It will save you from going insane in the end.

Java-script is simple in what it contains as a language.  Its main data-types (different kinds of items) are:

strings (things within single or double quotes like "Peter" or 'the mouse')
numbers (integers and floating point like 1, 2, 0, -10, 1.5, 3.14159265)
null    (a special word meaning 'no value')
true, false (Boolean logic values)
undefined (a special word meaning 'not defined' / 'unknown')
function (a thing that groups instructions on what to do)
this (a very special word in java-script that refers to an object itself)

Furthermore we have collections called arrays e.g.  [1,2,3,4] is a set of four numbers grouped into an array. Finally we have hash-maps and collections inside curly brackets - but they are for later.

So suppose we wanted to model a space-ship, as we will be doing in this game, we'd first need to think of what defines it.  Here is my first attempt.

// this is a comment - it starts with "//" and anything after it
// is completely ignored by java-script
function Ship()
{
  var x = 0;
  var y = 0;

  this.playerName = "Peter";

  this.draw = function()
  {
    // do some drawing
  };
}

We've defined our first "object" (called a "Class" in the object-oriented world).  The object is called "Ship".  The word "function" in front of it defines the "class" in java-script.  This class has three variables in it called "x", "y", and "playerName".  "x" and "y" are both "initialised" to 0 (the number zero).

this.draw is defined as a "function".  This makes java-script a little confusing in my opinion.  The "this" makes the "draw" visible to things outside the "Ship" class.  Its a java-script convention.  "draw" is a grouping of instructions.  At the moment "draw" is empty - it just contains one comment.

Note as well that every "instruction" or "statement" ends with a semi-colon ( ; ).  This is important to java-script it marks where things end (like a full-stop in an English sentence).

It might help too, in your mind, to replace { with the English word "begin" and } with the English word "end".

Any instruction inside the "Ship" curly brackets "{" and "}" can access the "x" , "y" and "playerName" variables.  However, both "x" and "y" are private (because of the "var" keyword) to "Ship", and the outside world will be unaware of "x" and "y".  "this.playerName" is a different story and can be changed by any other part of the program.

You don't need to write java-script like this, you can write it procedurally like a lot of people do.  However, you get massive advantages writing it as a "class".

The "ship" class becomes a blue-print for all "ships" in the game.  You can have a 100 ships all acting independently using the one class as a template.  Doing that in a procedural language is a lot more difficult and requires a lot more effort.

Furthermore, the "x" and "y" variables inside the "ship" are hidden from outside code.  This is called "encapsulation".  The advantage of that particular little trick is that things outside ship can't just change these values - they're protected.  It makes ship more "robust" and controllable.  It makes the ship a black box too in certain respects.  As you grow as a developer you can make use of this.  You can hide a lot of complexity and make things look a lot simpler.

Is object-oriented programming the end-all of things?  Short answer, "NO".  Object-oriented has weaknesses too.  As programs continue to grow, and as things are getting more "parallel", object-oriented programming too is starting to show cracks.  There are attempts at the moment to mix object-oriented with functional programming (e.g. the Scala language).  Functional programming on its own is very weak and suffers from procedural flaws.  However, functional programming is great for writing code that can be used in parallel.  The Scala language is a very good attempt at mixing object-oriented with functional and shows promise.  Scala's main weakness is that it is a complex language, possibly too complex for mass-adaptation.

The main object-oriented languages of today are (in no particular order) Java, C#, C++, Perl, Python, Scala, Ruby, and Java-script.

It is also important to note that "Java" is not related to "java-script".  They are two completely different languages.

peace-out

NB. Peter's maxim;

          "code should be no more complex than what it needs 
            to express succinctly and clearly."
                                                                                        -- pmgdv


Tuesday, 30 July 2013

a java-script game, tech-spike

First of all, a special thanks to Ants the Java Monkey for pointing me to a most excellent
blog on the creation of a C64 classic game "Survivor" on http://www.schillmania.com
Go and have a read - it is very well written.

I will be taking a much more technical approach, and I am approaching the game more
from a technological point of view than a "faithful recreation" of something bygone.

I will not spend a lot of time on requirements gathering (typical programmer).  Assuming
this is already done, I will show you how a programmer implements such requirements.

MDA (Model Driven Architecture) is my design philosophy as an expert programmer.
Without too much fanfare, it basically boils down to:

1.  talk to the customer / gather your requirements (Business Analysis work)
2.  design your object model (object oriented data modelling)
3.  put your functions on top of this model (encapsulate behavior etc.)
4.  come up with a deployment plan
5.  deploy it, rinse and repeat till you get it right.

There is actually one more step which I personally like to do before any of this.
For peace of mind, and to build confidence.  Its what I call a "tech-spike" - it basically
means that before approaching the problem, I try and conceive all the things that might be
"difficult" technically, and solve them individually ahead of time.  Thus removing the potential roadblocks.

A game typically requires the following high level things;

i.   rending (animations, drawing)
ii.  double buffering to do the rendering smoothly
iii. user input
iv.  loading images
v.   loading other assets (like levels)
vi.  a game logic loop (doing something)
vii. sounds

We're going to keep it simple as possible.  And I will address each of these issues in turn as a tech-spike with a little sample to show you how it works.

So to finish off this post, lets take a quick look at the first item which might take a few posts, but is well worth understanding.

The game we're writing will be a 2d game.  3d is a little more difficult and still a little more shaky when it comes to html 5.  The mathematics is also a bit more difficult.

Drawing in java-script

I am terrible at graphics, and laying out interfaces etc.  There are some programmers that have the gift but that isn't me.  Games design and writing is a skill in its own right.  The last games development company I worked for had 20 graphic artists (3d artists, animators, 2d artists, art directors etc.)  If you want a professional looking game you need to mix your talents with theirs.

Html 5 introduces a new element called a canvas.  A canvas is basically a rectangular surface on your page where you can draw 2d (or 3d) objects.  2d objects typically consist of images, text, rectangles, circles, lines etc.

Lets take a look at a typical canvas inside an html page.

<html>
<body>
  <canvas id="gameCanvas" width="200" height="200" style="border:1px solid #000000;">
  </canvas>
</body>
</html>

This creates a canvas 200 pixels wide and 200 pixels high with a black border around it.  The canvas can be referred to as "gameCanvas" (its "id").

Java-script is an incredibly power language.  It might not be the fastest on the planet, but its got really good performance these days.  Couple that with hardware accelerated drawing (hidden from you), any java-script drawing you execute is going to be very fast on a modern machine.

One last thing on browsers.  Html 5 is new.  Some older browsers aren't good at either following standards or aren't that fast drawing (no hardware acceleration) or running java-script (badly implemented java-script engines).

My advice, stay away from anything less than Internet Explorer 9 (e.g. IE 8, 7, 6 are out).  Generally, the latest browsers are your best bet if you're a developer.  Think of it this way.  Games take a while to write, especially if you've got a lot of graphics and big plans for a story.  If it is going to take you a year to write (big titles take many years), you can plan ahead a little.  We typically developed against high end video cards in C++ / DirectX and made the assumption that what is high end now, will be average in a year or two.

Lets change the above example with some embedded java-script (java-script inside the html page).  This is not my preferred way of writing - I will show you a better way further down the road.  This is just to demonstrate the "tech-spike" of drawing.

<html>
<body>
  <canvas id="gameCanvas" width="200" height="200" style="border:1px solid #000000;">
  </canvas>

  <script language="javascript">
    // get the game canvas dom element
    var screenCanvas = document.getElementById("gameCanvas");
    // get the 2d version of the canvas of this object to draw into
    var screenContext = screenCanvas.getContext("2d");
    // set the current drawing (lines, text, points) colour to lightish grey
    screenContext.fillStyle = "#aaaaaa";
    // use a 12 pixel high Tahoma font
    screenContext.font = "12px Tahoma";
    // write some text from the top left corner 50 pixels across, and 50 pixels down
    screenContext.fillText( "Hello world!", 50, 50 );
  </script>

</body>
</html>

The output of this looks something like


In terms of a coordinate system, we're looking at


That's all we have time for tonight.  Next time we'll really dig deep into drawing in java-script.

Monday, 29 July 2013

a java-script game

Games are there to entertain.  I personally always enjoyed writing the code more than playing the game.  Its a puzzle, I like puzzles.  A game I really liked was the Gravity Force 2 game on the Amiga.

I decided to rewrite it in java-script.  Mainly to brush up my own java-script development skills, and to see how java-script / HTML 5 performs on modern computers.

The other advantage of java-script and HTML 5 is that they are the current language of the Internet so to speak.  They also provide a rich cross platform for other devices.  Sure, they are still immature in that respect, but I have hope that they will evolve and that somehow naively everything falls into place.

So in this blog - I will write this game, step by step.