Archive for the ‘Programming’ Category

Digging for Social Gold (by Jambool)

Tuesday, October 12th, 2010

So I have decided to use Social Gold for my game. The service, features, and pricing seem great, but documentation is weak for noobs. To get started, I was looking for something more than the terse API docs and the mostly useless FAQs.

After a lot of Google digging (and no reply from Jambool support, which worries me), I found the slides to a webinar that is strangely no longer available to the public. It turned out to be the best documentation for integrating Social Gold with Flash that is on the Internet. (I didn’t even find any blogs talking about it.) Why isn’t the webinar replay public? The slides are. *shrugs*

Anyway, here are the slides, in case you want to see.

Java or Flash for game programming: which one?

Monday, April 26th, 2010

This question comes up a lot.

No, a lot!

The problem is, it’s not important.

Not important?! you exclaim. Then why do people ask it all the time?

Ok, actually this is a variation on another question: “What programming language should I use to make my game?” Once you’ve made some games, you come to know that it doesn’t matter. Any language will do. What does matter is the end product! Is it fun? Does it run on enough machines to meet your goals? Does it do what you wanted it to do? That’s all that matters.

Technology is a tool, so use whatever language you’d like.

As true as that is, it’s not always true.

The one way that choosing a language does matter is in the context of what you want to accomplish. Is your game downloadable? Or is it meant to be played in a browser? Those are big considerations, and they will have a material effect on what language (and tool set) you choose.

Narrowing things to Flash versus Java (where I have the most experience if you don’t count 10 years of C++), though, the answer is still, “It depends.”

Java and Flash both do downloadable and browser deployment, so let’s assume those factors are equal and are, thus, non-factors.

Do you want to reach the broadest audience or are you more interested in fast rendering and processing?

We all want fast rendering, but I mean does your project need lots of rendering muscle to succeed? Not just, “Oh it looks so cool.” but “Oh, this is not playable!” It’s got to really matter to the end product (because, ultimately, the end product is all that matters).

Java can render using hardware and is way faster than ActionScript, so it will have more power than Flash. A great browser library for Java is PulpCore. The feel of Flash with the speed of Java (although, it doesn’t do hardware rendering that I know of–but it is very close to a Flash experience without Flash, if that suits your persuasion).

Flash will ensure that your users have a more hassle-free experience since it’s installed on 99% of computers, whereas Java has quite a few old versions that are common. Relying on hardware rendering can give rise to technical incompatibilities, though Java doesn’t have to use hardware, so that can be mitigated.

Java is getting better about updates and penetration, but Flash still wins when you want to be compatible with the most computers (especially older or quirky hardware). That’s not to mention Flash is more web-enabled (ie, has strong support for integration with many sites and game portal APIs like Kongregate and Facebook), so for online games it makes lots of sense.

So, again, your answer has to derive from the question of how it affects the end product and what your goals are for it.

I’m doing online games, so I don’t want players to have to download and install anything. That’s a huge concern to me, so Flash wins almost right away because it’s the most hassle free. My second concern is penetration, and again–for my goals–Flash wins. I design for lower quality visuals but it’s made up for by the fact that I can reach more potential players. For commercial reasons, reaching more players is more important than having the best rendering sizzle.

For my backend (a.k.a. game servers), I use Java. Java is plenty fast, works on the platform I care about (Linux for servers), and was easy to learn with my backlog of C++ experience.

To summarize: the language you use is only relevant in context of the goals of your end product.

If you’re a hobbyist and don’t have any real goals, pick anything you like. If you have commercial goals, pick something that directly supports those goals.

It’s very project-specific, and it might even change from one project to the next.

Whatever the case, just make sure you’re having fun and don’t get all serious and uptight about languages and tools. It’s about the games!

Angry Explanations #2: Spinning a freaking image with PBE!

Thursday, November 19th, 2009

Following on from Angry Explanations #1, we will now add some motion to the scene. For kicks and giggles, we’ll cause the image to rotate each frame.

(Note that this information is in reference to PushButton Engine build r625.)

The key takeaway here is that for a component to be tickable, it must implement the ITickedObject interface and then tell the ProcessManager to start and stop calling onTick() every tick.

