Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Saturday, March 30, 2013

Postmortem: Building Hard-shell Hockey with NME

NME postmortem
After finally creating my first game with NME and publishing it to the Android store, I thought I would share my experience so far.

To begin, I should explain what NME is and what it can do since I have only given it a brief mention before.
According to the official site NME is:
“The best way to build cross-platform 2D games or rich applications.”
“Using the innovative Haxe language compiler, NME deploys the same source code to C++, JavaScript and SWF bytecode without sacrificing reliability. As a result, NME provides fast hardware-accelerated performance for Windows, Mac, Linux, iOS, Android and BlackBerry, while also supporting Flash Player and HTML5. NME mirrors the traditional Flash API, so developers can leverage their existing experience to target new platforms, with better results.”
So far I have to say that statement is pretty accurate. But what about other similar tools that exist such as Corona, Unity, libGDX, Marmalade etc and why did I choose NME over them?
One of the more obvious reasons why I chose NME was my past experience with the Flash API which certainly lowered the learning curve. However, it was the fact that NME is the only truly free solution that won me over. LibGDX came closest out of the other choices I mentioned but it still required a $400 license fee for iOS. Having witnessed the HTML5 vs. Flash war I feel it is much safer to bet on technologies that are free and open source.
Of course NME is not without its flaws. Bugs and issues with various platforms do exist although fortunately they are few and far between. Additionally the community is not huge and so one can’t expect the same level of documentation and tutorials. That being said, I have really noticed over the past year how polished NME is becoming and how the community is growing which is fantastic to see. I am very much looking forward to seeing shader support for mobiles being added too.
So, having decided upon NME as the tool to use I realised I needed a game engine. When I first started there was not much choice so I decided to port over an engine I had made in Flash. As of now, ports of the popular Flash game engines like HaxeFlixel and HaxePunk exist. Regardless, software architecture and game engine design has interested me so I don’t feel that I wasted my time by creating my own and so far am very pleased with my results.
That being said, I did greatly underestimate how much work was involved in getting the game engine working properly.
The first challenge was getting the hang of rendering in a different way to what I had been accustomed to with Flash. In Flash, I would mainly use the DisplayList and at times blitting. This works great in web browsers but less so on mobile devices. Blitting actually causes the mobile to render via software which kills performance. The DisplayList, whilst better (it is GPU accelerated), is still not the optimum way of rendering. The best way when considering performance on mobiles is drawTiles and drawTriangles respectively. This means using a third party tool to export a swf into a tilesheet to render via drawTiles.
After understanding and implementing drawTiles, my next problem was displaying Android ads. I managed to find a library that used NME extensions to achieve this except that it did not work out of the box. Eventually I tracked down another person who had managed to get it up and running and they gave me a lot of tips. In the end this required delving into some of the NME framework and modifying the Java code template. It was after this that I decided to just focus on developing for Android as I did not want to waste a similar amount of time getting iOS ads working (although I believe they work out of the box on that platform) [...]

Read more: Postmortem: Building Hard-shell Hockey with NME

Tuesday, March 12, 2013

How to Speed Up A* Pathfinding With the Jump Point Search Algorithm

Pathfinding is ubiquitous in games. So it’s important to understand the implications which are present when using algorithms such as A*. In this tutorial we’re going to cover a relatively new method for searching grid based worlds: Jump Point Search, which can speed up A* by orders of magnitude. Note: Although this tutorial is written using AS3 and Flash, you should be able to use the same techniques and concepts in almost any game development environment. This implementation is based on the original paper and article on JPS found here: Jump Point Search. The Lua based implementation, Jumper, was used for help with some parts of the implementation.

Jump Point Search Demo

Click the SWF to give it focus, then move your mouse over non-blocking areas of the map to have the NPCs try to get to it. Hit Space to switch between A*, Jump Point Search, and both. No Flash? Check out the YouTube video instead:

Setup

The demo implementation above uses AS3 and Flash with the Starling Framework for GPU accelerated rendering and the polygonal-ds library for data structures.

Pathfinding

Pathfinding is often used in video games and you are sure to bump into it at some point during your game development career. Its primary use is to give intelligent looking movement behavior to artificial entities (NPCs), to avoid them bumping into things (often). In some games the player avatar is also subject to pathfinding (strategy games, many third person RPGs and adventure games). So you might assume that the problem of pathfinding is solved, but unfortunately that’s not the case; there is no silver bullet which you can use and just be done with it. And even in big AAA games, you will still find funny things like this:
There may not be a silver bullet, but there is a bullet: the A* (A star) algorithm. In this tutorial we are going to see a brief overview of A* and how to speed it up using another algorithm, Jump Point Search. First we need a way to represent our game world in a way that a pathfinding algorithm can use it.

