Category Archives: Blog

Microsoft Stuffs Santa’s Sack with Gore

i took some time out of my schedule to hit X09, Microsoft’s annual holiday preview event for the Xbox 360 and related platforms. This is the nth year i’ve attended as a journalist, although truth be told my game journalism days ended when i woke up to the fact that i couldn’t make an honest buck from it. (So, too, ended my volunteer work, my origami hobby, my devotion to fatherhood, and my patriotism … if it wasn’t profitable, i decided to cut it out of my life.)

Crying little girl

Sorry, sweetie – you’re not economically viable.

Microsoft usually wears its heart on its sleeve at the X events. You can tell by looking around the room where they’re hedging their bets for the holidays, how they’re hanging their hopes. One quick glance around the room at this year’s events spoke volumes about the company’s holiday strategy: no kids, no families, and no casual gamers: just pure, unbridled core players with a penchant for blood n’ tits. God help us.

Generic First Person Shooter

Where have i seen this game before? Oh yeah – EVERYWHERE.

In the past, i’ve written for Whoa! Magazine and GamePad, two Corus Entertainment kids’ properties, and The Magazine Not For Adults (formerly Disney Adventure magazine), so my kid-dar is pretty finely honed at this point. i’m pretty adept at sussing out which titles will be M-rated at launch, and which ones will be T-rated but still inappropriate for the audience (realistic war games never made the cut, by my insistence). i strolled down one wall of the This is London night club in Toronto dismissing each game in turn: first-person shooter, first-person shooter, South Park-themed tower defense game, first-person shooter, third person stealth espionage, first-person shooter, first person shooter. And so on.

And sequels! i caught a glimpse of Splinter Cell: Enough Already, and Grand Theft Auto: Repeatedly-Sodomizing-a-Dead-Horse City. And the game landscape was the blandest, most unoriginal i’ve ever seen it.

Variety Doesn’t Sell

In previous years, there had been Xbox Live Community Games (now Indie Games). There had been friendly characters like Spongebob Squarepants and Banjo Kazooie. There had been Scene It! and You’re in the Movies and Viva Piñata. It’s not that any of these more accessible titles were necessarily any good, but at the very least i got a sense that Microsoft was trying to court a broader audience, trying to sell a system that everyone could enjoy.

Viva Pinata

Viva Piñata: obviously, since it is brightly coloured and features neither blood nor tits, only children are allowed to play it. Or fags – it also appeals to fags.

Well, we now see where that strategy has led them. Whether it’s because Microsoft itself has abandoned all hope, or whether the third party publishers saw abysmal financial returns on their family-oriented products (or indeed, whether the PR company wanted to look cool in front of the members of the gaming public who were invited for the first time this year), Xbox Live is no place for kids, families, or guys like me who don’t go in for blood n’ tits games.

Innovation Schminnovation

i counted on one hand the number of non-FPS, non-M-rated titles, and i had fingers left over:

  1. Tony Hawk: Ride, the one with the skateboard peripheral
  2. DJ Hero, the one with the turntable peripheral
  3. Rock Band: The Beatles, the one with the guitar and drum peripherals

Aaaaaaaand … that’s about it.

Rock Band: The Beatles

Not into first-person shooters? Good news: we’ve got all this extra crap you can buy.

So to you gamers who are slow to take a chance on innovative new franchises – you who want only more of the same, and who are happy with seeing a bigger number next for your favourite game’s title, you’re in for a real Christmas miracle this year.

You’ll run downstairs and slide on your knees to the foot of that tree, soft naked bottom peeping out of the bum flap on your pyjamas, and gaze with wonder at the gifts upon gifts that Santa left you. You’ll tear open the wrapping on each one in turn, eyes wide and mouth agape, imagining the thrills and unbridled delight each title will offer. And when the shredded paper has all been tossed to one side and the shrink-wrapped cases of your new Xbox 360 games sit glistening in the warm glow of the Christmas tree lights, you’ll marvel at the spectacle of a dozen or more new games to play for your Xbox 360 video game system.

