Monday, December 17, 2012

Using Torque and Thrusters to Move and Rotate a Player-Designed Spaceship

While working on a game in which the spaceships are designed by players and can be partially destroyed, I encountered an interesting problem: moving a ship around using thrusters is not an easy task. You could simply move and rotate the ship around like a car, but if you want ship design and structural damage to affect ships’ movement in a believable way, actually simulating thrusters could be a better approach. In this tutorial, I’ll show you how to do this.
Assuming a ship can have multiple thrusters in various configurations, and that the ship’s shape and physical properties can change (for example, parts of the ship could be destroyed), it is necessary to determine which thrusters to fire in order to move and rotate the ship. That’s the main challenge we need to tackle here.
The demo is written in Haxe, but the solution can easily be implemented in any language. A physics engine similar to Box2D or Nape is assumed, but any engine that provides the means to apply forces and impulses and query the physical properties of bodies will do.

Try the Demo

Click the SWF to give it focus, then use the arrow keys and the Q and W keys to activate different thrusters. You can switch to different spaceship designs using the 1-4 number keys, and you can click any block or thruster to remove it from the ship.

Representing the Ship

This diagram shows the classes that represent the ship, and how they relate to each other:
Gamedev Maths and Physics: Using Torque and Thrusters to Correctly Maneuver a Player-Designed Spaceship
BodySprite is a class that represents a physical body with a graphical representation. It allows display objects to be attached to shapes, and makes sure that they move and rotate correctly with the body.
The Ship class is a container of modules. It manages the structure of the ship and deals with attaching and detaching modules. It contains a single ModuleManager instance.
Attaching a module attaches its shape and display object to the underlying BodySprite, but removing a module requires a bit more work. First the module’s shape and display object are removed from the BodySprite, and then the structure of the ship is checked so that any modules not connected to the core (the module with the red circle) are detached. This is done using an algorithm similar to flood fill that takes into account the way each module can connect to other modules (for example, thrusters can only connect from one side, depending on their orientation).
Detaching modules is somewhat different: their shape and display object are still removed from the BodySprite, but are then attached to an instance of ShipDebris.
This way of representing the ship is not the simplest, but I found it to work very well. The alternative would be to represent each module as a separate body and “glue” them together with a weld joint. While this would make breaking the ship apart much easier, it would also cause the ship to feel rubbery and elastic if it had a large number of modules.
The ModuleManager is a container that keeps the modules of a ship in both a list (allowing easy iteration) and a hash map (allowing easy access via local coordinates).
The ShipModule class obviously represents a ship module. It’s an abstract class that defines some convenience methods and attributes that each module has. Each module subclass is responsible for constructing its own display object and shape, and for updating itself if needed. Modules are also updated when they’re attached to ShipDebris, but in that case the attachedToShip flag is set to false.
So a ship is really just a collection of functional modules: building blocks whose placement and type defines the behavior of the ship. Of course, having a pretty ship just floating around like a pile of bricks would make for a boring game, so we need to figure out how to make it move around in a way that is fun to play and yet convincingly realistic.

Simplifying the Problem

Rotating and moving a ship by selectively firing thrusters, varying their thrust either by adjusting throttle or by turning them on and off in quick succession, is a difficult problem. Fortunately, it is also an unnecessary one.
If you wanted to rotate a ship precisely around a point, for example, you could do that simply by telling your physics engine to rotate the whole body. In this case, however, I was looking for a simple solution that isn’t perfect, but is fun to play. To make the problem simpler, I’ll introduce a constraint:
Thrusters can only be on or off and they can’t vary their thrust.
Now that we’ve abandoned perfection and complexity, the problem is a lot simpler. We need to determine, for each thruster, whether it should be on or off, depending on its position on the ship and the player’s input. We could assign a different key for each thruster, but we’d end up with an interstellar QWOP, so we’ll use the arrow keys for turning and moving, and Q and W for strafing.

The Simple Case: Moving the Ship Forwards and Backwards

The first order of business is to move the ship forwards and backwards, as this is the simplest possible case. To move the ship, we’ll simply fire the thrusters facing in the direction opposite to the one we want to go. For example, if we wanted to go forward, we’d fire all the thrusters that face backwards.
Read more: Using Torque and Thrusters to Move and Rotate a Player-Designed Spaceship

Flash Haxe Gaming SDK, their tools, our tools

So Adobe released a few weeks ago its Gaming SDK for flash. The package includes Starling, Away3D and Feathers, three well know quality open source ActionScript3 libraries. You can easily find some externs for most of them on http://lib.haxe.org, which is great! However, during the development of my last game (which used Starling and Haxe) I found out that using haxelibs wasn't enough. A lot of good stuff is happening in the AS3 side, Starling is improving day after day on Github, users create really useful extensions for it. Time is precious and we don't want to write externs for everything or rewrite everything in haxe do we? Thanks to the great haxe/flash support, we can easily use all the good stuff in a matter of seconds, we can hack AS3 code and use the result from Haxe too. In this post I will try to teach beginners how to fish AS3 :)
  • how to compile a bunch of .as files into a .swf using the Flex SDK.
  • how to use those .swf files in haxe (with no extra work)
  • how to patch things when haxe is not happy with the .swf
We'll end up with the entire Adobe Gaming SDK, and more, for Haxe. But the journey is more important than the destination. NOTE: If you are not interested in the process and just want the SDK, I created a bunch of github repositories to host the results. See the test repository to learn how to play with it https://github.com/labe-me/haxe-gaming-sdk-test NOTE: I do not intend to write any extern for these libraries (I am too lazy for that), hence I won't submit them to haxelib. Feel free to use my work in any way you want to create nice haxelib packages. As far as I am concerned I really enjoy the haxelib git support :) Start. We are going to compile .as files, you'll need to install the Flex SDK. Let's learn how it works with Starling. (1) get the library sources:
[...] read more: Flash Haxe Gaming SDK, their tools, our tools

Thursday, December 13, 2012

Creating a Custom Virtual Keyboard

Although AIR for iOS offers access to the iOS virtual keyboard, you have limited control over the type of keyboard that appears. If you want additional keyboard configurations within your Flash project then you’ll need to build your own custom keyboard component. Although this will require some development effort it will allow you to tailor the user experience. For certain apps such as games, you may actually find a custom keyboard is the preferred option, as it will better fit your visual design.
Let’s see how to create one using Flash.
Flash iOS Apps CookbookThis tutorial is a previously unreleased recipe from Flash iOS Apps Cookbook and supplements the content found in Chapter 7, Working with Text and the Virtual Keyboard.
Flash iOS Apps Cookbook provides the recipes required to build native iOS apps using your existing knowledge of the Flash platform. Whether you want to create something new or simply convert an existing Flash project, the relevant steps and techniques are covered, helping you achieve your goal.

Getting Ready

An FLA has been provided as a starting point.
Download this recipe’s accompanying source bundle and open chapter7/recipe8/recipe.fla into Flash Professional.
The visuals for this application have already been created. Sitting on the stage is a virtual keyboard and a dynamic text field. The text field will be used to output what the user types.
The dynamic text field has been named field while the movie clip instance that represents the virtual keyboard has been named keyboard.