Oh, there’s one other key takeaway here: how to use PropertyReferences. You get a property of a component by way of the owning entity. You create a PropertyReference instance for each data member that you need to access. In this example, we’re accessing the rotation field on the SpriteRenderer component we added in Angry Explanations #1.

In a bit more detail, the PropertyReference is constructed with a special string: "@Sprite.rotation" (see line 11 in the code below). That means, this is a reference to the component of this entity with the name “Sprite” (recall that we gave it that name when we created the SpriteRenderer component instance), and the field “rotation” of the SpriteRenderer class. It’s quite simple once you realize what it’s doing (but I’m no less angry, mind you!).

I thought that a SpatialComponent might be necessary to alter the sprite’s position, but apparently that component has been removed (since r470, which is the current packaged release). That data seems to now be handled by the renderer component itself.

Add this one line to the end of showLogo() from the previous example:

spriteEntity.addComponent( new SpinController(), "spinner" );

Then add the following new class in a sub-folder (components/controllers/).

package com.yourcompany.yourgame.components.controllers
{
	import com.pblabs.engine.core.ITickedObject;
	import com.pblabs.engine.core.ProcessManager;
	import com.pblabs.engine.entity.EntityComponent;
	import com.pblabs.engine.entity.PropertyReference;

	public class SpinController extends EntityComponent implements ITickedObject
	{
		// Cache the PropertyReference instance here to avoid a bunch of temporary allocations.
		private var _rotProp:PropertyReference = new PropertyReference( "@Sprite.rotation" );

		// Nothing to do in the constructor because this is such a simple example.
		public function SpinController()
		{
			super();
		}

		// When the component is added to the sprite entity, we want to register to
		// get tick updates by the ProcessManager.
		protected override function onAdd():void
		{
			super.onAdd();

			ProcessManager.instance.addTickedObject( this );
		}

		// When the component is removed from the sprite entity, we want to unregister
		// from the ProcessManager so tick updates will stop.
		protected override function onRemove():void
		{
			super.onRemove();

			ProcessManager.instance.removeTickedObject( this );
		}

		// Each tick, we just change the rotation of the sprite renderer a little bit.
		public function onTick(tickRate:Number):void
		{
			// Get the current rotation.
			var rotation:Number = owner.getProperty( _rotProp ) as Number;

			// Add 1 degree to it.
			rotation += 1;

			// Store the new rotation back in the sprite.
			owner.setProperty( _rotProp, rotation );
		}
	}
}

As an addendum, I should point out that the rotation will probably not be smooth. To fix that, you should have the SpinController implement IAnimatedObject instead of ITickedObject. The registration with the ProcessManager is the same, except you call addAnimatedObject() instead of addTickedObject().

The difference is that IAnimatedObject will update when Flash draws a frame instead of when the ProcessManager ticks, and the motion will appear a lot smoother.

And you’ll want to normalize the rotation based on delta time since the last frame. Er, like this:

public function onFrame( elapsed:Number ):void
{
	var rotation:Number = owner.getProperty( _rotProp ) as Number;

	// Rotate 15 degrees per second, nice and slow.
	rotation += 15 * elapsed;

	owner.setProperty( _rotProp, rotation );
}

Angry Explanations #1: How to draw a freaking image with PBE!

Tuesday, November 17th, 2009

(Thanks to Ben G. for that humorous title! :D And just to be super clear–I’m not angry at all about PBE. The anger is entirely tongue-in-cheek.)

So, yeah, I got started with PBE at a bad time, I think.

It’s in transition between some major changes, and so all the docs and tutorials to this point are out of sync and kind of very… confusing. Because of that, I really struggled to figure this out, and in fact couldn’t get an image on the screen without professional help (I’ll let you interpret that however you’d like).

This information is relevant for PBE r625 and up.

(This isn’t to say the engine is poorly designed–it’s simply not accurately documented in places because it has been changing so quickly. And to be fair, it’s still in beta. I wouldn’t use the engine if I didn’t think it was great.)

A frustrated noob’s guide to getting a freakin’ image on the dang screen using Flex 3

Here’s the MXML which will reference the code.

<?xml version="1.0" encoding="utf-8"?>
<game:Game
	xmlns:mx="http://www.adobe.com/2006/mxml"
	xmlns:game="com.yourcompany.yourgame.*"
	width="750"
	height="600"
	layout="absolute">

</game:Game>