And they’ll all be exactly the same game.

The 8 Types of Items in Multiplayer Games

You may or may not know the name “Nexon”, but you’ve most likely heard of their games. The Korean company has produced the industry-leading titles Maple Story and Kart Rider, to name but two. And although they may not have invented virtual item sales through microtransaction as they sometimes claim, my hat’s off to them for showing the world that you can make a tidy sum from them.

Nexon’s Min Kim was recently interviewed by Gamasutra about the company’s upcoming virtual world Block Party. During the interview, Kim rattled off a list of the eight types of items you can sell in an online game.

When it comes to items, they can serve eight purposes, says Kim: function, envy/prestige, recognition, collecting, rarity/scarcity, competition, friendship, peer pressure. These are the keywords, he said several times, that you should be thinking about when designing your items to sell.

With the likes of MochiMedia, GamerSafe and HeyZap offering Flash microtransactions, i thought it would be worthwhile to explore Kim’s list, and to provide examples to flesh out his examples. Some of these item classifications bleed into others. Most of them need to hook into some sort of multiplayer game, because they’re driven by social interactions. But there are ways to structure your game to leverage feelings of envy and aspiration that don’t require a live multiplayer server, which i’ll explain in this article.

1. Function

The first item type is one that affects gameplay, like the downloadable tracks in Rock Band 2. Other, more generic examples are things like guns that provide extra firepower, and winged mounts that let you fly clear across a virtual world. Often, these items have the most perceived value to a player because they actually do something. Occasionally, they’ll even give a player an advantage over other players during gameplay.

Rock Band Music Store

i dropped twenty bucks in the RB2 store this past weekend, and only played one new song. Don’t judge me.

The danger is that by selling functional items, you risk alienating your player base, creating a class system of haves and have-nots. When poorly designed, functional items can actually exclude players from playing together; in the case of Rock Band, all four band members have own a downloadable track in order to play through that song together. It’s not long before a group of online strangers have to default to the songs that shipped with the disc, because none of them own identical set lists. Electronic Arts faced a lot of flack when players learned they would be charging extra money for in-game weapons in Battlefield: Bad Company that many people thought should have been included with the experience.

2. Envy/Prestige

Virtual clothing fits nicely into this category. In a multiplayer game, everyone wants to stand out. We can all recall the pain of spending half an hour tooling up a character for a virtual world, only to jump into that world to find that half the game’s population chose the same hat, boots and skin tone. Finding your twin online isn’t quite as annoying as wearing the same dress as another girl to prom, but it’s up there.

IMVU

IMVU fulfills every little girl’s dream of growing up to be slutty.

Some games are even designed so that all of the free players (or “hobos”, as i like to call them) look just similar enough as to annoy the player. A quick hit with the credit card is enough to straighten that out – one dollar buys you a new wardrobe item that no one else has. That is, until everyone else spends a dollar to have it, in which case you need to keep ponying up the real-world cash to stay ahead of the fashion curve.

The Xbox Live service recently added an Avatar Marketplace that consists solely of Envy/Prestige items.

Xbox Live Avatar

i spent five bucks to watch a fake person having fun?

3. Recognition

Recognition items that are based on player achievement, like trophies, banners and crests, are difficult to sell. These are most often freebies that a player unlocks by accomplishing something in the game. One way that i suppose you could monetize this type of item is to enable the player to pay to turn a free achievement into a concrete item.

Let’s say, for example, that they player can buy a statue of himself to put in the town square, but ONLY if he kisses seventeen muskrats. The player goes out and accomplishes this amazing feat, but has no real way to show it off – no one is going to go digging through the player’s mission log to uncover that particular accomplishment. So the player pays $23.95 real-world dollars to convert his achievement into the statue to brag about his prowess with muskrats.