World Representations

One of the most important things to consider when thinking about pathfinding for your game is world representation. How is the data of the passable areas and obstacles organized with programming structures in memory? The simplest representation you can use is a grid-based structure, where path nodes are organized in a grid and can be represented by a 2D array. We are going to use this representation in this tutorial. Specifically it will be an eight-way grid representation: allowing movement in straight and diagonal directions.
The black pixels in the image represent the blocking cells.
Your requirements might be different, so this structure might not suit you. Good thing is that with some processing (usually done offline) you can change pathfinding representations to other formats. Alternatives to grid based approach would include things like polygon (obstacles represented by polygons) or navigation meshes (navigation areas represented by polygons); these can represent the same data with fewer nodes. Another data that can be stored in map representation are costs: how much it costs to travel from one node to another. This can be used for the AI to determine the path that, for example, prefers roads over regular terrain (making the cost of the road less than the terrain). Jump Point Search is specifically designed for eight-way grid based map representation so we’ll use that. Also, in its vanilla form it doesn’t support weighted maps. (In the final section I’ll discuss a possible way to remedy this.)

A* Pathfinding Refresher

Now we have a world representation let’s take a quick look at implementing A*. It’s a weighted graph search algorithm which uses heuristics (little “hints”) of how to best search the area from the start node to the end node. I highly recommend that you check out this visualization of pathfinding algorithms: PathFinding.js – visual. Playing with it can boost your intuition of what the algorithm is actually doing – plus it’s fun! For pathfinding using A* in rectangular grids we do the following:
1. Find node closest to your position and declare it start node and put it on 
   the open list. 