Now define a resource in a ResourceBundle subclass, which is the image you want to display, and let PBE automagically make it accessible through the resource manager.

package com.yourcompany.yourgame
{
	import com.pblabs.engine.resource.ResourceBundle;

	public class EmbeddedResources extends ResourceBundle
	{
		// The path is magically also the name of the resource.
		[Embed(source="../assets/images/logo.png", mimeType="application/octet-stream")]
		public var logoImage:Class;
	}
}

Put that image into action! It’s a simple notion, but somewhat complicated if you’re new to the engine and its gooey innards.

package com.yourcompany.yourgame
{
	import com.pblabs.engine.PBE;
	import com.pblabs.engine.entity.IEntity;
	import com.pblabs.engine.resource.ImageResource;
	import com.pblabs.engine.resource.ResourceManager;
	import com.pblabs.rendering2D.DisplayObjectScene;
	import com.pblabs.rendering2D.SpriteRenderer;
	import com.pblabs.rendering2D.ui.FlexSceneView;

	import mx.containers.Canvas;
	import mx.core.Application;
	import mx.events.FlexEvent;

	public class Game extends Application
	{
		public var resources:EmbeddedResources;

		// We need access to this in a couple of functions.
		private var _scene:DisplayObjectScene;

		public function Game()
		{
			super();

			// Let the Flex Application initialize fully before we muck with it.
			addEventListener( FlexEvent.APPLICATION_COMPLETE, onStartup );
		}

		// This is called once the Flex app (stage, in particular) is initialized.
		private function onStartup( e:FlexEvent ) : void
		{
			// Load our embedded resources (the image to show).
			resources = new EmbeddedResources();

			// Tell PBE to initialize and pass it our instance so it can get the stage.
			// (Remember, Application is a subclass of Sprite, which PBE needs.)
			PBE.startup( this );

			createPbeScene();

			showLogo();
		}

		private function createPbeScene():void
		{
			// Create a new IEntity for the scene view.
			var sceneEntity:IEntity = PBE.allocateEntity();
			sceneEntity.initialize( "sceneEntity" );

			_scene = new DisplayObjectScene();

			// Since this is Flex, we need the appropriate scene view class.
			var sceneView:FlexSceneView = new FlexSceneView();

			// Set up the view size.
			sceneView.width = 750;
			sceneView.height = 600;

			// FREAKIN' IMPORTANT: add the view as a child to our display list!
			this.addChild( sceneView );

			// Connect the view to the display object scene (a component).
			_scene.sceneView = sceneView;

			// Add the display object scene to the scene entity.
			sceneEntity.addComponent( _scene, "renderer" );
		}

		private function showLogo():void
		{
			// Create a new IEntity instance for the sprite to be displayed.
			var spriteEntity:IEntity = PBE.allocateEntity();
			spriteEntity.initialize( "logoEntity" );

			// Add a sprite rendering component.
			var sprite:SpriteRenderer = new SpriteRenderer();

			// Tell the renderer to draw (and load) this image resource.
			sprite.fileName = "../assets/images/logo.png";

			// Tell the renderer to draw to the display object scene.
			sprite.scene = _scene;

			// Add the component to the sprite entity.
			spriteEntity.addComponent( sprite, "sprite" );
		}
	}
}

So, what the heck just happened? Pfft! Don’t ask me! I’m still a freakin’ noob! :)

I know a couple of things, though. The SceneView is like a “canvas” where all DisplayObjectRenderers are drawn. So you create entities and fill them with components (like a SpriteRenderer) and tell the renderer component about the scene view. Magically, the sprite appears! It’s not too much to understand if you just want to know the API and how to use it.

To really understand it, you’ll need to look under the hood and figure out the connections. A good bit of hidden work is being done to simplify the API, but possibly at the expense of understanding. It’s neither good nor bad. It’s just The Way of PBE (for now).

Feel free to post here to help fill my gaps in comprehension. I haven’t used the engine enough to write a thorough explanation, and I’m not too proud to accept help. :)

Virtual item sales in Flash: a managed payment service roundup

Friday, September 4th, 2009

The microtransaction bug seems to be going viral these days among the Flash community. There are a growing number of companies offering managed payment services to Flash developers: they handle the dirty backside, and you give them content and share the income.