Another option is to charge players to unlock badges, trophies and achievements that other players come by honestly. This kind of thing can go on in an after-market area – for example, while researching this article, i found a site that purports to sell you Pogo Club badges for $5 apiece.

Pogo Badges

We don’t need no stinking … oh, forget it.

Of course, players who spend a million hours mastering a game to unlock the Magic Whizzwang cry foul if you start selling Magic Whizzwangs to players with more dollars than time. There are a few strategies you can adopt here:

  1. Do it anyway, and cry yourself to sleep on a bed of money.
  2. Run the after-market site yourself, but don’t put any corporate branding on it, so that it looks like some shady fly-by-night site is selling badges, but you get all the profit
  3. Don’t do it, and risk losing out on a potentially major source of revenue.

There’s not a lot of difference between selling achievements and selling powerful in-game weapons. In both cases, you’re monetizing “time-poor, money-rich” players over “time-rich, money-poor” (AKA hobo) players. The difference is purely psychological: we think of awards as something to be earned, not bought. Of course, graduate to the Real World and you’ll find that most things in this life are earned with money, awards included.

4. Collecting

This is one of my absolute favourite item types to design. When i was working on The Sitekick Proejct for Corus Entertainment, i designed a number of often complex item collections, where certain items had to be combined like Voltron to unlock other items. i didn’t quite reach that Mecca where i had kids combining their Voltron uber-items to unlock Super Mega Ultra items, but i can see that’s where my career would have gone if i had stayed. :)

Sitekick

Confession: i friggin’ LOVE Sitekick.

Of course, the natural progression for The Sitekick Project or any game like it, with its big empty Pokemon-inspired list and it’s 1000 some-odd items is to charge players for items so that they can fill in gaps in their collections. While it’s a reasonably compelling prospect for an adult, you have to understand that maintaining complex collections is a psychological attribute of your people, and completing that sticker album or plastic pony set becomes absolutely crucial. It might be worth a few bucks to mom and dad to stop junior from having the DTs and just buy one or two missing items.

5. Rarity/Scarcity

The Sitekick Project also had its share of rare items, but of course it picked up its cues from other games – most notably CCGs, or Collectible Card Games. And CCGs owe it all to baseball cards.

Babe Ruth rookie card

Babe Ruth’s rookie card. My gut tells me this has appreciated in value.

The very best way to monetize rare items, incidentally, is to follow the baseball card model: items are sold in packs. Some items are rare. The player must continue to purchase packs filled with mostly mundane items and “doubles” in the hopes of stumbling upon a rare item. You can even produce rareities in tiers: you can go from “rare” at .01% probability to “legendary” at 0.001% probability. Rare items are usually shiny.

Depending on your scruples as a designer, you can also charge your players a large fee to flat-out buy a rare item. Just make sure the price is high enough to deter most players, who will likely end up spending more than the cost of the buy-out price fishing for rare items. This is the crane game principle that leads you to spend $35 trying to snag a $2 stuffed animal out of the machine, when the same amount of money could have gone towards a perfectly nice Gund bear at the Hallmark store down the street.

Crane Game

Just say NO to crack cocaine, and these things.

Another way to sell scarcity is to release a series of items and to arbitrarily limit their quantities. Of course, since the items are digital, scarcity is entirely artificial. Imposing an item quantity on them or selling an item for a limited time only is a great way to see completist players snapping stuff up like it’s an End of the World Sale. And once a player buys a limited item and the sale expires, it becomes both a Rare and Prestige/Envy item in one fell swoop.

6. Competition

i had trouble interpreting this one, and discerning it from Prestige/Envy items. There are a few ways i can think of to charge for competition:

  1. Sell tickets or entry fees to competetive events
  2. Build in a competetive aspect and charge players for the item with which they compete (a friend of mine bought a lot of Xbox games so that he could get a higher GamerScore than me. The Achievements are free [with purchase of game]. The purchase of game isn’t.)
  3. Sell the game itself and let players be competetive on their own. For example, you can see an air hockey table as a furniture item for a player to store in his room. The player can challenge friends to come to his house and beat him at air hockey. You can even build in a “home advantage” to an air hockey board that a player owns – perhaps the owner of the table always gets to go first?