2. While there are nodes in the open list:
   3. Pick the node from the open list having the smallest F score. Put it on 
      the closed list (you don't want to consider it again).
   4. For each neighbor (adjacent cell) which isn't in the closed list:
      5. Set its parent to current node.
      6. Calculate G score (distance from starting node to this neighbor) and 
         add it to the open list
      7. Calculate F score by adding heuristics to the G value.

  • A* Pathfinding for Beginners (In-depth article that explains F and G scores among other things.)

  • Heuristics is essentially making a guess at the chance that the node being evaluated will lead to the goal. Heuristics can make a big difference in efficiency of pathfinding algorithms as they tend to limit the number of nodes that need to be visited. We are going to use Manhattan distance for our purposes (meaning that nodes closer to the goal will have a smaller number):
    private function manhattanDistance(start:Node, end:Node):int {
        return Math.abs(end.x - start.x) + Math.abs(end.y - start.y);
    }
    
    This is more or less it. We stop the algorithm when we find the goal node, and then track back using parent variable of node to construct the path. Search algorithms can be used for other things as well. A* is a general weighted graph search algorithm, and can be used on any such graph. This can cover other fields in AI, such as finding the optimal steps to achieve certain objective: throw a bomb or run for shelter and try to sneak behind an enemy? In game development we need to do things fast, when updating our games at 60 frames per second every millisecond counts. Even though A* performs reasonably well for some uses there exists the need to make it faster or use less memory.

    Optimizations

    Choosing the representation is the first thing that will have an impact on pathfinding performance and your choice of pathfinding algorithm. The size of the graph that is being searched will have a big correlation on how your pathfinding performs (which makes sense; it’s easier to find your way in your room than in a big city). Then you would consider higher level optimizations which usually involve clustering data to smaller regions and then searching those while later refining paths in travelled smaller regions. For example, if you want to go to a restaurant in a neighboring city, you first consider how you get from your city to that one, and once you are in that city you limit your “searching” to the area where the restaurant is located, ignoring the rest. This would include things like swamps, dead end elimination and HPA*. On the lowest level you have to do the searching. You chose your data representation and possible abstractions and then plug them in an algorithm that will pick out nodes, travel here and there searching for the goal. These algorithms are usually based on the A* searching algorithm with possible modifications. In simpler cases you can get away with using straight A* which offers you the simplicity. I’ve provided a grid based implementation in the source download.

    Jump Point Search

    [...] Read more: How to Speed Up A* Pathfinding With the Jump Point Search Algorithm

    Thursday, February 28, 2013

    Making it in Indie Games: Starter Guide

    image Every now and then someone will ask me for advice on making it as a professional indie game developer. First, it’s a huge honor to be asked that. So I want to say “Thank you!” Second… damn, if I really want to help out it’s a serious endeavor. Of course, I could always say “Give it your best! Work hard! Be true to yourself!” and it wouldn’t be a terrible reply… just not a terribly useful one, either. So here it is. Here is what I’m going to link when that rare situation arises again, because it’s too much work to write it up more than once! This is advice that I feel may actually be practical to someone who is just starting out as an indie game developer. Hope it helps! INDIEPENDENT So yeah, what does being “indie” even mean? Is “indie” short for independent? Is this game “indie”? Is “indie” a genre? IT’S CONFUSING - WHY DO WE NEED THE WORD “INDIE” AT ALL. To answer the last question, I offer the following scenarios. Scenario 1: a person is looking to make games, and perhaps start their own studio. They type “game development” into a search engine. The results, to say the least, are underwhelming. Dry. Academic. Programming-centric. (Try it yourself and see.) Scenario 2: the person instead types “indie games” into a search engine. Instead of pages upon pages of conferences, bachelor’s degrees, and programming tools, that person is met instead with pages upon pages of games to play and vibrant communities filled with people who are doing exactly what he or she wants to be doing. Some of them went to school, but many did not. A wealth of different ideas and tools are used. There are even documentaries about making games! It’s not just something where you get a degree and wait in line for a job. You can start making games RIGHT NOW. The word “indie” is more than just a way to describe a type of developmental process… like any label, it actually provides an avenue for people to explore that process and then flourish within it. It has a real purpose. It serves real lessons on game creation and entrepreneurialism. It offers real motivation! Of course, it can be irritating to see the term misused, or become a vehicle for pretentiousness and arrogance. Like any label, “indie” also breeds a certain amount dogmatism, croneyism, and other -isms. But the net result is really worth something. As someone who once gave up on professional game-making because I thought it meant a 9-to-5, I can tell you that it’s genuinely valuable. As for what games are “truly” indie, we’ll never fully agree, and that’s probably for the best. But I can tell you the criteria I’ve devised for The Independent Gaming Source to determine whether a game is fit for coverage: 1. “Independent”, as in no publisher. 2. Small studio (roughly 20 members or less). I choose that definition because it’s the most useful one. Someone who is looking to become an “indie” game developer is interested in what is possible under those constraints and how those types of studios operate. It excludes companies like Valve and Double Fine, which are certainly independent but too large to be “indie”. It also excludes “feels indie”-type games that are not self-published. Under that definition you still run into gray areas, but hey, just because we don’t know when “red” turns into “purple” doesn’t mean the words aren’t useful. Just think about someone who wants to make a game with a small team and self-publish it… what should they type into Google for inspiration, advice, community, etc.? “Indie” is still as good a word as any, in my opinion. So, should I go to school to learn how to make games? The most important thing to know about video game development and schooling is that no one, whether it’s an indie studio or big company, cares about degrees. How could it, when some of its most prominent members are drop-outs or never-beens? John Carmack, Cliff Bleszinski, Jonathan Blow, and Team Meat are all prominent members of this club. A degree is a piece of paper that says you can do something in theory - game developers want to know that you have enough passion to do real work, regardless of whether you’re being graded on it. And if you’re thinking of going indie, it won’t matter what other people think - you’ll simply need that passion to succeed or else you won’t. You’re the only one holding the door open in that case. This isn’t to dissuade you from going to college, per se (I studied computer science in college, and while it was far from a perfect experience, I also gained a lot from both the curriculum and the friends I made there). The point is make something - games, mods, art, and music. If school helps you with that, great. If it doesn’t, then you need to rethink how you’re spending your most valuable resources: time and money (both of which can be exorbitant costs for schooling). If I go to school, what should I study? At a regular university, I would suggest majoring in computer science, even if you “just want to be a designer”. The design of games is very much tied to how they are made. At an art school, illustration, concept art, and 3d modeling courses are probably the most useful for games. At a game school, they will hopefully try to involve you in all aspects of game creation, from programming to design. I would stay far away from design-only schools or curricula - those are either scams or are better suited to academia than actual game-making. Also, it’s worth finding out whether or not the school owns what you make while you’re a student there. See also: Jonathan Blow - How to Program Independent Games (read the comments as well as watch the video) Okay, you say make something. How do I start? My best advice for those starting out is not to get ahead of themselves. It’s easy to start worrying about tools, teams, platforms, deals, marketing, awards, and whatever else before you’ve even gotten a sprite moving around the screen. Those stars in your eyes will blind you. They’ll freeze you up. You need to be actively making games all the time. If we were talking about painting, I’d tell you to pick up a painting kit and a sketchpad at your local art store ASAP and just have at it. You’d proceed to put absolute crap down on the pad and get frustrated. But it’d also be kind of fun - so you’d keep doing it. Along the way you’d read some theory and study other people’s work. With good taste and under a critical eye, you would keep doing that until the day you painted something good. We’re talking about games, though. I recommend Game Maker and Unity as two all-purpose game-making suites. They both have a good balance of power versus ease-of-use; they’re both affordable or have free demos, and they both have a wealth of tutorials and plug-ins online. Both are used by professional developers (Unity in particular). Grab one of those and start running through the tutorials. When you run into trouble, ask for help. Give help back when you begin figuring things out. Get active in a game-making community. But above all else, keep making games. It’s the only way to truly answer all of those questions in your head right now. Also, watch this: LASTLY, MY TOP 10 TIPS
    Read more: Making it in Indie Games: Starter Guide

    Monday, December 17, 2012

    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

    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

    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

    Tuesday, June 5, 2012

    Easily handle right mouse button in Flash movies

    Detecting and handling right mouse clicks in Flash has always been a pain. I blogged about it four years ago in the post preventing the right mouse cheat in your Flash games where I explained a dirty trick to trigger right mouse button with As2, and guess what? Things got even worse with As3, although I found a workaround preventing players to cheat in my Flash game Stringy. Finally, the pain is over. With Flash Player 11.2, you can finally do everything you want in Flash movies, without exporting them for Air. Look at this movie: You can use left mouse button to drag boxes, and right mouse button to destroy them. Also notice, the default right click menu does not appear. Look at the source code: [...]
    Read more: Easily handle right mouse button in Flash movies

    Thursday, May 31, 2012

    Tune your AIR for iOS development skills: compile, install and profile like a pro

    The purpose of this article is to share with you some tips, that might help you to speed up and improve the process of building AIR for iOS apps. These are the practices that I use every day and hopefully some of you will find them useful.

    Installing an app (*.IPA) on your iOS device

    As a developer you want to save time, being able to install apps on the device quickly and see the results is the most important thing. Using iTunes for app install has some drawbacks: you will have to synchronize it and it takes lot of time and you cannot install apps on devices that are not synchronized with your iTunes (like friend’s iPad).
    There are three ways I find quicker:
    iPhone Configuration Utility
    Available for Windows and Mac from Apple, this smart piece of software helps you to manage apps installed on your devices. Drag and drop IPA file to Applications and then choose a device and install or uninstall specific apps. Works for iPad as well. You can also manage configuration and provisioning profiles.
    Download for Windows | Download for Mac
    iPhone Configuration Utility
    Xcode Organizer
    Read more: Tune your AIR for iOS development skills: compile, install and profile like a pro

    Wednesday, May 2, 2012

    Gaming Your Way: So how does the NPC AI in Outpost:Swarm work ?

    Now Outpost:Swarm is live I thought it may be an idea to explain how I did your in-game partners AI. If you've ever read up on Boids you'll know they have 3 simple rules, Separation Alignment Cohesion And all the examples you'll see are bird like objects flying around, maybe towards your mouse pointer, maybe avoiding obstacles. All seems simple enough. Adding them to a real game however quite a bit trickier. For separation we have to ensure the NPC is avoiding both the player and all the baddies. Firstly we find the distance to the players sprite using a simple distance=dx*dx + dy*dy; Like you would in your usual circle to circle tests. If we're too close then we need to repel the NPC from the player, via: tmpPoint1.x+=dx+dx; tmpPoint1.y+=dy+dy; Where tmpPoint1 is just a new Point(0,0); That's part 1 of the test done, the second is checking against all the baddies, and there can be a load at any one time. What I did was use a flip flop, every even frame we get a list of all the possible neighbours ( Baddies which are close enough to care about, if they're on the other side of the screen then we can skip them ), every odd frame we do exactly the same distance check as we did above. Finally we divide our Point value, tmpPoint1.x/=speedDivisor; tmpPoint1.y/=speedDivisor; ( private var speedDivisor:Number=20; ) This keeps the values within a respectable range so we don't move too fast. Read more: Gaming Your Way: So how does the NPC AI in Outpost:Swarm work ?

    Friday, March 23, 2012

    How to Build a Python Bot That Can Play Web Games

    In this tutorial we’ll explore the ins and outs of building a Computer Vision-based game bot in Python, which will be able to to play the popular Flash game Sushi Go Round. You can use the techniques taught in this tutorial to create bots for automatically testing your own web games.

    Final Result Preview

    Let’s take a look at the final result we will be working towards:

    Prerequisites

    This tutorial, and all the code within it, requires that a few additional Python libraries be installed. They provide a nice Python wrapping to a bunch of low-level C code which greatly eases the process and speed of bot scripting.
    Some of the code and libraries are Windows-specific. There may be Mac or Linux equivalents, but we won’t be covering them in this tutorial.
    You’ll need to download and install the following libraries:
    • The Python Imaging Library
    • Numpy
    • PyWin
    • All of the above have self installers; Running them will automatically install the modules into your \lib\site-packages directory and, in theory, adjust your pythonPath accordingly. However in practice this doesn’t always happen. Should you begin receiving any Import Error messages after installation, you’ll probably need to manually adjust your Environment Variables. More information on adjusting Path Variables may be found here.
    The final tool we’ll need is a decent paint program. I suggest Paint.NET as an excellent free option, but any program with rulers that display their measurements in pixels can be used.
    We’ll use a few games as examples along the way

    Introduction

    This tutorial is written to gave a basic introduction to the process of building bots that play browser-based games. The approach we’re going to take is likely slightly different than what most would expect when they think of a bot. Rather than making a program that sits between the client and server injecting code (like a Quake or C/S bot), our bot will sit purely on the ‘outside’. We’ll rely on Computer Vision-esque techniques and Windows API calls to gather needed information and generate movement.
    With this approach we lose a bit of refined detail and control, but make up for it in shortened dev time and ease of use. Automating a specific game function can be done in a few short lines of code, and a full-fledged, start-to-finish bot (for a simple game) can be cranked out in a few hours.
    The joys of this fast approach are such that once you get familiar with what the computer can easily ‘see’, you’ll begin to view games slightly differently. A good example is found in puzzle games. A common construct involves exploiting human speed limitations to force you into a less than optimal solution. It’s fun (and pretty easy) to ‘break’ these games by scripting in movements that could never be accomplished by a human.
    These bots are also very useful for testing simple games – unlike a human, a bot won’t get bored playing the same scenario over and over again.
    Source code for all of the tutorial examples, as well as for one of the completed example bots, may be found here.
    Have fun!

    Step 1: Create a New Python Project

    In a new folder, right-click and select New > Text Document [...]
    Read more: How to Build a Python Bot That Can Play Web Games

    Monday, March 19, 2012

    Compile Time Only

    The const and final keywords only apply at compile time. Despite having written about const and final before, readers frequently ask me about these two keywords. Today’s article will answer the question and definitively show that these keywords only apply at compile time: not runtime. Let’s start with const. Consider this simple class: class MathConstants [...]

    Read more: Compile Time Only

    Tuesday, March 13, 2012

    fastSort, faster is better!

    Today, Jackson Dunstan posted about how to use a profiler to get better performance in flash.
    For this post he decided to show how to use TheMiner… awesome!
    In this post he’s profiling two sorting method: native vector. sort, and Skyboy’s fastSort code.
    At first I was impressed by the result of Skyboy. Then I realized two things.
    First, The flash native sort REALY don’t like Number.infinity, negative infinity.
    So when sorting and vector. with these values inside, it’s getting a LOT slower.
    Where a standard vector could take 100ms to sort, one with infinity values in it can take up to 2000ms!!
    The other thing is fastSort is using void (*) pointer everywhere.
    So if we go back a few day to my previous (epic) article , we know that this is a really bad thing when casting from void to Number.
    It’s allocating a LOT of memory. (5Mo/Sort on 50K elements)
    So I decided to add a few hundreds lines to this class with already a lot of it (fastSort)
    I added a specific sorting method for int, uint and Number to manage only typed values.
    The result is quite amazing!
    Native Vector Sort : 100 ms + 400Ko allocation
    UnOptimized fastSort : 400 ms + 5Mo allocation
    New Optimized fastSort : 20ms + zero allocation
    Finaly, just before giving you the code, I want to invite you on a new little forum that focus on Performances, optimization, debugging and multiple other flash hardcore subjects.
    Many of the most hardcore dev and blogger I know are already in or are going to join soon, so please be part of this and enjoy posting refreshing and brain teasing content!
    The Hardcore flash forum
    And now.. the way too many lines of code part: [...]

    Read more: fastSort, faster is better!

    Sunday, February 26, 2012

    Epic Flash memory leak track down

    Have you ever had a memory instantiation problem that was impossible to track down? Here is a post that might help you with that kind of thing!

    Beware! This post is very long… but VERY instructive! If you want to learn some internal mechanism of Flash, I strongly suggest you read it from top to bottom without skipping parts!:)

    The Context

    Yesterday I was helping Luca (creator of Nape physic engine, made with haXe) to find what seemed to be a big memory leak. There was a couple framework used so it could be directly from Nape… or from Starling… or from debug tool running… or from a port error from haXe…

    Memory profiling

    So I though it was going to be simple


    I got TheMiner running and started profiling. It was pretty easy to find a LOT of memory allocation coming from Starling. The SWC version available is over 4 months old and back then there was a lot of useless instantiation coming from TouchProcessor.as
    If you use Starling, I suggest you build from sources as these instantiation are gone now.
    There are a couple left but no big deal.

    We also saw that Nape was using a LOT of anonymous function call and some try catch. This create what’s called activation-object. And there was a lot of these. So by removing anon-calls and try catch we were able to remove a lot of instanciation.

    And After removing the debugging tools, It was clear it was coming from haXe or Nape.

    But even when recording all samples allocated by the VM I could not find the damn allocation. (we are talking of more than 1Mo per sec)

    Then I wrote a Scala script to try to identify samples that could have been missed, but that didn’t help me much since that was only an override of constructor and constructorProp avm opcodes.

    Simplifying the context

    So I decided to look a bit further into the bytecode and found something very interesting.

    After simplifying the problem multiple time, I got this very simple code to demonstrate the bug.
    Because Nape has that very nice abstraction layer, it can support both standard DisplayObject as well as Starling 3D DisplayObject.

    The leak happens when Nape try to set the DisplayObject properties like .x, .y, .rotation, etc.
    Let’s create a fake DisplayObject class and name it DO [...]

    Read more: Epic Flash memory leak track down

    Thursday, February 23, 2012

    Building An Elevator in Box2D

    Introduction

    It took me 4 days to build an Elevator via Box2D in Corona SDK. I wrote the actual code and API for it in about 30 minutes. Getting the physics to work proved way more challenging than I anticipated. I’m still learning the ins and outs of Box2D as it relates to game development, so wanted to report on how I went about it and what I learned.

    The following article talks about how I’m using Box2D in my game, the 4 approaches I took to building an elevator, and what I eventually decided upon.

    Please keep in mind some of the things below are related to Corona SDK’s implementation of Box2D. Thus, some of the issues and compensation measures I took may not need to be done, nor happen, in other implementations and platforms.

    Why An Elevator?

    Elevators provide an interesting transition in both games and movies. They also provide easier ways for game developers to unload and load a level, provide a rest for the player, and/or make it easy to provide cut scene dialogue to prepare for the player for an upcoming part. In a lot of horror movies, they actually are the focal point of a lot of scary scenes such as Resident Evil, and also provide a perfect setting for comedic relief such as such as Spiderman 2 and Deep Rising (good ole Ipanema).

    One of my favorite easter eggs was from Max Payne was in an elevator. You walk into a shoddy NYC apartment building elevator alone, with the notorious off-kilter 3rd person camera. Combined with the absurd brightness in the elevator’s interior amongst a very noir game, the tell tale “elevator muzak” is playing. If you shoot the overhead speaker, Max utters a smirk filled, 2nd word annunciated “Thank you!“.

    Romance, fear, death. In such a confined space clearly only meant for short periods of stay, elevators can force us to view the human condition ever more clearly. Many writers play up the claustrophobia aspect, the lack of control as a metaphor for life taking us where it wills to, or preying on our fear of the unknown when you hear bad things just outside the lift walls.

    It also helps players in games get from one floor to another in a controlled manner. Kind of like they do in the real world.

    How Does Mine Need to Work?

    A game I’m building requires that a character inside a building go up a floor in the building he is in. It’s based on a Brooklyn apartment building that has 13 floors with 12 ft ceilings. The character is on the 12th floor and needs to use the standard elevator. It has a call switch on the outside. You press a button and the elevator will arrive at the floor the button was pressed. You can optionally walk into the elevator and press the up or down buttons for the same effect. The elevator does not move on it’s own, only when a button is pressed. It currently only operates on 2 floors.

    Simple, right? Code wise, it was. Here’s the Lua class on Github. The only thing to really note is the goUp, goDown, and tick functions. The goUp and goDown simply set flags so the elevator knows where to go. The tick function handles the actual movement via the game loop. Distance joints, which I’ll cover in a minute, are not powered by motors, so I just increment or decrement the length to move it up or down.

    Brief On Box2D

    Read more: Building An Elevator in Box2D

    Friday, February 3, 2012

    HOWTO: Join multiple SWF files into one with AIR for iOS

    A while back, I promised to write some of the backstage tips that made it possible for Machinarium (1 GB sources!, 28 SWFs!) to run on an iPad with AIR, which requires only a single SWF.

    One of the issues you run into is how to join/concatenate 28 SWFs into single SWF. I wrote an article about using SWC libraries for that here Compiling big Flash/AIR projects with lot of SWFs for iOS. This sometimes works, but very often the workflow is more complex and you want to keep the same SWF files for Android and iOS and use them at least in a bit similar way. On Android you can however load SWF files at the runtime and this is very effective for the memory usage. On iOS you have to watch this, especially when you have everything in a single SWF. So, ideally you place all assets into separate files and load them and dispose them on-demand. But that’s more of a general problem you should keep in mind – every asset that doesn’t contain AS3 (pictures, videos, music), put aside. But back to the topic.

    Now comes the magic by David ‘Oldes’ Oliva (the lead developer of Machinarium) from Amanita Design, who made it all possible and wrote a script which can be used for joining SWFs together.

    Note: This solution allows you to use multiple SWF files containing AS3 script and logic in each of them, not only for assets. That’s why it’s so powerful.

    *prerequisite: you’ll need to understand how to work with the command-line on Mac or Windows.

    Steps:

    1) Prepare SWFs like you were using them the standard way, but instead of loading them dynamically via the Loader class, SWFLoader or a similar mechanism, each SWF has to be Class (or contain at least one, can contain more), which you can instantiate. That’s because once you join all SWFs together, you will be instantiating it’s contents, not loading.

    2) Download the samples package rswf-join-example.7z (for unzipping use 7-zip compatible tool)

    3) Download the REBOL script view environment http://www.rebol.com/download-view.html

    Using the tool:

    4) Navigate to the samples folder. There are three scripts that you might want adjust to fit your workflow:

    compile-and-run.r
    - this is the rebol script that does part of the job and runs Game.bat

    Game.bat
    - here you want to adjust the path to your Flex/AIR SDK so it points to the adl command

    Red more: HOWTO: Join multiple SWF files into one with AIR for iOS

    Sunday, January 15, 2012

    Nape and Starling together? It’s possible!

    Hey, friends!

    Somebody of you already tried fastest 2D flash physics engine Nape with a GPU 2D rendering framework Starling together and noticed that Body.graphic property is class of flash.display.DisplayObject and it can’t be assigned to the starling.display.DisplayObject instance.

    So, some of you just used Box2D, some of you controlled Starling DisplayObjects manually, maybe some did what I did, but keep it away from public, but I like Body.graphic property – it’s really useful and I wish all as3 developers can easily use fastest 2d physics engine with 2D GPU rendering engine.

    Today I’m glad to present you modified Nape FP 10+ swcs (release and debug) of the Milestone 7.2 “r3″ (maybe not fully) compatible with the Starling.

    I just replaced Body.graphic flash.display.DisplayObject class by the Dynamic class (* in as3) and removed Body.graphic.rotation radians to degrees conversion to make it compatible with Starling in my case.
    Now I can use Nape as usual, with usual DisplayObjects, it’s really cool!
    Yes, there are possible some more compatibility issues, but this changes was enough in my case and Nape worked with the Starling DisplayObjects fine.

    Feel free to download and use this swcs with Starling Framework!
    debug swc
    release swc

    I like a challenge with caxe and flib compiling on Windows in the MinGW I faced while recompiling swc, it was fun!
    To get the working swcs on Windows, you should

    Read more: Nape and Starling together? It’s possible!