Learn to Code


A programming or 'code' tutorial for interested beginners to learn some of the basics.

What you will need:


What I will teach you:

This is designed to give you a little bit of a taster into the world of coding and programming. Spend enough time practicing and you can make some really nice things.

A little bit of Javascript

Javascript is one language of many but is one of the more accessible languages to learn for a beginner for the following reasons:


Some basic javascript looks like the text below in a typical editor such as notepad++
Everything in the image below will be understandable by you if you master the knowledge I am going to share on this page and so much more.

An introduction to data

Data is best thought of as 'stuff the computer knows'. Typically we store it in what is called a 'variable'. In mathematics at high school you would have been used to hearing about 'x' and 'y' for algebra. Variables are similar. They are blocks of memory that we assign a name to that stores something such as a number, a piece of text, a color, an image, a sound, and so on. I'm being fairly loose here with my definitions though - so you may get more exact terminology from a lecturer or computer scientist.


In a javascript program data comes in 3 main forms:
1. Basic Variables - storing a single number, or a single piece of text
2. Arrays - storing a collection of numbers, objects, pieces of text or so on that are referenced with an index - similar to looking up a page in a book by the page number.
3. Objects - these are a way of grouping arrays and variables into a single named entity. For example you might have a 'creature' in a game that has variables to store its 'health', 'age', 'weight' and so on. Rather than storing independent variables for each of these we can group them under an object and these values become 'properties' of the object rather than mere variables.

In javascript - as with many languages - a variable, array or object needs to be declared before it can be used, though often we declare it and use it at exactly the same time.
What do I mean by 'declaring' it?

Declaring a variable means we are telling the computer that this named 'thing' is going to be used to store data of a particular type.
Javascript makes it easy for us in that we don't have to specify that much. For example, I could declare a variable called 'weight' and store in it either just a number or a number plus the units (kg/lbs).
EG:
var myweight = '90kg';
or
var myweight = 90;

The main difference is that if we store it as a number we can use the basic operators such as addition, subtraction, multiplication and division with it.


Declaring a variable is done with the 'var' statement.
EG
var hitpoints = 0;//declares a variable called hitpoints which stores the number 0 in it.
var creatures = new Array();//declares an array (currently empty).
var template = new Object(); //declares an object (without defining its contents) and calls it 'template'.

Javascript is a little different from some languages. Arrays can be resized on the fly, and Objects can have properties (eg health, height, weight) defined and declared at any time - but you will run into problems if you try and access a property or variable or array or anything which has not been already declared. In other languages it either will not compile or will crash, but in javascript you just get unusual behaviour as the program often continues to run but not as expected.
You will notice I finished each line or statement above with a semicolon. This is not necessary in Javascript but because I am used to it in a number of other languages and it is accepted in Javascript I choose to finish my lines with a semicolon. You can put multiple statements into a single line by doing so, but it doesn't look good.
To store data in an array once we have declared it we need to specify the 'index' number that we are going to access. In other words, think of it like a book with pages.
Each page contains data, and the page is referenced by a number. Typically we begin at '0' and work our way up. There is effectively no upper limit to the number of indexes. So we might do this:
creatures[0] = 'a man';
creatures[1] = 'a goblin';
creatures[2] = 'a dragon';
creatures[3] = 'an alien';

That declares 4 elements of the array, which can be accessed by referring to the index 0 to 3 in this case. You will notice I put a single quote around the text 'a man' and so on. These could also be " double quotes. But I prefer single quotes where possible. Quotes are placed around text data.
The array element is referred to by putting square brackets around the index number. Some languages use round brackets, a few use curly braces, but many use square brackets. Often getting these wrong can be a source of error in your code.


To define an object and its properties we simply do the following (using our object called 'template' above: )

template.color = 'red';
template.size = 'big';
template.age = 1;
template.weight = 100;
template.speed = 0.1;
template.books = new Array();
template.books[0] = 'Great Expectations';
template.books[1] = 'The Hobbit';
template.books[2] = 'Ethel the Aardvark goes quantity surveying';


In this case I have defined some properties that store text, numbers and one property that is an array. I have then defined the elements of that array.

It would be no good if we couldn't do anything with these variables, properties, objects and arrays. So we have lots of operators, some built in, some we can build ourselves to change the values and refer to them.