7. Friendship

Korean game Cyworld popularized virtual gift-giving, and went so far as to make those virtual gifts expire, which blew my mind. This was years before North American designers were even thinking about virtual item sales, and the Koreans were already pioneering a virtual sofa that you could buy with real money and give to a friend that would vanish in a puff of smoke after two weeks. It boggles my mind.

Facebook Gifts Landfill

A brilliant bit by artist Arend deGruyter-Helfer – a Facebook Gifts landfill.

8. Peer Pressure

Again, this is a subtle thing to distinguish from a Prestige/Envy item. i think the difference is that a Prestige/Envy item is something that one person has that you want. A Peer Pressure item is something that EVERYBODY has. You want it not because it’s a particularly attractive item, but because you don’t want to feel left out.

Here’s how i see this working: throw a toga party in your virtual world. Hype it HUGE. Have everyone mail away (in-game) for a toga, and cut off mail-in toga orders at a certain point. Then just grind away on the hype machine for a week, while the players can’t order a toga. On the day of the party, everyone who sent away for one receives a free toga via in-game mail. You can also find other ways to give away togas for free on the day. Make sure it’s well known that EVERYBODY must have a toga to properly party.

When over half of your players have a toga, and the other half do not, make togas available as an impulse item for x real-world dollars (or cents). Then, sit back and watch people snap up those togas.

This is a good way to avoid pissing off your players: you gave them every opportunity to get a toga for free. The players who have to buy togas have only themselves to blame.

Freaks

One of us … one of us … one of us …

Here are a few additional categories of virtual item types that i’d like to add to Min Kim’s list:

Sustainability Items

These are items or services that constantly suck players’ resources to keep them playing. Picture a car combat game where you have to keep buying gas. Tamagotchis were essentially giant drains – you had to keep feeding and playing with your virtual pet, or else it would die and you’d brick your device.

The Sims characters are on constant drains – their hunger, happiness, fun and social lives are constantly sapped as you play.

The Sims

That’s funny … i feel MY fun being sapped as i play.

If you build out a lot of gameplay beyond keeping your virtual parasite happy and emotionally well-adjusted, completing mundane tasks like feeding and watering your online identity becomes a bore. So you can sell players items like auto-plant feeders, dog-walking services and extra gas tanks, instead of making players drill for their own crude.

Charity Items

i very much like the idea of virtual items that are tied to some sort of charitable cause. The red movement pulled this off with their Facebook gifts, and i can see it working elsewhere as well.

Red Charity

Pilfe(red).

Insurance

You haven’t yet seen a virtual world where a tsunami hits your virtual house while you’re away and wipes out all your tchotchkes. That’s because i haven’t designed my own virtual world yet. But in my dystopian vision, you can buy fire, theft, flood and gigantic lizard insurance to protect your goodies from various Acts of Ryan.

Feature Locks

At the beginning of most virtual worlds, you design your avatar and choose a house. The designer can then lock these two features, and others like it, forevermore. Once you choose your look, that’s it. It’s done. Once you choose a neighbourhood to live in, you have to abide by that choice. Once you choose your character’s name, it’s locked in for all time.

This enables you to charge a lofty real-world price for a key game feature that you’ve already built. Charge the player a “plastic surgery” fee to go back into the character creator tool. Good fun.

Step Right Up

The Art of Money Getting

Best. Entrepreneurship book title. Evar.

