Showing posts with label software design. Show all posts
Showing posts with label software design. Show all posts

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

Monday, October 15, 2012

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, August 4, 2012

Games And Entity Systems

Last week I delved into Ash – an ActionScript Entity System by Richard Lord: https://github.com/richardlord/Ash I built this little shooter: http://www.boyblack.net/proto/hunted/TopDown.html (note: something is broken with Stage3D and Chrome on Mac OSX, at least on my machine. Try it in Firefox or Safari if it doesn’t work for you, and drop me a comment).

What’s That Then?

Entity Systems offer an approach to object design that fits well with games, where requirements and behaviours need to be tweaked or swapped out constantly. Traditional object oriented design falls over a little bit in that environment. In an application (as opposed to a game), objects and collaborations are usually clearly defined and do not change after startup. Objects play specific roles, and for the most part, those roles don’t change much. In a game, however, the behaviours of “actors” within the system can change significantly during gameplay. An enemy may be stunned, for a period, losing the ability to attack. The hero may pick up a weapon, become invincible, or learn to fly. Time may slow down, speed up, or change direction. Class inheritance is obviously not a good choice here (it rarely is anyway). But actually, many object oriented design approaches are at odds with these requirements.

Ash

Ash breaks things down into Components, Entities, Nodes and Systems.

Components

Components are simple value objects: [...]
Read more: Games And Entity Systems

Friday, November 4, 2011

Design Tactics – Select Single

The other day I was coding a particular UI implementation and realized that I had coded the same thing in multiple languages multiple times. I knew exactly how I was going to go about it and did what I usually do and, as usual, it worked just right. I started wondering how many examples like that exist, and that it would be good to occasionally document them, if not for my own sake, then for the sake of others.

These things aren’t necessarily so broad in scope that I’d call them design patterns. I might call them a design strategy, but that still has the connotation of being broad in scope, and could be confused with the strategy pattern. So I thought of naming them design tactics. Kind of like hand-to-hand combat with your code.

The first one, and the one that sparked my interest in the subject, I call the Select Single Tactic. I’m sure you’ve done this plenty of times yourself. It’s basically the functionality of a radio button, a list, a menu or other navigation. You have a number of items, of which only one can be selected. When the user selects one, it usually changes its state to show that it is selected, and the other associated items will change their state as needed to show that they are unselected.

The most common scenario is that the user will click on an item to select it, so we’ll go with that idea. A common first start is to code the item so that it responds to the click directly, changing its state to selected. See the following snippet, kept in pseudocode as it can apply to just about any language:

// constructor
Item() {
        this.addEventListener(click, this.onClick);
}

void onClick() {
        this.setSelected(true);
}

Here, the item responds to its own click by changing its visual state to show that it has been selected. In some cases, this is fine, but there’s probably a more elegant way. However, we’ll leave it like this for now [...]

Read more: Design Tactics – Select Single

Tuesday, October 11, 2011

Five Lies They Tell You in Software

The following are 5 things I wish someone had told me back in January of 2000.

  1. The User is the Most Important Thing
  2. If You Don’t Evolve, You’ll Die
  3. Using OOP, Design Patterns, Frameworks, and TDD with the Right IDE Will Solve All Your Problems
  4. You Can Code Something Right The First Time
  5. There is a Clearly Defined Career Path in Programming

1. The User is the Most Important Thing

Making money is the most important thing.

Anyone who says the user is the most important thing hasn’t been in enterprise software, is endeavoring to fight against bad software, doesn’t run a business, or is talking about Open Source.

If you want good software, yes, you should pay attention to the user. Doing informal user testing, engaging with real users/customers while developing the software should be done. Investing in design early, heavily, and constantly are great ways to lead to building software that has a great user experience that people want to use.

That doesn’t implicitly make software magically sell itself. For mid-size to larger companies, those using the software aren’t the ones who pay for it. Often they’ll never use it, nor see it. They’ll be looking for the right marketing messages, and/or validation that it solves key problems THEY are concerned about. They are hoping to solve what they perceive as important problems to their business, not those actually using the software in their day to day jobs for their business.

A lot of the most profitable software is the most tortuous to use. Case in point, SAP. Atrocious user experience. Yet, it sells extremely well (well, did, heh, read Blue Ocean Strategy). SAP can “run your entire business”. No other software product can make that claim with that much history to validate the claim.

This is important when you consider extremely large companies with a variety of different departments from HR to shipping, to finance, to IT. Even a modicum of perceived productivity enhancements across the board implies a significant amount of money saved. Remember, the 3 ways to make more money in a business:

  1. Raise your prices
  2. Increase your output
  3. Lower your overhead
Read more: Five Lies They Tell You in Software

Friday, February 18, 2011

Switch vs Strategy

Switch vs Strategy:

Recently, I’ve been working with the blend mode feature for Bunnyhill, my upcoming 2D rending engine based on Molehill. And I’ve used strategy objects to replace what could have been written in a switch statement. I think this could be a nice example for replacing switch statements with strategies, so I’ll share some of the details here.

The Switch Appraoch

First let’s take a look at the naive switch appraoch to set the blend mode of a render engine. Say we have a render engine that implements the interface below.