I personally think that it is worth it to build your own system (and I’m usually the guy saying, “Use the middleware, fool!”). But I think it depends on the scale of what you are planning. In my case, I want total control, and I want to own access to my customers so that I can continue to communicate with them. I also don’t want my games to become advertisements for a payment service.

I don’t view virtual item sales as just a sales channel. It’s also a gesture that means a player cares about and is emotionally invested in the game, and I want to maximize that relationship to make my players happy, long-term customers. Without access to my customers, the payment service is crippling my business. I don’t know that all these systems insulate the developer from his/her customers, but that is a major issue to bear in mind.

These Flash-specific services could be really useful to someone who is making much smaller scale games and wants some add-on sales or someone experimenting with virtual goods in an effort to diminish reliance on ad revenue. I’m not reviewing any of the services, just announcing that they exist. I haven’t investigated them all very deeply, but I will be poking around.

75% – andrograde.com
70% – www.nonoba.com
60% – www.gamersafe.com
60% – www.mochimedia.com
50% – www.heyzap.com

Which is best? It depends on your goals and plans. If you’re just making little quickie games (90% of Flash games), then any of the above would work. If you have a more broadly scoped business plan, you might want to steer clear and look into services that are not Flash-specific and spend the time/money to do the integration yourself.

When instanceof doesn’t recognize an instanceof.

Thursday, August 13th, 2009

Java’s ‘instanceof’ keyword is not the same as ActionScript’s ‘is’ keyword. In theory, they do the same thing: find out if an instance of an object implements a class or interface. In reality, they’re quite different.

Java compares for an exact match. ActionScript compares for a match or any subclass of the class being compared.

Let’s say we have class A which implements interface I. And we have class B which is a subclass of A (and implicitly implements interface I).

Java:

if( A instanceof I ) // True
    print( "yeah" );

if( B instanceof A ) // True
    print( "yeah" );

if( B instanceof I ) // False!
    print( "yeah" );

ActionScript:

if( A is I ) // True
    print( "yeah" );

if( B is A ) // True
    print( "yeah" );

if( B is I ) // True!
    print( "yeah" );

So, having learned a lot of ActionScript before diving into Java, I expected ‘instanceof’ to behave just like ‘is’. But no. And that was annoying not to realize at first. So, you’ve been warned!!

Update: Hmm, now I wonder if overloading method parameters behaves the same way as instanceof in Java? I’m going to be safe and make an interface for any classes that have multiple subclasses (ie, categories of entities which require special behaviors). It’s still polymorphic, so I guess it’s “good design.” I haven’t had quite enough experience digging into the reasons for Java’s language design choices.

Update 2: Of course I had to test the behavior of overloaded methods. Turns out that Java isn’t as exacting with overloaded methods–which is a relief!

For example, I have an Entity class, and a subclass called ItemEntity. I need to do some special handling on an ItemEntity (or any subclass of it) in a method that takes Entity as a parameter. Overloading that method to take an ItemEntity gives me the desired behavior for ItemEntity or any subclass of ItemEntity. Yay!

When ActionScript talks to Java using bytes

Saturday, August 8th, 2009

I’ve just finished building my client/server communication loop for Spirits of Gaia. The client is Flash (Flex), and the server is Java (built on Project Darkstar).

Darkstar uses a binary message format, which is a different approach from something like SmartFox, which uses strings (“raw”, XML, or JSON). I had experience with SmartFox, but I hadn’t tried to implement a binary format in Flash before. It really wasn’t bad in the end, and most of my time was spent just learning about ByteBuffers and ByteArrays in ridiculous amounts of detail.

And–of course–one of my bugs probably induced more research than necessary as I attributed malfunctions to various other possible causes. The bug was that I inherited one of the command processing classes from a base class which didn’t implement what I thought it did, so it was silently failing. :roll: But I learned a lot. A whole fricken lot! And that’s enough learning for anybody.

So one issue is that you can’t be sure what the endian-ness is for the server or the client. Well, maybe you can, but before now I didn’t know enough about it to make any assumptions. Darkstar uses ByteBuffers to hold incoming messages, and the default for Java is big endian for ByteBuffer. Thus, I use big endian on the server.

I had a feeling that Flash would take care of it for me, but of course I wanted to make sure it was using big endian, too. For a while, though, I didn’t know how to make a ByteArray use big endian or little endian.