As you can see, you need to be a bit of a PT Barnum type in order sell virtual items online. We’re talking about selling something that has no inherent value, that costs you zero dollars to reproduce, and that lives or dies on the human psychological foibles you’re able to tap into. The morality of all this may be questionable, and i’ve heard some folks call virtual item sales downright evil, especially when it comes to selling virtual items to children. But i have another perspective:

  1. Having been a child myself (and, in fact, remaining so to a large extent), i know first-hand the real joy that a virtual thing can bring. Some of the most amazing places i’ve been, some of the most interesting people i’ve met, and some of the funniest things i remember have all been from video games, while many of my real-life experiences have fallen far short of my virtual experiences.

    And when i laid that last sticker down in my Panini He-Man and the Masters of the Universe sticker album, i knew that the scads of allowance money i’d burned collecting those stickers had been worth it. In my own small child universe, i had accomplished something. i had followed through, and i had achieved.

    And today, employing much of the same determination, focus, and vision, i continue to achieve.

    Prince Adam

    Thanks to He-Man, i am also aggressively homosexual.

  2. If rich people are so well-off that they have nothing better to do than to spend their money on non-existent items, more power to them. i willl gladly take their money and build out the charitable arm of my company, so that real people with real needs can eat real food.

This way to the great egress!

Made with Unity3D: Paradudes and Bomb Factory

i ran into Zylex of M2H Game Studio in the #Unity3D chat channel on IRC. He had just launched two products in the iPhone App Store and was trying to promote them. Since both products were made with Unity iPhone AND one was free AND he was gracious enough to provide a promo code for the other to one lucky reader, i thought it would be a nice idea to give him some love.

So we totally did it, and then i stmbled onto the corporate blog with sex hair to promote his games.

Paradudes

Paradudes

Flying nerds.

This simple tap-em-up features bespectacled, be-parachuted dudes who fall from the sky at an increasingly rapid pace. You touch the ‘dudes to make them pop their chutes and slow down. Each chuted dude gives you a coin, and sheds an additional bonus coin that you can tap for double the points. If a ‘dude drops off the screen with no chute, you lose a heart. Lose all of your hearts, and the universe implodes, both destroying you and causing time and space to fold in on themselves.

Paradudes

Don’t let the title confuse you: there are more than two of them.

Speed isn’t the only escalation: the game introduces ‘dudes who already have their chutes open, so that when you instinctively tap them, they close their chutes and plummet to their (presumably) adorable deaths. There is also POISONED MONEY (American, i guess?) that makes you lose hearts when tapped. Add to this balloons that need to be popped, and falcons that need to be … murdered? i’m not sure. But they’re worth bonus points. The high scores screen also lists UFOs, of which i saw NONE because games like these usually put me into cardiac arrest within the first thirty seconds.

Falcons must (inexplicably) die

If you see a falcon, assassinate it, for it is worth points.

Paradudes is an excellent testimony to the fact that just because you wield fancy 3D game software like Unity for iPhone, it doesn’t mean you have to produce something complex or technologically mind-blowing. Paradudes is essentially a 2D game with 3D models with all the hooks to make it a fun little tap-fest. And you can’t beat free.

Download Paradudes from the iTunes App Store!

Bomb Factory

Bomb Factory

Bomb Factory: incidentally shares its name with the film studio that casts American Idol winners in lead roles.

i can’t give a succinct review of Bomb Factory because i didn’t play it – i didn’t want to shell out the 99 cents because Zylex is a lousy kisser. But maybe you can try it out and leave a review on our What Are You Playing? forum? Zylex was good enough to provide us with a promo code for a FREE version of the game. The code can only be redeemed through a US iTunes account, so if you’re from a decent and peaceable country, don’t bother trying it.

Bomb Factory promo code: MLRNL9LK4R7F

The code is single-use! If you’re the first reader to punch it in successfully, you’re the only reader to punch it in successfully. If you claim the code, please be decent and leave a comment to let us know so that the rest of us don’t waste our time typing it in. i won’t make you write a review – i promise.

Download Bomb Factory from the iTunes App Store!

Monkey See, Monkey Code