interface IRenderEngine {
 function setBlendMode(value:String):void;
}

And the BlendMode class provides static constants representing different blend modes.

class BlendMode {
 public static const ADD:String = "add";
 public static const ALPHA:String = "alpha";
 public static const NORMAL:String = "normal";
}

A possible render engine implementation for the switch approach is shown below.

class RenderEngine implements IRenderEngine {
 public function setBlendMode(value:String):void {
  switch (value) {
   case BlendMode.ADD:
    //use add blend mode
    break;
   case BlendMode.ALPHA:
    //use alpha blend mode
    break;
   case BlendMode.NORMAL:
    //use normal blend mode
    break;
  }
 }
}

In our main program, we could set the blend mode of the render engine like this.

renderEngine.blendMode = BlendMode.ADD;

The use of switch seems quite reasonable at the first glance, but is identified as “coding bad smell” in Refactoring, by Martin Fowler. If we were to add more blend modes to the render engine, this means we have to add an extra constant in the BlendMode class and an extra case in the switch statement. One feature change results in changes in two places, no good!

This is when the use of strategy objects should be considered.

The Strategy Approach

[...]

Thursday, February 17, 2011

Getting started with Ember

Getting started with Ember:

the Game

If your new to entity systems then you may want to read my posts on Game Architecture and Entity Systems first to get an over view. You can download the code for this example here

Ok so first step to making games on the Ember frame work is to create you games main class. This has the same role as an applications context in robotlegs.  Its main role is the initialization and tearing-down of you game.

package{
    import com.tomseysdavies.ember.base.Game;

    public class MyGame extends Game{
        override protected function startUp():void{

        }
    }
}

we can now launch the game from felx like so and pass it a reference to the display object that we want to become the games view.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:local="*">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <local:MyGame contextView="{gameView}" />
    </fx:Declarations>
    <mx:UIComponent id="gameView" />
</s:Application>

Components

So our game is now launching and has a reference to its view so we can now look at creating our first component. A component is a value object its highly portable and normal has no methods only data. For this tutorial we will need two.

package components
{
    public class PositionComponent
    {
        public var x:Number = 0;
        public var y:Number = 0;
    }
}
package components
{
    import flash.display.Bitmap;

    public class GraphicsComponent
    {
        public var asset:Bitmap;
    }
}

Entities

Now lets go back to our start up function. So here we first create that our components then next we create an entity and add our components to it. Think of an entity as an empty container to which we can add components. We create entities with the entityManager [...]

Entity Systems

Entity Systems:

Favour composition over inheritance

If you haven’t already read my previous post on the problems of traditional game architecture and why entity systems are needed. I’m going to cover the basics of an entity system before we look at 3 different implantations and the pro’s and con’s of each.

What is an entity?

An entity (sometimes called game object) represents something in the game. For every tree,tank or ninja we have an entity. An entity is container to which we can add components (behaviours) that define what it is. e.g In this rather conceptual example a Ninja gets a Renderer, Physics, Health and Stealth components which together make up a Ninja.

Entity system

This is the basics of all Entity systems one of key feature is the ability to create entities and change there components at run time. So a Ninja could become a Tank! (that’s the hard sell done).

Spotter guide.

There are 3 main ways to implement an entity system I have seen and I’m going to quickly out line them all and take a critical look at the pro’s and con’s. I’m going to call them common, almost and true (yes I’m bias but I think they are appropriate names)

“Common”

Most common implantation you are going to come across. Its based on the strategy pattern and its the simplest to understand. The first time I built a entity system this is what I did. There are good example out there in flash like PushButton Engine.

How it works

All components have a common interface normal with a function update(). Calling update() on entity causes update() to be called on all its components. Components then update there data for example a render component may copy its graphics to a view port.

Common Entity system

Pros

Simple and fast. Better than inheritance.

Cons

Scalability and flexibility (how easy it is to make changes). To explain the issue lets take an example. We have an entity with both renderer and physics components. Both need to know about the location of the entity in the world. So we have two options

  1. push the data up into the entity its self.  In complex games this can result inmore and more specialised data gets pushed up into the entity creating a god object.
  2. Allow components to access other components data. When one component depends on the data in another component we get a dependency. Component A can’t function unless component B exists. As a game grows so does the complexity of the dependencies.

There are work arounds to this issue for example automatically creating component B when A is added but then we need to give it the correct data. We start to lose the ability to mix and match components on the fly that makes an entity system so powerful. Entity to entity communication for example in collision detection is also difficult.

“Almost”

[...]

How to communicate between game objects.

How to communicate between game objects.:

Over on Richard “PhotonStorm” Davey’s blog he proposed a simple way to communicate between objects in your game using a “Registry” a class with static variables storing all the major systems of your game. So, for example if you wanted to create a spray of blood when an enemy is hit, in the enemy’s hit() function you would include the line Registry.fx.sprayBlood(x, y) and the FX object stored in the Registry.fx variable would create the blood spray and handle updating etc.

In the comments on Richard’s post, I pointed out that this isn’t a very object-oriented approach: these are basically global variables by a different name. I have used a similar approach myself on quite a few games projects, and overall it works well and is a quick way of getting things done. I have, however, encountered two problems with it.