hexadecimal My first approach was to get around it entirely by encoding all values that require more than 1 byte into hex strings. What a joyful aside that was! (Sarcasm, you see.) I mean, now I know how to encode anything to hex and back and do it sideways, too. But, this wasn’t working so well and it was bloating the nice binary format anyway. (No, I wasn’t really concerned about the size of the packets based on that, but if there’s a better way and it’s more space efficient–why not?)

Then I dug a bit deeper and realized that you can tell a ByteArray to use big endian like this:

var buffer:ByteArray = new ByteArray();
buffer.endian = Endian.BIG_ENDIAN;

Hard, huh? :) So then I didn’t need to encode multi-byte values into fun hex strings anymore (with one exception). So my PacketBuffer class got a bit more efficient in speed and size, and all is well now.

The one exception is for Java long values, which are 8 bytes. Flash (as far as I know) has no way to pull an 8-byte value from a ByteArray. And, no, I don’t want to do it by hand–which doesn’t mean I won’t! If encoding to hex string doesn’t work out, then I’ll write some code to stitch 8 bytes into a long value and stuff that into a Number (since it won’t fit into a 4-byte int). But, honestly, that kind of stuff is not my cup of tea because it’s not fun to me. But if it’s gotta be done, I’m a professional, so I’ll buckle down and do it. Clearly, I want to whine about it a lot just in case I do really need to do it.

For completeness, you tell a Java ByteBuffer to use big endian like this:

final ByteBuffer buffer = ByteBuffer.allocate( someSize );
buffer.order( ByteOrder.BIG_ENDIAN );

I think it’s ok to assume that Java (and Darkstar) will still default to big endian on whatever OS my future game server will be running (a flavor of Linux, no doubt). If I run into some bizarre bug where command ids are getting scrambled, I’ll know the first place to look.

Learning resources for Darkstar newbies

Friday, June 5th, 2009

I’ve been intensely researching Project Darkstar Server (PDS). Along the way, I thought I would collect some of the documentation, forum posts, and tutorials that have helped me understand how to get started. I’ve tried to avoid outdated stuff and only post things relevant to the latest Darkstar (0.9.9 0.9.10 0.9.11). Over time, I will add more as my own knowledge and experience deepens.

So, I present to you A collection of valuable links and resources for finding your way through the Darkstar code thicket.

Getting Started

You’ll need to understand this before you even get started.

Server

Example Clients

Darkstar Basics

Understanding Managed Objects

Understanding Tasks

Services and Managers

Protocols and Transports

Known Issues (Big Ones)

Vital Tools

  • Gamalocus profiler and viewerreally useful, and the graphical viewer makes interpreting the data much easier. It hasn’t been updated in a while, so I hope the project owner keeps it up to date or it can be given a new maintainer.
  • Asynchronous task library – if you need to do anything outside of Darkstar (like access a database), you will probably want to use this to work outside the Darkstar task time limitation. (I wish this was on Google code. The Java.net site is really horrible [and slow for me] by comparison.)
  • MockSGS – a unit testing library for Darkstar.

Better than SmartFox? Researching Project Darkstar Server.

Thursday, May 28th, 2009

I haven’t reached any conclusions yet, but I am really excited about Project Darkstar Server.

Project Darkstar is software infrastructure that aims to simplify the development and operation of massively scalable online games, virtual worlds, and social networking applications. Originally created by Sun Microsystems, it is today advanced as an open source project through the Project Darkstar Community.

I knew about it a few years ago, but it didn’t seem complete enough to bother with. But then I saw that CampFu had launched using it on their games backend, and that pushed me over the fence into wanting to investigate because it has to be pretty robust and usable to support a commercial product like that.

campfu I like SmartFox Server just fine. I think for my needs (indie games on small to medium scale), it would work really well. But two big motivations for looking at Darkstar are that 1) Darkstar seems like it provides more MMO functionality from the start, and 2) Darkstar is free and open source.

I had written a hefty chunk of server code for SmartFox already, and had plans for more. That’s really the product’s weakness for doing something with a persistent world type experience. SmartFox is very bare bones, but that’s not a bad thing if you go in knowing it’s not MMO-in-a-box. Well, I don’t think Darkstar is, either, but it appears to have more than SmartFox that is specifically for virtual worlds. So that is what really excites me about it: maybe I can get to building game logic sooner!