i LOVE seeing games that use a technology i’m learning, because it helps me write a longer “How’d They DO That?” list, and ultimately helps me to learn more of that technology. Until it got into the realm of hijacking Pixel Bender to do multi-threading, i was constantly trying to emulate amazing things i’d seen other people do in Flash. i hope that by showcasing games Made with Unity, your head will also start reeling with possibilities.

Five Common AS3 to UnityScript Translations

i’ve been using Unity3D on and off for a week now. i’d burned through about a dozen beginner tutorials, and am a little overwhelmed by how much i don’t know about the engine, which enables you to create 3D games to deploy to a number of platforms, including the iPhone and web browsers.

i’d look like a fool if i tried to write a tutorial at this point. So instead, i’ll share this list of translations of common Actionscript 3 coding tasks to the Unity3D engine’s JavaScript-like UnityScript language.

Flash to Unity

1. Render an Object Visible or Invisible

Actionscript 3:

thing.visible = true; // or false

UnityScript:

thing.renderer.enabled = true; // or false

2. Tint an Object

Actionscript 3:

var colorTransform:ColorTransform = new ColorTransform();
colorTransform.color = 0xFF0000;
thing.transform.colorTransform=colorTransform;

UnityScript:

thing.renderer.material.color = Color.red;

3. Get a Random Number

Actionscript 3:

var someRandomNumberBetween0And5:int = Math.floor(Math.random()*5);

UnityScript:

var someRandomNumberBetween0And5:int = Random.Range(0, 5);

4. Respond to a Key Press

Actionscript 3:


stage.addEventListener(KeyboardEvent.KEY_DOWN, doKeyDown);

private function doKeyDown(e:KeyboardEvent):void
{
	switch(e.keyCode)
	{
		case 32:
			// Space bar! Do stuff.
			break;
		default:
			break;
	}
}

UnityScript:

if(Input.GetKeyDown("space"))
{
	// Do stuff.
}

5. Open a Web Page

Actionscript 3:

navigateToURL(new URL("http://www.untoldentertainment.com"), "_self");

UnityScript:

Application.OpenURL("http://www.untoldentertainment.com");

Tutorial – Understanding Classes in AS3 Part 4

In this tutorial, you’ll learn about the OOP (Object-Oriented Programming) concept of encapsulation, and how to break encapsulation to get stuff done in a decent amount of time.

Technical Correctness vs. Getting Sh*t Done

i’ve been really happy with the way this series has been received. If you’re like me, you’ve had a hard time understanding the big deal about OOP and Classes – you know it’s something you’ve got to bite the bullet and eventually learn, but it seems like a whole lot of extra typing for nothing.

Cat on keyboard

i’ve been typing for friggin’ HOURS!

But for those of us designers-turned-coders who have embraced Classes (or have been forced into using them for a paid project with a deadline), we’ll tell you that when written the “right” way, Classes can free you from writing a lot of code in your next project.

The trouble comes when you know so much about Classes that you write them too correctly. You can definitely spend too much time making a Class all things to all people and for all purposes. “It’s a MegaClass that can be an animated sprite AND a media player! It’s so VERSATILE!” Meanwhile, you either haven’t launched a game in a year, or your clients are calling every other hour wondering how their project is coming along.

Kids in back seat

Are we there yet? Are we there yet? Are we there yet? Are we there yet?

Let’s Recap

In Understanding Classes Part 1, you freed yourself from the timeline. In Part 2, you took a little detour and learned how to piggyback your library to write custom MovieClip symbols using inheritance. In Part 3, you started looking at how code could be organized in separate files to keep your workspace light, and to better organize your work. Now let’s take a look at the next principle of OOP, encaspulation, to see if we can’t turn our Classes into true drag-and-drop Lego bricks.

OOP Encapsulation

Good encapsulation makes dinosaurs happen. Bad encapsulation makes the dinosaurs go crazy and kill people.

Lego, Ikea furniture, and Your Code