Entering a player's name with a custom virtual keyboard.
With the Selection tool (V) selected, double-click on the keyboard instance to examine its timeline. The keyboard contains 28 keys – 26 for the letters of the alphabet, an ok key for when the user is finished typing, and a del key to delete a character. You’ll find that each alphabetic key is represented by its own movie clip and that the instances are named a_key to z_key. This naming convention makes it easy to determine the letter that a key represents by simply examining the first character of its instance name. The remaining two keys have instance names of ok_key and del_key. Additionally there’s a movie clip named surface that sits beneath the keys and represents the keyboard’s body.
Double-click on any one of the keys to examine its timeline. Each is represented by two frames, where the second frame will be shown when the key is being pressed. The movie clip symbol for each key is linked to a class named Button, which was introduced in the Handling user interaction recipe from Chapter 4. Open Button.as and familiarize yourself with the code.

How to do it…

Perform the following steps.
From Flash, select File | New and create a new ActionScript 3.0 class. Name it VirtualKeyboard.
  • Add the following ActionScript to the class:
    [...]
    Read more: Creating a Custom Virtual Keyboard
  • Wednesday, December 12, 2012

    Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler

    Adobe Scout allows developers to profile SWFs like never before. The telemetry data sent by the release Flash Player to Adobe Scout is by default only set to send basic telemetry data. To be able to see data for the AS3 sampler, Stage3D rendering, and DisplayList rendering you have to enable the SWF (password is optional).
    This is done by using the newer asc2 compiler that comes in Flash Builder 4.7 or in the AIR sdk found in the Gaming SDK from Creative Cloud. Currently asc2 only works with ActionScript projects and implements a new flag called -advanced-telemetry or a check box in Flash Builder 4.7 ActionScript project properties.
    To enable SWFs that don’t use asc2, mainly Flex apps or legacy SWFs, you need to use a script to write a specific SWF tag into the SWF file. This doesn’t change the SWF abc code but just adds a SWF tag that Flash Player will use to start sending telemetry data. There is a python script written to help with writing this tag. But the python script requires python and I wanted something a bit easier to use so I created SWF Scout Enabler.

    To use the application all you need to do is drag your SWF into the application and it will create a new SWF (or override if you give it a “” suffix) that is enabled for advanced telemetry.
    The application will also save the last suffix and password used. It also has the ability to re-process the last processed file by clicking on the top right box image.
    Last but not least, the full source of the application can be found on github.
    Download the SWF Scout Enabler AIR application.
    I need to thank Joseph Labrecque for testing out the app.
    Note: This app has been tested on a bunch of SWFs but if it is not working let me know. There seems to be a bug with Adobe Scout on AS2 SWFs older than version 8. Adobe Scout will never do ActionScript sampling on AS2 SWFs but it will do basic telemetry.

    Read more: Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler

    Tuesday, December 11, 2012

    Animating With Asset Sheets: An Alternative to Blitting

    So you’ve got your awesome game in the works, it’s got all sorts of complex physics, epic enemy AI or what-have-you. But it feels lifeless. You want some OOMPH, you want some animation!
    So if you go and look up how to animate, the first answer you come across will most likely be a method using spritesheets and blitting. In fact, almost all tutorials on the web talk about nothing but blitting, as if there’s no other way to animate. But in my experience, there’s a better way to animate your orcs and goblins!
    This method could be called animating with asset-sheets – or more technically, tweening with asset-sheets – as opposed to using sprite-sheets. Before we get into exactly what this means, let’s consider an important question:

    What’s Wrong With Blitting?

    Below are some reasons as to why you would not want to use blitting in certain cases.

    1. It Takes a Lot of Space

    Whether we’re talking about RAM or disk space, sprite sheets can easily clog things up. Especially if you’re trying to make HD graphics. Huge sprite sheets may have to be split into multiple PNGs, taking up precious RAM and skyrocketing your game’s size if you’re not careful.

    2. It’s Not Dynamic

    What happens when you want to speed up an animation? You could skip some frames, but what about slowing down? The animation would look choppy and ugly. Even if you want to only support 60 fps, what if a computer can run the game faster? You could have jaw-droppingly smooth animations at higher frame rates with no extra work, and it would also look good if you chose to change the game’s frame rate at any time.
    And what if you wanted something to happen when the player’s arms reached some place? Or to have him pick up something? You’d need to manually mark his arm throughout the animation, which may be time-consuming as you can’t get any data about where any of his limbs are from a sprite sheet.

    3. It Doesn’t Allow You to Make Transitions

    What happens when the player is running and suddenly jumps? It cuts to the jump animation right away. This looks choppy, and this would happen every time the animation transitions to a new state. You’d have to make a transition for every pair of animations you have, which is not only insanely time consuming, but also has the adverse effect of increasing your RAM usage as discussed earlier.

    The Alternative

    Using asset-sheets not only allows the animations to be dynamic and scale up with any FPS, as well as transitioning smoothly between any two states, but also takes a tiny tiny amount of disk space and RAM compared to blitting!
    This isn’t even very new. Some popular games use it, like the recently popular Closure.  Its only limitation is that it can’t do frame-by-frame (FBF) animation, since it relies on tweening – so if you have complex explosions, you’ll have to use sprite sheets.
    But for a lot of cases, you’ll find you won’t need to, and it’s more than worth the effort to have a system like this for your game, as some games could rely completely on this, shaving off a ton of overhead. It’s also really cool because it’s similar to how you might animate a 3D game!
    So to summarize:
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting

    Let’s Dive Right In

    This is a character and his asset sheet.
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting
    As the name implies, an asset sheet is a PNG with all the limbs/assets of the character or object separated.
    And here is the animation data in JSON (of course, you can use whichever format you prefer to work with):
    //this snippet shows the first three frames of the "Body" animation
    "-name":"Body",
    "Frame": [
    {
     "-x":"0.65",
     "-y":"-64.45",
     "-rotation":"0.000"
    },
    {
     "-x":"2.45",
     "-y":"-64.45",
     "-rotation":"0.279"
    },
     "-x":"3.30",
     "-y":"-64.05",
     "-rotation":"0.707"
    }
    
    Now combining these two together in an awesome engine, you get:
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting
    And unlike a blitted animation, this could speed down or up, or transition very smoothly. So this is what we'll be doing.

    Step 1: Exporting Your Asset Sheet

    The first step is to get your asset-sheet ready. You can do this in any number of ways. The point is to end up with a sheet containing the assets and a data file containing the positions of the assets in the sheet. This is the exact same method as for making a spritesheet, except in lieu of sprites you add separate assets.
    Export your player's limbs and pieces as individual PNGs, then use a program like Texture Packer to group them into a sheet. There are other programs, but I personally prefer Texture Packer because of how versatile and feature-rich it is.
    Tip: Whatever software you use to make your sheets , make sure there is at least 2px of padding between each asset and 1px extrusion. This will prevent some nasty problems in the future.

    Step 2: Exporting Your Animation Data

    [...]
    Read more: Animating With Asset Sheets: An Alternative to Blitting

    Tuesday, December 4, 2012

    Introducing Game Developer Tools

    I am really excited about what happened tonight. We just announced the introduction of the Adobe Game Developer Tools on Creative Cloud. You can read the official announcement here. As part of this, we are introducing three new products: Adobe Gaming SDK, FlasCC and Adobe Scout, which I have been working on for a year now. Here is a video about Adobe Scout and why it is going to change everything for your as a developer: I wrote a full article on how to get started with Scout. Make sure you check it out! If you have any questions, check the Scout forums! If you want to take a deep dive in Scout you can also check the video tutorials here. We also wanted to provide a great out of the box experience for developers to get started with the stack. Provide a nice package that allowa developers to get up and running quickly without having to hunt for the frameworks needed, the compilers and right documentation. That's why we are also introducing the Gaming SDK: The Gaming SDK contains the key frameworks you guys need to use to create fast performing 2D and 3D GPU games, but also much more, from the ATF tools to iOS ANEs. Starling, Feathers and Away3D are officially supported by Adobe and part of the Gaming SDK. It provides to you a one stop shop package to get started with the technology, we hope you guys will enjoy it! For those of you guys doing native development and interested in porting native games to the desktop, you can now use FlasCC (formerly named Alchemy), which is now release quality and supported.

    Read more: Introducing Game Developer Tools

    Friday, November 30, 2012

    How to make a Facebook social game

    Hi and welcome back to my blog!
    This time I’m going to talk about the process of making a very basic social game as a Facebook app.
    It’s my hope that if you know how to make a Flash game and have a little bit of PHP/database experience by the end of the article you will be set to make your first Facebook app.
    This is a technical article covering the implementation of some of the core social game subsystems and not intended to be a discussion about moral justification of social game mechanics or even about how to design a social game – I’ll leave those aspects to game-designers and the media :)
    The game I’m going to be making is called ‘Pet My Kitty’.

    Click to play the live version of the game on Facebook

    Pet My Kitty

    In a nod to the now defunct mock-social game, Cow Clicker Pet My Kitty will have an absolute minimal set of functionality necessary to operate as a social game:
    • Interactive mechanic
    • Database persistence
    • Ability to purchase an in-game item
    • Invite friends
    • Social marketing incentive
    Let’s quickly review each one of these points to elaborate on why they are key to a social game.
    Interactive mechanic
    There has to be something interactive about a Facebook game, no matter how simple otherwise it wouldn’t classify as a game. Furthermore, there needs to be something visually rich and rewarding associated with each interaction, so the user understands they are doing things the right way.
    Read more: How to make a Facebook social game

    Tuesday, November 27, 2012

    Using GDB script files with the FlasCC GDB

    The Flash C++ Compiler (FlasCC) provides a complete BSD-like C/C++ development environment based on GCC that lets you compile your C/C++ code to target the Adobe® Flash® Runtime (Flash Player and AIR®). With FlasCC you can port almost any existing C/C++ code to the web, across browsers. FlasCC includes tools for building, testing, and debugging C/C++ projects, example projects with source code, and documentation. You can get FlasCC today on the http://gaming.adobe.com/technologies/flascc/ page.
    Today I want to share a quick FlasCC debugging tip. The FlasCC based gdb tool is located in the FlasCC download under sdk/usr/bin/gdb (Mac) or sdk/usr/bin/gdb.exe (Win/Cygwin).
    Before trying this out we need a simple C app to debug. Go ahead and create a file called test.c and put the following code inside:
    C:
    #include <stdio.h>
    int main(int argc, char **argv)
    {
        int i = 0;
        printf("Hello World %d Time\n", i++);
        printf("Hello World %d Time\n", i++);
    }
    And the command to compile the debug SWF with FlasCC is:
    CODE:
    sdk/usr/bin/gcc -g test.c -emit-swf -o test.swf
    The FlasCC gdb relies on an environmental variable called FLASCC_GDB_RUNTIME, if you do not set it before running gdb you'll see the following message inside of the gdb prompt:
    CODE:
    (gdb) run
    Starting program: hello.swf
    Please set the FLASCC_GDB_RUNTIME environment variable to the path to a debugger player or browser.
    The FLASCC_GDB_RUNTIME needs to be set to the standalone debug Flash Player or to a browser that has a debug Flash Player. I recommend for the first time that you try using the FlasCC gdb to download a standalone debug Flash Player from here and us it. I downloaded the Mac version and put in a folder called /Code, which means I would run this command in Ternimal before I call gdb:
    CODE:
    export FLASCC_GDB_RUNTIME=/Code/Flash\ Player\ Debugger.app
    Lets take a look at my command line to see how to put this all together:
    CODE:
    renaun$ sdk/usr/bin/gcc -g test.c -emit-swf -o test.swf
    renaun$ export FLASCC_GDB_RUNTIME=/Code/Flash\ Player\ Debugger.app
    renaun$ sdk/usr/bin/gdb test.swf
    GNU gdb (GDB) 7.3
    Copyright (C) 2011 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "--host=x86_64-apple-darwin10 --target=avm2-elf".
    For bug reporting instructions, please see:
    <http://www.gnu.org/software/gdb/bugs/>...
    (gdb) b main
    No symbol table is loaded.  Use the "file" command.
    Make breakpoint pending on future shared library load? (y or [n]) y
    Breakpoint 1 (main) pending.
    (gdb) run
    Starting program: test.swf
    0xdddddddd in ?? ()
    Breakpoint 1, 0xf0000051 in main (argc=0, argv=0x200ff0) at test.c:5
    5       int i = 0;
    (gdb)
    So I setup export to the debug Flash Player and then ran the gdb against the SWF. But once in side the gdb command prompt I still need to setup a break point. When trying to setup a break point before starting the SWF it will display another warning which needs a yes response. After responding with a yes I can then type run.
    Here is the trick, by using gdb -x script.txt we can run it all in one command. Instead of having to type in my break point each time or responding yes. This is how it works, create a script.txt file and put in the following gdb commands:
    CODE:
    set breakpoint pending on
    b main
    r
    The first line sets the default warning option to be yes so you dont have to worry about it not being set. The second command sets a break point at the main function. And the last command runs the gdb, telling it to start. The command to use the gdb script is below:
    CODE:
    renaun$ sdk/usr/bin/gdb -x script.txt test.swf
    Another handy command to put in script.txt is the set as3namespace com.renaun.test command. This is needed if you create a FlasCC SWC with a custom namespace.

    © %FIRST Erickson - visit the <renaun.com:flexblog text="{ ModelLocator.myThoughts }"/>


    Read more: Using GDB script files with the FlasCC GDB

    Monday, November 26, 2012

    Quick Tip: The OOP Principle of Inheritance

    This entry is part 6 of 6 in the series Beginner's Guide to OOP

    We’ve come a long way in this beginner’s guide to object-oriented programming, discussing the principles of cohesion, coupling, encapsulation, and abstraction. In this final article, we’ll discuss the OOP principle of inheritance and its uses in game development. Note: Although this tutorial is written using Java, you should be able to use the same techniques and concepts in almost any game development environment.

    What Is Inheritance?

    Inheritance is the principle of class hierarchy. It is the ability for one object to take on the states, behaviors, and functionality of another object. A real-world example of inheritance is genetic inheritance. We all receive genes from both our parents that then define who we are. We share qualities of both our parents, and yet at the same time are different from them. Objects in OOP can do the same thing. Parent classes can have child classes (also known as superclasses and subclasses respectively) which can have the same properties of the parent class, and can define new states, behaviors, and functionality of their own. As an example, consider the following class that could be used as a parent class to different shapes:
    public class Shape {
      protected int height;
      protected int width;
    
      public Shape(int h, int w) {
        height = h;
        width = w;
      }
    
      public int area() {
        return height * width;
      }
    
      public int getHeight() { return height; }
      public int getWidth() { return width; }
      public void setHeight(int h) { return height; }
      public void setWidth(int w) { return width; }
    }
    
    To extend this class to implement a triangle, it would look like this:
    public class Triangle extends Shape {
      public Triangle(int h, int w) {
        super(h, w);
      }
    
      public int area() {
        return super.area() / 2;
      }
    }
    
    Triangle has all the same states and functions as Shape, but redefines the area() function to return the proper area of a Triangle (half base times height). The keyword super is used to reference the superclass and any of its states and functions. This is why we can use super() to call the constructor of the superclass and super.area() to call the area() function of the superclass. So, in this case, super.area() returns height * width. The protected keyword is the last access level modifier. It acts like the private access level modifier but also allows any subclasses to have access to the variable or function.

    Why Is It Helpful?

    As you can see, inheritance can greatly help reduce code redundancy between similar objects by taking what those objects have in common and putting them in one place. This also creates more maintainable code because it helps to comply with the principle of DRY and to prevent the ripple effect in code changes. If all of this seems familiar, it’s probably because abstraction had very similar benefits (as well as most of the other principles of OOP). Abstraction is closely related to inheritance as an abstracted class can be used as a superclass to create subclasses. The only difference between an abstract class and a normal class is that an abstract class cannot be used to create an object.

    How to Apply It

    Lets go back to our three games one more time to describe how to apply inheritance.

    Asteroids

    Recall that we defined an abstract class for moving objects across a screen. Also recall that we defined a Ship class for the ship object. To apply inheritance to Asteroids, we can have the Ship class extend the Movable class as follows:
    /**
     * The Ship Class
     */
    public class Ship extends Movable {
      /**
       * Function to rotate the ship
       */
      public void rotate() {
        // Code that turns the ship
      }
    
      /**
       * Function to fire
       */
      public void fire() {
        // Code to fire
      }
    }
    
    The code needed to move the ship is taken care of in the Movable abstract class, so we can remove it from the Ship class. All the other objects for Asteroids could also inherit from the Movable class, making it extremely easy to change how to move an object. One thing to note about inheritance is the ability to have multiple inheritance, or the ability of one class to inherit from multiple classes at the same time. Some languages allow it, others do not. Java is one of the languages that does not allow multiple inheritance. Therefore, you couldn’t have the Ship object inherit from both a Moveable class and a Drawable class. Make sure you are familiar with what your programming language allows before you try to design inheritance into your game.

    Tetris

    Inheritance can be applied to Tetris by having the Tetrimino and all of the game visuals inherit from the Drawable class, which we defined in the last article.

    Pac-Man

    Recall that for Pac-Man we identified thee objects: Pac-Man, a Ghost, and a pac-dot. Throughout this series we’ve only discussed these three objects and have put off mentioning anything about the last critical piece of Pac-Man: the power pellet. With inheritance, we are now ready to talk about it. A power pellet is a special pac-dot that allows Pac-Man to eat ghosts. Its states and behaviors are exactly the same as a pac-dot, with really the only difference being its size and the ability to blink (remember that to keep the game loosely coupled, we want another class to monitor when a power pellet is eaten and active the changeState() method of the ghosts). This is when inheritance comes in handy. Since a pac-dot and power pellet are practically the same object, we can create a PowerPellet class which extends the PacDot class. The PowerPellet class would just need to modify a few states to make it bigger and add the behavior of growing and shrinking to create a blinking effect. And that’s it – we now have a power pellet with little extra work. Not too shabby. The code for how this would look could be as follows:
    Read more: Quick Tip: The OOP Principle of Inheritance

    Tuesday, November 20, 2012

    How to make a multi-player game – part 2

    Hello and welcome back to my blog! This is part 2 in the series where I talk about making a multi-player game.
    Last time we built a TCP socket server in node.js and we’re able to send and receive complex types. Read the first article if you’ve not already done so here.
    Here is a live version of the game I’m describing in this series:

    Clock synchronisation

    It’s important that both the client and server’s clocks are synchronised because if there is any time based interpolation, you want both server and client to agree on what time it is and therefore at what position your interpolated object is.

    Asteroids on an interpolation orbit
    I use this technique in 2D Space MMO to ensure the orbiting asteroids are in the same position across all clients and on the server. The asteroids are actually interpolating on an orbit around a central location – there are no update messages getting sent to correct their positions, the only thing which keeps them synchronised is having the same time value across all clients and server.
    Before we can try to synchronise clocks, we need to be sure we’re using the same concept of time on both server and client. We want to calculate the number of seconds since 1970/01/01, which is the same in both javascript and actionscript:
    Read more: How to make a multi-player game – part 2

    Monday, November 19, 2012

    Quick Tip: The OOP Principle of Abstraction

    This entry is part 5 of 5 in the series Beginner's Guide to OOP
    We’re almost done with this series on object-oriented programming, and in this article we’ll discuss the OOP principle of abstraction – that is, generalising an object – and its use in game development.
    Note: Although this tutorial is written using Java, you should be able to use the same techniques and concepts in almost any game development environment.

    What is Abstraction?

    Abstraction is the principle of generalization. This requires that we move from a specific instance to a more generalized concept by thinking about the most basic information and function of an object.
    This may sound a bit strange, but we are already familiar with the concept of abstraction. For example, if I say the word “car”, what do you think of? Odds are we weren’t thinking about the same car. I was thinking about a black Mustang Boss 302, which is a specific instance of a car. Neither of us were wrong because the word car is a very general concept of a vehicle that we use for transportation (or recreation in my case).
    The same goes for video games. Video games are categorized into groups such as RTS, RPG, Racing, etc.. These groups are all generalized concepts that describe the gameplay of a game. StarCraft II, Elder Scrolls V: Skyrim, and Need for Speed are all specific instances of these generalized concepts.
    Thus, abstraction takes many specific instances of objects and extracts their common information and functions to create a single generalized concept that can be used to describe all the specific instances as one.

    Why is it Helpful?

    Abstraction is helpful because it strips everything down to its most basic principles. This can help when encapsulating functionality of an object because it can help identify the important information that should be made visible and the unimportant information which can be made hidden.
    Abstraction also helps with the Don’t Repeat Yourself principle. By taking what a group of objects have in common and abstracting it, we can help prevent redundant code in each object which in turn creates more maintainable code.

    How to Apply This Principle

    As before, let’s use our three games to see some concrete examples of this principle in action.

    Asteroids

    [...]
    Read more: Quick Tip: The OOP Principle of Abstraction

    Thursday, November 15, 2012

    Quick Tip: The OOP Principle of Encapsulation

    This entry is part 4 of 4 in the series Beginner's Guide to OOP
    We’ve discussed object-oriented programming for game developers in general and the specific OOP principles of cohesion and coupling. Now let’s take a look at encapsulation and how it helps to keep code loosely coupled and more maintainable. Note: Although this Quick Tip is explained using Java, you should be able to use the same techniques and concepts in almost any game development environment.

    What Is Encapsulation?

    Encapsulation is the principle of information hiding. That is, the implementation (the internal workings) of an object is hidden from the rest of the program. A popular example you’ll hear for encapsulation is driving a car. Do you need to know exactly how every aspect of a car works (engine, carburettor, alternator, and so on)? No – you need to know how to use the steering wheel, brakes, accelerator, and so on. Another example is searching for a value in an array. In Java, you can do the following:
    int myArray[] = {1, 2, 3, 5, 7, 9, 11, 13};
    Arrays.asList(myArray).contains(11);
    
    The above code will return true if the value 11 is in myArray, otherwise it will return false. How does the contains() method work? Which searching technique does it use? Does it pre-sort the array before searching? The answer is it doesn’t matter because the exact implementation of the method is hidden.

    Why Is Encapsulation Helpful?

    Encapsulation helps to create code that is loosely coupled. Because the details are hidden, it reduces the ability of other objects to directly modify an object’s state and behavior. It also greatly helps when you must change the data type of a variable. Lets say you decided to use a String to keep track of time in “hh:mm:ss” format. After awhile, you come to realize that an int representing seconds might be a better data type for time. Not only must you change the data type in the object, but also every time you referenced the object’s time in the entire program! Instead, you can use what are known as getter and setter functions. Getters and setters are usually small functions that return and set a variable respectively. A getter function to get the time would look as follows:
    public String getTime() {
      return time;
    }
    
    The getter will return a String value: the variable time. Now when we want to change time to an int, instead of changing all calls to the getter we can just change the getter function to change the int data type into a String data type.
    Read more: Quick Tip: The OOP Principle of Encapsulation

    Thursday, November 8, 2012

    Quick Tip: The OOP Principle of Coupling

    This entry is part 3 of 3 in the series Beginner's Guide to OOP So far in this series, we’ve discussed object-oriented programming in general, and the OOP principle of cohesion. In this article, we’ll look at the principle of coupling and how it helps in game development. Note: Although this tutorial is written using Java, you should be able to use the same techniques and concepts in almost any game development environment.

    What Is Coupling?

    Coupling is the principle of “separation of concerns”. This means that one object doesn’t directly change or modify the state or behavior of another object. Coupling looks at the relationship between objects and how closely connected they are. A Relations Diagram is a great way to visualise the connections between objects. In such a diagram, boxes represent objects and arrows represent a connection between two objects where one object can directly affect another object.
    A relations diagram A relations diagram
    A good example of coupling is HTML and CSS. Before CSS, HTML was used for both markup and presentation. This created bloated code that was hard to change and difficult to maintain. With the advent of CSS, HTML became used just for markup, and CSS took over for presentation. This made the code fairly clean and easily changeable. The concerns of presentation and markup were separated.

    Why Is Coupling Helpful?

    Objects that are independent from one another and do not directly modify the state of other objects are said to be loosely coupled. Loose coupling lets the code be more flexible, more changeable, and easier to work with.
    A loosely coupled system A loosely coupled system
    Objects that rely on other objects and can modify the states of other objects are said to be tightly coupled. Tight coupling creates situations where modifying the code of one object also requires changing the code of other objects (also known as a ripple effect). Tightly coupled code is also harder to reuse because it can’t be separated.
    A tightly coupled system A tightly coupled system
    A common phrase you’ll hear is “strive for low coupling and high cohesion“. This phrase is a helpful reminder that we should strive for code that separates tasks and doesn’t rely heavily on each other. Thus, low (or loose) coupling is generally good, while high (or tight) coupling is generally bad.

    How to Apply It

    Asteroids

    First, lets look at the objects of Asteroids and how they are connected. Recall that the objects are a ship, an asteroid, a flying saucer, and a bullet. How are these objects related or connected to each other? In Asteroids, a ship can fire a bullet, a bullet can hit an asteroid and a flying saucer, and an asteroid and a flying saucer can hit the ship. Our relations diagram then looks as follows:
    The Asteroids relations diagram
    As you can see the objects are all pretty well interrelated. Because of this, we have to be careful of how we write the code, otherwise we will end up with a tightly coupled system. Lets take for example the ship firing a bullet. If the ship were to create a bullet object, keep track of its position, and then modify the asteroid when the bullet hits, our system would be very tightly coupled. Instead, the ship should create a bullet object, but not worry about it after that point. Another class would be responsible for keeping track of the bullet’s position as well as what happens when a bullet hits an asteroid. With an intermediary class in between our relationships, the diagram would look as follows:
    Read more: Quick Tip: The OOP Principle of Coupling

    Friday, November 2, 2012

    Quick Tip: The OOP Principle of Cohesion

    This entry is part 2 of 2 in the series Beginner's Guide to OOP
    In the first post of this series, we discussed why object-oriented programming (OOP) was helpful for game development, and learned how to identify objects, their states, and their behaviors. In this article, we’ll look at the specific OOP principle of cohesion and how it applies to games.
    Note: Although this tutorial is written using Java, you should be able to use the same techniques and concepts in almost any game development environment.

    What Is Cohesion?

    Cohesion is the principle of being or doing one thing well. In other words, cohesion means grouping together code that contributes to a single task.
    A great non-programming example of this principle was covered in one of the first Gamedevtuts+ articles which talked about the Covert Action Rule:
    Don’t try to do too many games in one package … Individually, those each could have been good games. Together, they fought with each other.
    The same rule applies to object-oriented programming. Each object should only have one responsibility. Every behavior of that object should only do one task. Any more than that and you’ll have a much harder time making changes to the code.

    Why Is It Helpful?

    Code that is organized by functionality and does only one task is said to have high cohesion. Highly cohesive code is reusable, simple, and easy to understand. It also creates objects that are small and focused [...]
    Read more: Quick Tip: The OOP Principle of Cohesion

    Thursday, November 1, 2012

    10 steps to becoming a better programmer

    Hi and welcome back to my blog!
    I wanted to cover 10 of the things I’ve learned over the years being a professional programmer that really helped me improve the quality of my code and my overall productivity.

    1. Never ever duplicate code

    Avoid duplicating code at all costs. If you have a common code segment used in a few different places, refactor it out into its own function. Code duplication causes confusion among your colleagues reading your code, it causes bugs down the line when the duplicated segment is fixed in one location and not the others and it bloats the size of your code-base and executable. With modern languages its become possible to get really good at this, for example here is a pattern that used to be hard to solve before delegates and lambdas came along:
    /// <summary>
    /// Some function with partially duplicated code
    /// </summary>
    void OriginalA()
    {
     DoThingsA();
     
     // unique code
     
     DoThingsB();
    }
     
    /// <summary>
    /// Another function with partially duplicated code
    /// </summary>
    void OriginalB()
    {
     DoThingsA();
     
     // unique code
     
     DoThingsB();
    }
    But now we can refactor the shared part of both functions and rewrite using a delegate:
    /// <summary>
    /// Encapsulate shared functionality
    /// </summary>
    /// <param name="action">User defined action</param>
    void UniqueWrapper(Action action)
    {
     DoThingsA();
     
     action();
     
     DoThingsB();
    }
     
    /// <summary>
    /// New implmentation of A
    /// </summary>
    void NewA()
    {
     UniqueWrapper(() =>
     {
      // unique code
     });
    }
     
    /// <summary>
    /// New implementation of B
    /// </summary>
    void NewB()
    {
     UniqueWrapper(() =>
     {
      // unique code
     });
    }

    2. Notice when you start distracting yourself

    When you find yourself flicking to facebook or twitter instead of working on a problem its often a sign that you need to take a short break. Go grab a coffee away from your desk and talk to your colleagues for 5 minutes or so. Even though this seems counter intuitive, you will be more productive in the long run.

    3. Don’t rush the solution out the door

    When under pressure to produce a solution to a problem, or to fix a bug, its very easy to get carried away and find yourself rushing, or even missing out your usual crucial testing cycle completely. This can often result in more problems and will make you look less professional in the eyes of your boss and colleagues.

    4. Test your finished code

    You know what your code is supposed to do, and you’ve likely tested that it works, but you really need to prove it. Analyse all the potential edge cases and make a test which confirms that your code performs as expected under all possible conditions. If there are parameters, send values outside of the expected range. Send null values. If you can, show your code to a colleague and ask them to break it. Unit testing is a formalised approach to this.

    5. Code review

    [...]
    Read more: 10 steps to becoming a better programmer

    Quick Tip: Intro to Object-Oriented Programming for Game Development

    This entry is part 1 of 1 in the series Beginner's Guide to OOP
    Welcome to a new series of Quick Tips on Object-Oriented Programming! We’ll be going over the principles of OOP and how they can be used to create organized code. In this first part, we’ll talk about what OOP is and why it’s helpful, with a few examples of how it could be used in game development.

    What Is Object-Oriented Programming?

    Object-oriented programming (OOP), in its most basic sense, is a programming style used to organize code. Video games can run anywhere from a few thousand lines of code (Cut the Rope has 15,000) to millions of lines of code long (Crysis has over a million). You can see why it’s so important to write code that can be easily modified and maintained.
    Programming styles, such as OOP, help to organize code in such a way that it becomes easier to maintain and modify. OOP helps organize code by organizing it into what are known as objects.
    Objects hold information about state and behavior:
    States are the characteristics of the object, or the words you would use to describe it, and usually take the form of is or has descriptors. A computer is either on or off, a chair has four legs, and you have a name.
    Behaviors are the things the object can do, or the actions the object can perform, and are usually verbs that end in ing. You are sitting, using a computer, and reading this article.

    Why Is It Helpful?

    As stated earlier, OOP is helpful because it helps create maintainable code – code that is understandable, adaptable, and extendable.
    It also helps create reusable code by following the DRY (Don’t Repeat Yourself) method: write the code once and then reuse it, rather than copying and pasting.
    The OOP way of thinking also lends itself well to directly translating real-world objects and interactions into code.

    How to Apply It

    I’ll list three different examples of how to apply OOP to video games. In later articles, we’ll look at how to code these examples, but for now we’ll just stick to learning to identify objects and their states and behaviors.

    Asteroids

    First, let’s imagine that we wanted to make the classic game Asteroids. To identify what the objects are in Asteroids, try describing it.
    Wikipedia describes Asteroids as follows:
    The objective of Asteroids is to score as many points as possible by destroying asteroids and flying saucers. The player controls a triangular-shaped ship that can rotate left and right, fire shots straight forward, and thrust forward. As the ship moves, momentum is not conserved – the ship eventually comes to a stop again when not thrusting.
    Think about what in this description could stand alone, or the things that are described that could have state and behavior. These become our objects.
    The objects for Asteroids are: a ship, an asteroid, a flying saucer, and a bullet (can’t forget those!). The cool thing about objects is that we normally describe things in terms of objects in everyday talk, so they usually reveal themselves through a description.
    The classic game of Asteroids
    The classic game of Asteroids
    Now that we have identified our objects, let’s define the state and behavior for one of them: the player’s ship. Think about what attributes describe the ship; these are its states. Then think about what the ship can do; these are its behaviors.
    A ship has states of:[...]
    Read more: Quick Tip: Intro to Object-Oriented Programming for Game Development

    Thursday, October 25, 2012

    Joe Willmott's Blog: Flash AS3 camera to follow your character

    For years I have used Sham Banghal's vCam in my flash games. It has always done what I needed of it and it was easy to use, however my latest game is a big one and as a result, it creates a decent amount of lag. I have looked into it and the lag was caused by all of the complex vector graphics. A way around this was to make a new camera that only rendered the graphics that are currently on-screen, saving the computer from having to render everything all of the time. I used scrollRect to create the simplest of cameras and would like to share it with anyone else looking for a very simple camera to use in their flash games! The only code required is this:
    import flash.events.Event; import flash.geom.Rectangle; stage.addEventListener(Event.ENTER_FRAME, cameraFollowCharacter); function cameraFollowCharacter(evt:Event){ root.scrollRect = new Rectangle(char.x - stage.stageWidth/2, char.y - stage.stageHeight/2, stage.stageWidth, stage.stageHeight); }
    As you can see from the code, you will also need a movie clip on-stage called "char" (or if it is called something else, change the bits that say "char" in the code. This is an incredibly simple camera but very effective as it completely removed the lag from my game! I have also attached an example .fla so you can see how it all works (saved in Flash CS4): Source file: Joe Willmott's ActionScript 3.0 Camera

    read more: Joe Willmott's Blog: Flash AS3 camera to follow your character

    Monday, October 22, 2012

    Picking a Color Palette for Your Game’s Artwork

    In this tutorial, we’ll look at what color palettes are, tools for choosing colors that go together, and the secret to picking a perfect color scheme for our games!

    An Introduction to Color Palettes

    The term color palette is used widely across many different industries of design. Its exact definition and interpretation varies slightly between industries, but for the purposes of game design we can simply refer to it as a predefined set of colors based on specific rules.
    Traditional color palettes generally consist of five colors within a specific scheme, but this is more of a guideline than a rule. In game design, color palettes can consist of any number of colors as long as they all follow your predefined set of rules.
    Before we delve deeper, consider whether you want to create your own color palette or find a ready-made scheme online. Either way, there are many tools that can help you out!

    Picking Palettes With Tools

    Color palettes can be created in virtually every program with a color picker, but why use MS Paint when there are so many great websites that can get the job done better?

    Kuler

    Adobe Kuler is one of my favorite tools for making a color palette, simply because it acts as an all-in-one tool.
    As well as being able to create your own color palette and pick colors from an image you find inspirational, you can also share your palettes and find ones created by others! This means there’s a never-ending supply of ready-made palettes for you to choose from.
    I recommend using this tool if you are looking for an in-depth experience or if you are looking to find user palettes created by others.

    Color Scheme Designer 3

    Another great tool for making color palettes is Color Scheme Designer 3. It has all the standard features you would expect from a color palette tool, and really shines in in its interface design!
    I found it effortlessly easy to jump in and make a color palette. I would recommend using this tool if you are looking for a simple experience.

    Color Blender

    The last tool I am going to suggest is Color Blender. Out of the three tools I would have to deem this tool the most interesting.
    Read more: Picking a Color Palette for Your Game’s Artwork

    Friday, October 19, 2012

    Stage3D compressed textures – Introducing the ATF SDK

    We introduced Stage3D last year and the momentum behind has never stopped growing but there is one area we did not give all the details. The ATF file format, it is mentioned here and there, so what's up with this? Some of you may have seen it in the documentation for Stage3D referred as the compressed texture file format, but we never shared any tools to create those famous ATF textures.
    Before we package the ATF tools with the AIR SDK, I am happy to share here in advance the ATF tools so that you guys can start leveraging the ATF format now!
    So what is it?
    First, let's start by talking about what compressed textures are.
    When doing GPU programming with any technology, you have two options for how you handle your textures. You can go compressed or uncompressed, very simple. So, what is the difference?
    1. When using uncompressed textures, a good old uncompressed file format like PNG is used and uploaded to the GPU.
    2. Because GPUs don't support such a file format natively, your texture is actually stored in CPU memory, when it could actually be stored on the GPU memory!
    3. Same thing applies for JPEG images, make no mistake, graphics chipsets don't know anything about JPEG which would also be decoded on CPU memory.
    4. Of course, each platform has different support for compressed textures depending on the hardware chipset being used.
    Now get ready for the fun! Here is below a little table to illustrate it:

    PlatformFormat
    ImgTech (iOS)PVRTC
    Qualcom (Android)ETC1
    Mali (Android)ETC1
    NVidia (Android)ETC1/DXT1/DXT5
    Android (PowerVR)PVRTC/ETC1
    WindowsDXT1/DXT5
    MacOSDXT1/DXT5


    Why ATF?
    As you can imagine, if you would develop a game targeting iOS, Android and desktop, you would need to supply your textures compressed to each format for each platform. Which would look like this:
    1. leaf.png encoded to DXT for Windows and MacOS
    2. leaf.png encoded to ETC1 or DXT for Android (Nvidia)
    3. leaf.png encoded to PVRTC for iOS (ImgTech)
    Of course it is a pain to provide all the different versions of the textures, detect at runtime which platform you are running on and upload the corresponding texture. Wouldn't it be cool if you could just rely on one single container, that would wrap all the textures for each platform and Flash Player or AIR would extract automatically the texture required depending on the platform? So here comes ATF.
    The ATF internals
    Really, think about the ATF format as a container for lossy images. Here is below a little figure showing very sinply the structure of a default compressed ATF file:
    Read more: Stage3D compressed textures – Introducing the ATF SDK

    Wednesday, October 17, 2012

    Project “Monocle”, profiling taken to the next level

    Adobe project "Monocle"Back in August, I posted a sneak peek video of project "Monocle" the next-generation profiling tool for ActionScript based content. Last week at GDC online, I gave a talk entitled "Changing the game" and demoed Monocle. Again, the feedback we had was unbelievable.
    I have been using Flash for 13 years now and I have seen lots of cool things happening in Flash. The introduction of AMF in Flash Player 6 (Flash Remoting) allowing fast and efficient RPC communications taking care of serialization for you (AMFPHP, anyone? Props to Patrick Mineault). Damn, that was nice. The introduction of BitmapData in Flash Player 8, which enabled so much expressiveness and Flash Player 9 with ActionScript 3 and a world of new possibilities. I think Monocle is the next big thing happening to Flash, it will just revolutionize the way we work with Flash Player and AIR.
    I got lots of emails and tweets from people asking to get on the prerelease. I am really excited to announce that all of you guys can now get access to "Monocle"!
    Please register, test Monocle, look for bugs, give us feedback! So what do you need to get started?
    1. Register here.
    2. Download Flash Builder 4.7 Game Development Beta 2 with Project Monocle Support.
    3. Compile your project and make sure the compiler option "Enable Detailed Telemetry" is enabled. Joseph Labrecque has posted great details here.
    4. If you are using Flash Pro or have existing SWFs you don't want to recompile. We provide a little python script to post process you SWF and make them profilable.
    I hope you guys will love it. Enjoy!
    Read more: Project “Monocle”, profiling taken to the next level

    Getting all the collection names with MongoDB and AS3

    At work I've been making on a quick tool to modify objects in MongoDB for our upcoming game. As I remembered reading about some AS3 drivers that allow you to directly connect to a Mongo database rather than need to use a server script, I decided to take a look. And immediately hit a roadblock.
    In the main libs I found; @s9tpepper's MongoAS3 lib, and JMCNet's full-mongo-flex-driver; there was no built-in way to get the collections in a database. If you've worked with Mongo before, you'll know that it's slightly important to know that.
    Both libs provided access to the Mongo runCommand() command, but no combination of keys seemed to do the job. Of course, you could always just keep a static Array of Strings, but where's the fun in that?
    Other languages and drivers usually have a function along the lines of getCollectionNames() and with the help of @dun4n's google-fu, we found out how to do it. Mmmm, smells like a hack!

    How it works

    So, for a database that looks like this: [...]
    Read more: Getting all the collection names with MongoDB and AS3

    Tuesday, October 16, 2012

    Create a Simple Asteroids Game Using Component-Based Entities

    In the previous tutorial, we created a bare-bones component-based Entity system. Now we’ll use this system to create a simple Asteroids game.

    Final Result Preview

    Here’s the simple Asteroids game we’ll be creating in this tutorial. It’s written using Flash and AS3, but the general concepts apply to most languages. The full source code is available on GitHub.

    Class Overview

    There are six classes:
    • AsteroidsGame, which extends the base game class and adds the logic specific to our space shoot-’em-up.
    • Ship, which is the thing you control.
    • Asteroid, which is the thing that you shoot at.
    • Bullet, which is the thing that you fire.
    • Gun, which creates those bullets.
    • EnemyShip, which is a wandering alien who’s just there to add a bit of variety to the game.
    Let’s go through these entity types one by one.

    The Ship Class

    We’ll start with the player’s ship: [...]

    Read more: Create a Simple Asteroids Game Using Component-Based Entities

    Monday, October 15, 2012

    TypeScript for ActionScript Developers

    Introduction

    The following covers what the TypeScript language is compared to ActionScript 1, 2, and 3 with as much context as possible and compares the syntax side by side. This article should help serve as a reference while you learn TypeScript. Also, these articles always help me learn while writing them and I like to have documentation I can refer to later.
    You cannot really talk about ActionScript without talking about the Flash Player internals just like you can’t really talk about JavaScript for web development without also talking about browser internals. Thus, I’ve tried my best to make what the ActionScript equivalents are in the JavaScript browser world.


    What is TypeScript?

    TypeScript is awesome. It’s this new language from Microsoft that enhances JavaScript. Like Robert Penner said, it’s basically ActionScript 2. You get strong-typing at compile time, but your code is compiled to ActionScript 1/JavaScript at runtime and has no enforcement of types. It has a variety of features, but the only two that really matters are the optional strong-typing and the ability to work with existing JavaScript libraries in a strongly-typed way. There are more, but the only ones ActionScript developers will really care about are:
    1. Optional Typing
    2. Classes
    3. Packages via Namespaces
    4. supports private
    5. modules
    6. everything compiles to JavaScript
    7. everything using classes/packages/modules compiles to RequireJS/AMD/CommonJS
    8. You can code in normal JavaScript; TypeScript is optional; you can mix and match
    9. all the TypeScript features for typing aren’t compiled into JavaScript (no enforcement) so it’s normal JavaScript that gets outputted
    Again, there are some other cool features such as overloading, interfaces, statics, follows ECMAScript 6, allows you to “use” ECMAScript 6 now, open source, blah blah blah, etc. I’m only focusing on that ones that matter.
    Here its creator, Anders Hejlsberg of Turbo Pascal, Delphi, and C# fame, does a 1 hour overview.



    Anders Hejlsberg

    Why TypeScript?

    If you want strong-typing in JavaScript, you’ll love TypeScript. Its typing is near identical to ActionScript 2 and 3.
    If you are a server-side developer who prefers to render the client side, think Google Closure annotations are sufficient, unit tests who’s sole purpose is to catch spelling errors & type casting errors, or believe “loose typing” is a great feature of JavaScript, peace the eff out.
    To quote Cliff Hall on a recent post defending languages that compile to JavaScript on Google+:
    They let you apply useful abstractions like classes, interfaces, inheritance, encapsulation, and OOP design patterns. This allows you to build larger systems in a more maintainable way, that is more team-friendly.
    Yep. For me, spelling mistakes and type issues that aren’t parsing related should be trivial issues, but instead have a major detrimental impact because of the current JavaScript development landscape and browser runtime issues (swallowed exceptions, misleading error messages, still not developer friendly compared to more mature runtimes, etc). TypeScript, at least in Visual Studio, will help alleviate the spelling & type casting issues, and if you do write unit tests, they’ll test more important things.

    How? TypeScript Compiler

    TypeScript the compiler is written in TypeScript. The compiler will output to JavaScript, optionally with header definitions. If you go to http://www.typescriptlang.org/ you can learn how to install and/or download what you need. I used the Node install. For Mac, this is nice because it makes it global so you can play in the Mac Terminal.
    npm install -g typescript
    If you want to compile some TypeScript to a JavaScript file in the same directory, on a command line, go: [...]
    Read more: TypeScript for ActionScript Developers

    Avoiding the Blob Antipattern: A Pragmatic Approach to Entity Composition

    Organising your game code into component-based entities, rather than relying only on class inheritance, is a popular approach in game development. In this tutorial, we’ll look at why you might do this, and set up a simple game engine using this technique.

    Introduction

    In this tutorial I’m going to explore component-based game entities, look at why you might want to use them, and suggest a pragmatic approach to dip your toe in the water.
    As it’s a story about code organisation and architecture, I’ll start by dropping in the usual “get out of jail” disclaimer: this is just one way of doing things, it’s not “the one way” or maybe even the best way, but it might work for you.  Personally, I like to find out about as many approaches as possible and then work out what suits me.

    Final Result Preview

    Throughout this two-part tutorial, we’ll create this Asteroids game. (The full source code is available on GitHub.) In this first part, we’ll focus on the core concepts and general game engine.

    What Problem Are We Solving?

    In a game like Asteroids, we might have a few basic types of on-screen “thing”: bullets, asteroids, player ship and enemy ship. We might want to represent these basic types as four separate classes, each containing all the code we need to draw, animate, move and control that object.
    While this will work, it might be better to follow the Don’t Repeat Yourself (DRY) principle and try to reuse some of the code between each class — after all, the code for moving and drawing a bullet is going to be very similar to, if not exactly the same as, the code to move and draw an asteroid or a ship.
    So we can refactor our rendering and movement functions into a base class that everything extends from. But Ship and EnemyShip also need to be able to shoot. At this point we could add the shoot function to the base class, creating a “Giant Blob” class that can do basically everything, and just make sure asteroids and bullets never call their shoot function.  This base class would soon get very large, swelling in size each time entities need to be able to do new things. This isn’t necessarily wrong, but I find smaller, more specialised classes to be easier to maintain.
    Alternatively, we can go down the root of deep inheritance and have something like EnemyShip extends Ship extends ShootingEntity extends Entity. Again this approach isn’t wrong, and will also work quite well, but as you add more types of Entities, you will find yourself constantly having to readjust the inheritance hierarchy to handle all the possible scenarios, and you can box yourself into a corner where a new type of Entity needs to have the functionality of two different base classes, requiring multiple inheritance (which most programming languages don’t offer).
    I have used the deep hierarchy approach many times myself, but I actually prefer the Giant Blob approach, as at least then all entities have a common interface and new entities can be added more easily (so what if all your trees have A* pathfinding?!)
    There is, however, a third way…

    Composition Over Inheritance

    If we think of the Asteroids problem in terms of things that objects might need to do, we might get a list like this: [...]
    Read more: Avoiding the Blob Antipattern: A Pragmatic Approach to Entity Composition

    Saturday, October 13, 2012

    SWF Versioning

    I am sure some of you guys have been confused in the past about the SWF versioning and which version to use when targeting Flash Player or AIR. Romil in the past posted a little table with the history. I decided to give it a little update that you can then bookmark. We will have this posted as an official reference on livedocs soon, but for now here it is!
    Flash Player versionAdobe AIR versionSWF version
    9.0.115.0NA9
    10.01.510
    10.12.010
    10.22.611
    10.32.712
    113.013
    11.13.114
    11.23.215
    11.33.316
    11.43.417
    11.53.518

    Read more: SWF Versioning

    Tuesday, October 9, 2012

    How to make a multi-player game – part 1

    Hello and welcome back to my blog!
    Its been a while since my last post, this is because I’ve been working on a multi-player game, called mmoAsteroids which you can play by clicking on the icon on the side-bar. This post is my attempt to crystallise the most important points I’ve learned during the making of this game and my other multi-player prototypes.

    Click here to view the video on YouTube.

    Introduction

    Firstly, it’s important to identify what I mean by multi-player and what implications that has. I’m talking about non-local multi-player, over the internet rather than at the same computer.
    Of course this means there needs to be some kind of way for the players to communicate with each other over the internet. I’ve chosen the server-client model rather than peer-to-peer, because that’s what my target platform client, Adobe Flash supports.

    Client side

    Why choose Flash? Because:
    • The install base is massive, even compared to HTML5
    • It’s a fixed platform, you don’t need to worry about different browsers, or different hardware
    • The Flash portals are an amazing resource for distributing games
    • There are very mature development environments available which support full debugging via the world class Visual Studio
    • It has support for TCP sockets built right in

    Server side

    Because I’m using the client-server model, I need to choose a platform for the server-side code.
    I’ve chosen node.js for this article, simply because it’s the fastest way to get a decently performing server set up and running with the least amount of code. Also, with your own server there are no limits on the number of clients you can support simultaneously, unlike ready made packages like player.io, or SmartFoxServer which limit you to a certain number of users until you sign up to their paid plan.
    Of course, they provide a lot more features for that money as well; it’s important to weigh up the costs and benefits of whatever platform you choose.

    Client-server model

    How do server-client based multi-player games work?

    Briefly, the client and server communicate by sending messages to one another. The client might send a message to the server saying he wants to move forwards. The server will receive the message and react accordingly. The server might send back a message saying that the player collected a power-up, or that someone else has joined the game.
    The client and server both maintain a copy of the game universe; the server has the master copy and then client has a (possibly partial) copy for local simulation and display purposes. The server has authority over all the important decisions in game, like players getting hit by bullets, or being killed, or levelling up. The client has authority about what keys are being pressed and other pieces of user input data.
    The reason for this separation of authority is to prevent cheating; although this is only really something you need to worry about once your game is big enough for hackers to invest time in finding cheats, it’s worth taking simple steps ahead of time to prevent the possibility of a hacked client from, for example, transmitting that he killed everyone in the world to the server, or something of that nature.
    Having the server be in authority simply prevents this from being possible.

    WoW recently suffered from hackers exploiting the system

    MMO? MO?

    It’s important to distinguish between the various types of multi-player game before we get into this too deeply, because the type can have a massive effect on the amount of code you need to write.
    Starting at its simplest form, I’m going to define an MO or Multi-player Online game as a multi-player game supporting as many players as possible running on one server (a physical computer located on the internet somewhere).
    An MMO is a Massively Multi-player Online game. There are many different forms this can take, but nearly all of them will involve more than one physical server working together to handle the huge load that ‘massively’ implies.
    How they work together will define how the game is to be designed; for example you might want your game universe to be shared by all players at the same time, as in Eve Online; this requires that several servers work together to form a large shard to share the load. Or you might want to instance your universe so that each individual server actually holds a unique copy of the universe and players in one universe cannot see players in another, like Realm of the Mad God. Or yet again, maybe you want to have some kind of combination of the two, where the universe is split up into realms and players cannot see players in other realms but they can travel between these realms, like in World of Warcraft [...]
    Read more: How to make a multi-player game – part 1