Firstly, you can end up with all you code in one huge blob or “god class”. For example, if the FX class is responsible for handling any possible visual effect you would want to create, it could end up getting very big. But, other than academic notions of “good” and “bad” code, there’s nothing especially wrong with having big classes. They may be a bit harder to maintain and reuse, but nothing to worry about too much.

Secondly, using static/global variables as a communication method means you can be limited to having only one “game” in a single project. Now in most scenarios this wouldn’t be a problem, but it’s normally best not to assume you will only ever have one of a particular class of object. I’ve worked on several Flash projects that were collections of minigames in a single swf. Where I was relying on static variables in some of my base-classes and utility classes, I started to see clashes between the different games.

Ok so how do I handle the same problems? Well, say an enemy needs a reference to the player in order to chase after them. Rather than looking up Registry.player, I would just have a “player” variable in my enemy class and I would pass in the value of player when I create the enemy, or once I know the player exists. Or if the enemy needed more than a couple of different references from game in order to work, I would just pass in a reference to the game itself, and let the object access whatever information it needs. As Richard points out, the downside to this approach is that you end up with a lot of references in different places. This isn’t really a problem if you null your references when destroying objects, but it is more work, and you can leak memory if you’re sloppy with it [...]

Sunday, January 30, 2011

ActionScript OOP and Design Patterns: Why Bother?

ActionScript OOP and Design Patterns: Why Bother?:

At a workshop not long ago I found myself saying, I’ve got nothing against 4th Graders. It was in relation to the MVC, which is the precursor to the Gang of Four’s catalog of patterns, but it’s appropriate in this discussion as well. Originally, I was asked what I had against MVC, and I said, Nothing, [...]

Sunday, December 26, 2010

Functional ActionScript Part 2: Trends in Functional Programming

Functional ActionScript Part 2: Trends in Functional Programming: Last week, I explored some of my conceptions–correct and otherwise–surrounding functional programming. This week, I'd like to talk about use cases for functional programming, tools that use functional techniques, and ways that you can use functional concepts without passing function [...]

Mockolate

Mockolate:
Mockolate is a framework to create mock objects and test spies for AS3. A mock object can be used to simulate the behaviour of complex, real (non-mock) objects when using the real object would be impractical or impossible. Situations where a mock object would be useful:
  • When an object is slow (like a database or webservice),
  • is non-deterministic (like the current time),
  • has states that are difficult to reproduce (like network connections

Wednesday, December 22, 2010

Functional ActionScript Part 1: Thinking Functionally

Functional ActionScript Part 1: Thinking Functionally: Several months ago, I came across a blog post, Separating Event Handling From Event Filtering, by Thero Hultberg. At the time, I thought it was a cool idea, but obviously it was impractical at scale because the proposed solution [...]

Tuesday, December 21, 2010

Write high quality unit tested Actionscript 3 for fun and profit…

Write high quality unit tested Actionscript 3 for fun and profit…:

For the past year or so unit testing has been one of my favorite subjects. There are tons of books on the subject, but several really stand out. Here are my favorites so far:


Clean Code by Uncle Bob Martin

This book does cover unit testing a bit. It isn't the focus of the book, but regardless it sits here at the top of my unit testing list. Why? Because the hardest part of writing unit tests is writing code that can be tested in the first place. Get it. Read it. Learn it. Seriously. Uncle Bob rides in the vanguard in the battle against horrible dirty code[...]

Best practices for real-time collaboration using Flash Media Server

Best practices for real-time collaboration using Flash Media Server: Take advantage of RTMFP to build real-time collaboration apps that succeed despite the connectivity challenges of the Internet.

Sunday, December 5, 2010

ActionScript 3.0 Interface: What are they good for?

ActionScript 3.0 Interface: What are they good for?: "Let’s Be Humble Design Patterns were founded in the context of OOPSLA (Object-Oriented Programming, Systems, Languages & Applications) gatherings sponsored by the ACM (Association for Computing Machinery) and attended by both academic and industry programmers. These are smart folks in the world of computing, but as I’ve mentioned on other occasions, they are far less arrogant [...]

Saturday, December 4, 2010

ActionScript 3.0 Saturated Abstract Factory 2: What’s Wrong with Inheritance?

ActionScript 3.0 Saturated Abstract Factory 2: What’s Wrong with Inheritance?: "strong>Doing Composition The essence of the Abstract Factory Design Pattern is to create compositions for the Client. In the class diagram shown in Part I of the Saturated Abstract Factory series, the Client looks like a juggler pulling in different parts that are composed into a functioning component. (”Components” in this context are objects created using [...]

Real Software Engineering does it work ?

Real Software Engineering does it work ?: "

I am a self taught developer and I am proud of that :)

My primary education is within electronic enginering and I have always had the impression that this gave me a advantage compared to the
people with a formal education in software development.

So when I watched the presentation “Real Software Engineering” by Glenn Vanderburg I got my suspicions confirmed.
Watch the entire presentation here:
http://www.softdevtube.com/2010/11/29/real-software-engineering/

"