Once again, the three principles of Object-Oriented Programming are inheritance, encapsulation, and polymorphism.

Think of your Classes as Lego bricks. You want to build a Media Player brick that works in your current project, that you can lift out and snap into your next project that requires a Media Player, with no extra work required. That’s the dream, anyway.

Lego

You want your code to be less time-consuming. You know – like Lego.

Up to this point, i’ve recommended that you make all of your Classes’ fields (things that a Class is) and methods (things that a Class does) public. Public variables and methods can be accessed by anyone and anything outside the Class.

Let’s look at some code. We have an ImageGallery Class and our Main Class. Main creates an instance (stamp, version, print) of ImageGallery and draws it to the screen using addChild:

package
{
	import flash.display.MovieClip;

	public class ImageGallery extends MovieClip
	{
		public var numberOfImagesICanDisplay:int = 5;
		public function ImageGallery()
		{
			// Display numberOfImagesICanDisplay
		}
	}
}
package
{
	import flash.display.MovieClip;

	public class Main extends MovieClip
	{
		public function Main()
		{
			var imageGallery:ImageGallery = new ImageGallery();
			addChild(imageGallery);
		}
	}
}

So far so good. But take a close look at that variable on ImageGallery:

		public var numberOfImagesICanDisplay:int = 5;

That field is declared public. That means that any idiot (including YOU) can access that field and change it. Let’s be a total jackwad and, from Main, change it to eight million:

		imageGallery.numberOfImagesICanDisplay:int = 8000000;

This messes up ImageGallery’s pyjama party to the very limit. How is ImageGallery supposed to display eight million photos? It’s only really set up to handle five images. There HAS to be a way to protect important variables like numberOfImagesICanDisplay from other ass-hat Classes like Main.

Terminator

i recommend sending the Terminator back in time to prevent yourself from messing with that variable.

Stop Looking at My Privates

Fortunately, there is a better and less future-altering way. If we change public to private, only instances (copies, stamps) of the ImageGallery Class can read and write the value of that field. Hooray!

The way i suggested you write your Classes was completely backards. Public is the most permissive access modifier. Private is the least permissive access modifier.

The rule i’ve read is that you should always start out restrictive, declaring everything private, because once you go public it’s kinda hard to go back to private. (If you were an early bloomer in high school who “went public”, you’ll know how difficult it is to regain your privacy)

Slutty schoolgirl

It’s hard to recover from going public

So declare everything – methods and fields/variables – private. If you find that any outside Classes need to access those methods and fields later, you can open them up by making them public.

What Should I Make Public?

Object-oriented programming eggheads are pretty particular about the kinds of things that should be public, and those that should be private. The example i’ve heard is to think of a device like a vending machine. There are certain client-facing input methods that need to be accessible to the outside world:

  • insert coin
  • push snack button
  • push coin return button

And there are certain things the vending machine is going to return to the person using it:

  • snacks
  • coins
  • error messages (“SOLD OUT”, INCORRECT CHANGE”, “NO CANDY FOR YOU, FATTY”, etc)

So the vending machine accepts input and dispenses output. Everything else is private. The user does not need to be able to control the coils that turn to dispense the snacks. The user has no business figuring out how to make change inside the machine, or managing the vending machine’s inventory of goodies. That’s all internal stuff. That’s private.

Vending Machine

None shall know the labyrinthine secrets of the vending machine! MWA HA HA HA HA!!

Dispatching Events

We already know how to write a public method on a Class, and we learned how to pass a parameter through to the Class. Here’s a snippet from an imaginary vending machine Class:

public function insertCoin(coin:Coin):void
{
	// Tally up the value of the coin that has been inserted
	switch (coin.type)
	{
		case "quarter":
			coinValue += 25;
			break;
		case "dime":
			coinValue += 10;
			break;
		case "nickel":
			coinValue += 5;
			break;
		case "penny":
			// No pennies!
			return coin(coin);
			break;
		default:
			break;
	}
}