I’ve only done a day of reading about it, and I’ve downloaded and browsed through the 0.9.9 distribution. So far it looks really cool, and I like that the developers want to make it seem like a single-threaded program, because I’m not looking forward to debugging thread race conditions and all that crap. Another big plus for Darkstar, in my book.

If things pan out, I am going to be releasing a multiplayer Flash game. Some folks were balking at the idea of using Unity for Lila Dreams, but I still think that’s the way I’m going for that project. But it doesn’t mean I’m done with Flash, because I have a closet full of game concepts that I’d love to be able to create eventually. PushButton Engine is still very much on my radar. And, as I’ve said elsewhere, I choose the technology based on the needs and goals of a project and its parameters. I’m not a fanboi of any particular technology, platform, programming language, etc. I just use what makes the most sense on a case by case basis.

Maybe Darkstar will become my server technology of choice. I need more time to dig deeper and find out what it’s really like to use it on something that is non-trivial. Does it really provide a lot of virtual world infrastructure as compared to SmartFox? Is it viable for indies? I guess you can find the answers when I post again on this topic in the near future! :)

Two weeks with Unity: Flash what?

Tuesday, April 7th, 2009

I’ve got most of my Flash work on hold at the moment, because I’m basically abandoning my own Flash game engine in favor of the upcoming PushButton Engine. I invested a lot of time, blood and sweat into my own engine and even built a nice editor. But, the friction of trying to push that forward while also trying to prototype new ideas is enormous–especially after using Unity.

I will detail my thoughts and experiences with PushButton Engine in a later post (I haven’t used it much, and it’s not quite production ready), but I can offload a huge amount of effort and leverage the work of a bunch of really smart people. But, I digress.

This post is about Unity. It’s been about two weeks since I started working with Unity. Because it’s a 3d engine and doesn’t use ActionScript, it had the effect of forcing me to learn more than just the Unity API and editor.

I’ve become a 3d modeler. Yes, I’ve bitten the bullet and learned about Blender. Turns out it’s a really nice tool, it’s free, and it’s a lot of fun! I haven’t animated anything yet, but that’s coming up real soon.

I have created several models during my learning stages (over the past few months in between everything else), and I think one day I will be decent at it. I’ll never be great, but I can probably model most of the stuff my small projects will require. Albeit, this is something that will require a lot of practice. I don’t expect much in the way of pleasing results for a while. But that won’t stop me from making new games.

I’ve learned C#. Unity uses Mono (an implementation of .NET), and I don’t like UnityScript (ECMA script, basically) because that’s how I roll. I prefer a verbose, strongly typed, manly language, and C# delivers. It wasn’t hard to learn since it’s close to C++, ActionScript, and Java, and I know all of those already. I did buy a book, though, for reference and some deeper learning as my Unity projects increase in complexity. Overall, C# has been fun, but not as fun as learning Blender. :)

Here’s how I would sum up my experience with Unity from a total noob standpoint:

  • Realize that almost every core game engine system is already implemented: input, physics, collision detection, rendering, runtime game object management, editing tools, web connectivity, asset management, etc. It’s all there.
  • Hit a few annoying oversights: font handling, lack of collision groups/filtering, a very minor particle system missing feature (rotation/spin). Realize that you can still do 99% of what you want to without developing a huge infrastructure of your own.
  • Proceed directly to game logic programming. Do not mess with low level minutia at all, other than learning the API.
  • Become joyous and explode with glee.

So, yeah. Basically, you just go straight to the fun parts! :) I am working on a simple learning project which I will release soon, and I honestly think that if I had known how to model, how to code C#, how to use Unity’s API that I could have made this game in a few days, tops. The art and sound will be more time consuming than making the game itself!

This is such a huge change from Flash, especially when I was slogging away on my own engine, trying to get to a point where I could do what I am now doing in Unity. I just want to get the heck on with making a game. I’m not the kind of guy who enjoys low level system programming. Some coders like that stuff, and–bless their hearts–now I don’t have to. 8)

All the hype is true. Unity is everything you’ve heard that it is.

I won’t totally abandon Flash (yet), but at this point Flash has specific, limited utility (2d games that need a specific look and games that require massive audience reach) whereas before I viewed it as obvious and clearly superior choice for web games. No more!