I won't cover all the operations we can do but the simplest ones that you will use most are the following especially for numeric data:
+ Addition (we can also use addition for text data and as you might imagine it adds blocks of text together to form longer strings of text - this is called concatenation.
- Subtraction
++ Increment by 1
-- Down count by 1
* Multiply by
/ Divide by
% Modulo (divide by a number and return the remainder - used with integers)

So for example we might want to work out the weight of a man and his luggage at the airport. So we could do this:
var totalweight = man.weight + luggage.weight;


I define a variable called totalweight, and take the weight property of an object called man and an object called luggage and add them together


Or I might want to know how fast a car has driven on the freeway:

var carspeed = distancetravelled / timetaken;


That covers a lot of the basics of declaring and using arrays and variables - there's a large amount more than this to cover in detail but you have a start.

A look at loops

Loops - loops are your best friend and your worst enemy.

Loops are blocks of code that keep executing until some condition is reached that causes the loop to break. Infinite loops can be bad and are often the reason why code gets stuck - as a part of it enters a loop that never satisfies the exit condition.
A computer program simply follows a program through from top to bottom, jumping around as necessary as the instructions tell it where to go.
Loops are one of the mechanisms used to control where a program flows through the code. A simple loop that a lot of geeky kids wrote on computers on display in department stores in the 80s was something like this:


10 Print "My Cheeky Message"
20 Goto 10


I'll let you figure out what this might have been used for.


Two main loops in javascript that you will see me use a lot are 'for' loops and 'while' loops.

A 'for' loop is used to perform a series of actions a number of times.
A 'while' loop is used to perform a series of actions until a condition is met or not met.

A 'for' loop has a counter variable - I often use the variable names 'i' and 'j' - as a child I used 't' but typically 'i' and 'j' are used.
It looks like this:
for(var i=0;i<maxvalue;i++)
{

}
Note the placement of semicolons and curly braces.

The first part 'var i=0;' declares the starting value of i

The second value i<maxvalue; says to continue for as long as i is less than maxvalue (defined elsewhere)

The third part i++ says to increment i by one each cycle of the loop.

After that we have a set of curly braces. Inside these curly braces are the parts that are executed for each iteration of the loop.
It is possible to perform weird or different variations on this with a for loop - such as going backwards, or jumping around rather than incrementing by a fixed amount. Not really recommended unless you know what you are doing.
Also - it is generally bad form to change the value of 'i' inside the curly braces. It will work but is not really how it is intended to work.

A common practice with a for loop such as this is to use it with an array.
Our earlier example of our array called 'creatures' had 4 elements, indexed as 0 to 3.
Rather than referring to the element of the array by the actual number we can use a variable, such as 'i' in this case.
And even better - if we want to perform the same or similar action on all the 'creatures' we can do it with a for loop like this:
for(var i=0;i<creatures.length;i++)
{
// do stuff with creatures[i] in here - note I used the expression [i] - in other words rather than using 0-3 I used the variable i to refer to the element.
}


A 'while' loop looks like this:
while(condition==true)
{
// statements go in here
// typically some method of changing the condition to 'false' will occur here to escape the loop.
}

You might use a while loop for something like this:
while(deployedmonster==false)
{
// try and deploy the monster and set deployedmonster to 'true' when you have done so successfully.
}


It's not always necessary but sometimes it is worth including a counter in the while loop and forcing
the loop to exit if too many cycles are performed.
The situation determines when this is a good idea.
For example - in the above example, maybe there is no good place to put the monster, so rather than trying forever we put a counter in that if it goes above 100 attempts, or a 1000, or 50 or whatever we jump out with a 'break' statement.
Our main usage for the two loops comes down to a few things:
If we want to perform an action multiple times in a row then a for or while loop is useful.
If we want to perform an action on all elements of an array then a for loop is very useful.
If we want to perform an action multiple times while a condition is true then a while loop is useful.

A taster of 'if' statements

The 'if' statement is your best friend in programming.


An 'if' statement says 'if this condition is true, then do these actions' it is typically combined with an 'else'
There are in some languages 'elseif' statements that allow for multiple else statements but I don't use them in Javascript.

So for example you might say
if(person.age>=18)
{
person.allowedtovote = true;
}
else
{
person.allowedtovote = false;
}

The variety of conditions we can impose are huge - infinite actually. But if all we could do is check one value in an if statement it would not be very useful. So we also combine it with 'and','or' and 'not' operators.
In different languages these are different. Some languages use words, some languages use symbols and some languages use different symbols. The way we compare two values in Javascript is usually like this:
if(person.age==18) //note I used two equals signs...some languages use a single equals sign - in Javascript using a single equals will not do what you want so don't do that!
{
person.isanadult = true;
}
if(person.gender!='male') //the not equals operator '!='
{
alert('This person is not male');
}
if(person.allowedtovote==true && person.enrolledtovote==true && person.didnotvote==true)
{
alert('This person will be fined!');
}
That (&&) was an example of the 'and' clause - which evaluates as 'true' if the combinations are all true
if(person.eyecolor=='blue' || person.eyecolor=='brown')
{
alert('You have either blue or brown eyes');
}
the || symbol represents 'or' and is true if either of the two statements is true.

In many languages there are other operators than these, but these are a starting point from which you can make almost all others.


You will note I use curly braces around the statements and round brackets around the if condition test....do that.
It varies from language to language.

A thing called 'SCOPE'


Something I've not talked about yet but which is extremely important is a thing called 'SCOPE'.

Imagine you are talking to a friend about a tv show. Halfway through the conversation another friend walks over and hears your comments about one of the characters. Unless they know what you are talking about they won't necessarily know what show the character belongs to.
That is kind of like SCOPE.

SCOPE says that a variable, object or array is only known 'local' to the function, loop, if block or so on that it belongs to.
The easiest way of knowing where scope starts and ends is looking for curly braces { }
Anything inside a pair of curly braces is at the same level of SCOPE, and is able to be accessed by any sets of curly braces INSIDE that pair.
In my code you will see a lot of variables defined at the 'top' level outside of curly braces.
Sometimes this is considered bad form. Global variables are often thought of as a thing of the past - a variable which is accessible EVERYWHERE.
But they are useful - and they have their advantages.
But local variables - variables defined with a function or a SCOPE are neater and better to use wherever possible.
Here is an example:
var counter = 0;
while(condition==true)
{
var x = //some calculations;
counter++;
// some more statements
}
alert(counter); //will give the value because counter was defined OUTSIDE the while loop and changed within it
alert(x); //will throw an 'undefined' or error because x only exists inside the curly braces and is destroyed afterwards.


SCOPE really comes into play though in the next section:

Functions

Functions are your bread and butter in Javascript and in many languages.
Some languages refer to them as procedures, subroutines, functions and a variety of things.
The terminology varies from language to language but how I will explain the function is like this:

A function is like your microwave. You put things in, the microwave does its stuff, and you get some cooked food back.

A function has 'parameters' or 'arguments' which are like the food you pass to the microwave and the settings you push on the front panel. Inside the function the cooking takes place. At the end of the function cooked food is given back.
The analogy breaks down a little because it is not the arguments or parameters that change but usually a different value is given back entirely.


You declare a function as follows (example)
function mybadaddition(number1,number2) //note no semi colon at the end of the line
{
var number3 = number1 - number2;
return number3;
}

And you would call the function like this in your code:
var mynumber = mybadaddition(10,20);
mynumber would have the value '-10'.


Functions are amazingly useful.
Note - you don't have to return a value. This is sometimes useful too. Sometimes you just wish to perform a group of operations and be able to call it multiple times with a single statement.
For example you might want to have a function that beeps a noise, alerts the user with a message, and sends an image to the screen. And you might want it to do it at all different points in the program. By combining it into a function you can then call that function wherever you want.

SCOPE and FUNCTIONS:
Variables, Objects and Arrays defined inside a function are ONLY accessible inside that function. And THEY ARE FORGOTTEN once the function exits.

2d Game Engine


Games follow fairly simple logic at their heart.
All programs involve breaking down the process into its component 'ideas' and 'logic'.

In the same way movies follow a pattern and a formula, as do books so do programs for games.

The typical structure of a simple game is as follows:

Load Game Data
Start Game Loop:
{
Get Input From User
Update Objects in the Game
Draw the Game
}
After the Loop Exits:
Unload Game Data / Clean Up

Some game engines and systems don't need the clean up process but it is good to have as it is the basis of being able to successfully load extra levels, and so on - by cleaning up the system to a 'fresh start' we can then load the next level knowing that we're all ready to go again.

But the main loop only has three main things it has to do.

Get the user input such as mouse movement and keyboard input.

Move the game objects around, check for collisions, perform calculations

Draw the game objects and effects


That's basically it.


In my web games I have a library I've written myself which is a nice neat structure that I can re use and do so over and over.
I have a Javascript file called init.js where all my loading goes. I have a Javascript file called renderer.js where all my drawing takes place internally. And a file called gamedata.js (or variation of) that is where everything else takes place.
The index.html file has a loop which runs 'n' frames per second (typically 30 or 60) and which calls 'handleinput(); updategame(); and drawgame();'
In some games I get lazy and mix them up a bit.



Hope that is reasonably clear.

Enjoy coding.


2d Game Engine

Game Engine For You To Use


Engine zip file (base media and code)
Main Index
Initialisation Routines
Miscellaneous Functions
Core Game Functions and Data
Gui Simple
Renderer (2d)