And here’s an example of how you might call that function from outside the Class:

vendingMachine.insertCoin(new Quarter());

In Actionscript 3, the proper way to signal to the outside world that something important has happened inside a Class is to fire an even dispatcher. Here’s what that looks like in our imaginary vending machine Class:

// This line goes at the top of the Class where you declare your fields:
public static const RETURN_SNACK:String = "returnSnack";

// And then later, when you declare your methods:
private function returnSnack():void
{
	dispatchEvent(new Event(RETURN_SNACK));
}

And here’s how you listen for that event in the Main Class (or from whichever Class instantiates [makes a copy of] the vending machine):

// Make sure you import the generic Event stuff near the top of the file:
import flash.Events.event;

// This is what your instantiation and listener definition look like:
var vendingMachine:VendingMachine = new VendingMachine();
vendingMachine.addEventListener(VendingMachine.RETURN_SNACK, getASnack);

// And elsewhere, you define the method to respond to the event:
private function getASnack(e:Event)
{
	// HOORAY FOAR SNAKZ!!!
}

Anyone see a problem yet? i do. We’re not really able to pass a parameter back to Main through our dispatchEvent command. So how does Main know what kind of snack it received?

There are a few ways around this. We can store a variable on Main called requestedSnack and take it on faith that vendingMachine returns the correct snack. Or, we can create a public variable on VendingMachine to store the returnedSnack, and in Main’s getASnack method, we refer to vendingMachine.returnedSnack. And then there are super egghead ways to do it that remain mysterious to me.

Nerd

i am not well-versed in the Way of the Nerd.

Let’s Get Ready to Fudge It

But here’s the CHEATERPANTS way of doing things. Using dispatchEvent is nice, because we can plop this vending machine down in any other game or app and it WORKS. It’s encapsulated. There are no dependancies. We just need to listen to all of its dispatched events in the new file, and we’re gold. But to be honest, that’s a whole lot more typing, and i’ve got things to do.

The cheaty way to do it is to pass a reference to Main as a parameter to the VendingMachine Class:

// From Main:
var vendingMachine:VendingMachine = new VendingMachine(this);
// From VendingMachine:
public function VendingMachine(main:MovieClip)
{
}

// And then later in VendingMachine:
private function dispenseSnack(snack:Snack):void
{
	main.getASnack(snack);
}

Hooray! No need to listen for an event, dispatch an event, declare a constant, or tapdance around the return value problem. The vendingMachine instance knows who its daddy is, and can invoke any of Main’s public methods.

Who's Your Daddy

(um … i can’t actually tell, ’cause his head is cut off)

Of course, the drawback is that this breaks encapsulation. You can no longer pick up your VendingMachine Class and move it to a new project, because VendingMachine is dependant on receiving a reference to a Class that has a public method called getASnack() on it.

Here’s how i go about it: if i’m writing something that i think is pretty handy, and it’s abstract enough that i’ll likely use it in future projects, i might do the extra work to write a nicely encaspulated Class. But if it’s sunny outside and all the other kids are playing in the park, and i can hear their joyous squeals through my opened window, i’ll break encapsulation and throw my Class a reference to the Class that instantiated it.

Splash Pad

Encapsulation be damned – the splash pad’s open!

Don’t Cry, Nerds

Dear Eggheads: i haven’t left you out this time. The concept of passing a variable to the constructor function of a Class was explained perfectly clearly here, i hope, but i know how you like to muck things up with big words and impressive terminology. Your term for this technique is “Dependency Injection”, and if you’d like to read a more serious article on it with fewer pictures and bigger words, check out Joel Hooks’s article AS3 Dependency Injection Demystified.

Here’s a solid step towards demystifying it: STOP CALLING IT DEPENDENCY INJECTION. Sheesh almighty.

To read the rest of the Understanding Classes series, or to see more tutorials, check out our Flash and Actionscript 911 feature.