4k – Tiny Keyboard Handler


I’ve been toying with an entry into the 4k game competition held at gamepoetry. The game I’m making uses the keyboard for controls which is a bit rare for me.

AS2 had a very useful method called Key.isDown() whose functionality is pretty self explanatory. This isn’t available in the much more event driven AS3, but when doing something as tiny as 4k it’s a pretty useful thing to have. So I wrote my own tiny little version of it. A bare bones swf with nothing but this code weighs in at about 750bytes, but it’s not that big of an addition to your filesize since the swf has some basic stuff that adds to the size. The demo code adds another 200 bytes, but that’s meant to be stripped out.

Note that the trick is to add this into your main class, not to put is as a class of it’s own. That adds too much to your filesize.

I also recently discovered wonderfl which is a crazy cool online actionscript editor thingie. You can try the code live there! or the new even smaller version.

If that’s not your cup of tea, here’s the code in plain old boring text:
(This is an updated version, a whopping 17 bytes smaller)

package {
    import flash.display.Sprite;
    public class STKI extends Sprite {

        // this stores all key states
        // For some reason this seems to be smaller when typed
        public var k:Object;

        private var block:Sprite;

        public function STKI () {
            k = { };    // shorthand for initializing a object

			// the trick is to use the dynamic nature of objects,
			// if the property exists it's overwritten,
			// if it doesn't it's created
			// the function actually gets a KeyboardEvent, but
			// having it untyped makes it smaller
			// So does using a regular ("keyDown") string instead
			// of the static one provided by the event.
            stage.addEventListener("keyDown", function(e:*):void{ k[e["keyCode"]] = true});
            stage.addEventListener("keyUp", function(e:*):void{ k[e["keyCode"]] = false});

            // this is just to show that it works
            block = new Sprite();
            block.graphics.beginFill(0xff00ff);
            block.graphics.drawRect(-4, -4, 8, 8);
            block.x = 250;
            block.y = 250;
            addChild(block);
            addEventListener("enterFrame", handleEnterFrame);
        }


        private function handleEnterFrame(e:*):void{

            // this is how you use it, just access the keyCode
            // in the object, it acts just as good old Key.isDown
            // from AS2

            if (k[37]) { //left
                block.x -= 1;
            } else if (k[39]) { // right
                block.x += 1;
            }

            if (k[38]){ // up
                block.y -= 1;
            } else if (k[40]) { // down
                block.y += 1;
            }
        }

    }
}
Posted in 4k, code |
  1. that’s fantastic, and here I thought this couldn’t get more ugly. nice work!

  2. Hey, great tips! I used this technique in my 4k game entry, and actually improved on it a little. In the keyboard handler, change “true” and “false” to be 1 and 0, then in your update function, use: block.x += k[39] – k[37]; // Right – Left block.y += k[40] – k[38]; // Down – Up You have to initialize your k array to be equal to a string of 40 or 50 0’s, but I found that compresses really well, and the bytes saved are more than worth it. private var k:Array = [0,0,0,0,0,0,0 …. ,0,0,0]; Cheers! –clint

  3. Nice one 🙂 I do use un-typed vars, but not until the very end because it stops lots of the context sensitive assists from working in FlashDevelop! (same for strings replacing constants)

  4. I changed the event handlers into inline functions and that saved me a good 17 bytes. Thanks Richard. Using an array instead of an object actually added 2 bytes for me. You really should try using untyped arguments and plain strings instead of the constants, that’ll save you something like 11 bytes!

  5. If you’d like to save yourself even more bytes you could do the following: 1) Use an array instead of an Object and 2) Wrap the function into the event listener call itself. Functions add quite a lot of extra bytes to the SWF, the less of them you have in your final game, the smaller it will be! Here’s the code I use: stage.addEventListener(KeyboardEvent.KEY_DOWN, function (e:KeyboardEvent) { keys[e.keyCode] = true; }); stage.addEventListener(KeyboardEvent.KEY_UP, function (e:KeyboardEvent) { keys[e.keyCode] = false; } );

in one piece, source code


As promised, here is the complete source code for in one piece. This is the code for the refactored version, not the actual code that was entered into the jam. The game itself is the same, the code is just alot prettier.

I used FlashDevelop and the open source Flex SDK to code this, so that’s what would be the most convenient to use to get it running. It should compile just fine using Flex Builder too (it’s the same compiler), but using the plain Flash Authoring tool might be trickier. Although I hear CS4 supports the tag, so it might work.

The code uses Tweener for some quick animations, as3ds for linked lists (the inital plan was to have more stuff in the chain) and some color conversion code I stumbled upon on a japanese site a while back. All of these are included in the package for your convenience.

All the graphics are as .swf, the corresponding .fla files are also in there. You will however need the Flash Authoring tool to edit them.

The whole thing is under the MIT license, which basically means you can do whatever you please with it as long as you keep the license attached.

Any and all questions are welcome!

Posted in code |

in one piece


I present to you, In one piece, winner of the Audience award of Nordic Game Jam 2009. Read more about the game below.

Get Adobe Flash player

As you’ve likely noticed I attended the Nordic Game Jam this past weekend.

I ended up in a group together with Jonas and Joel.

The theme for the whole global event was As long as we have each other we will never run out of problems. We also had a few additional constraints:

  • A complete play session must always last 5 min or less
  • The game must be language independent
  • Choose one of the following adjectives:
    • Developing
    • Falsifying
    • Trapped

All three of us came up with a couple of ideas each, mine naturally involved ropes. Jonas had an idea about escaping from a shrinking chamber (pictured below). Joels idea was about a guy walking around the Roskilde festival (we were in Denmark, mind you) playing bongos. Attracting a ever increasing line of followers behind him.

iop-sketch2

iop-sketch3This is the idea we went with. It morphed and changed around quite a bit. Early on we decided to change the setting of it, a festival didn’t feel artsy enough. We also realized that a long line would be pretty hard to control regardless of input method, so we wanted to tweak the gameplay towards a different main mechanic.

That’s when we came up with the whole fitting into shapes idea (pictured right).

As you’ve likely noticed this blogpost has about a gazillion more images than usual. This is because of Jonas. He’s one of those pen and paper guys. It’s been a while since we worked together. And I had almost forgot how awesome it is to have a whole person dedicated to the art when making a game.

We called it a night pretty early on friday, just to get an early start on saturday. It was all downhill from there.

Joel got to work on the sounds. Also, most excellent to have someone being able to do that properly for once.

I took some screenshots during the saturday:

iop-progress1

iop-progress2

iop-progress3

iop-progress4

 

Most of the sunday was spent in a complete frenzy. The deadline was set at 1500, and that is also the exact time we started our upload to the server.

The game posted here has seen some additional improvements compared to the one we presented at the jam. All the changes made are cosmetical and the gameplay is 100% intact from the original. The code has also had a major refactoring, there’s not very much time to make things pretty when you find new bugs minutes before the deadline.

Speaking of code, I will post the complete sources with all you need to build the game yourself in a few days. It’s gonna be under the MIT license so you can do almost whatever you please with it.

Comments, questions and profanities are very much appreciated!

Posted in Games |
  1. Congraz nice game, my score 6,092,134

  2. Too bad about the time limit. Any chance of releasing a longer playing version? Would be cool to see this concept expanded into an aspect of a larger adventure game in which such dangers mustbe passed in various forms… but yeah, that’s alot more involved from a programming point of view.

  3. 6,760,515! 😀

  4. 3429955 😀

  5. I like that one of your level screenshots appears to be a phallic shape, hah.

Nordic Game Jam in Pictures


This weekend I attended the Nordic Game Jam, the flagship event of the Global Game Jam. A whole load of games were made, I’m not sure how many since I’m still waiting for the NGJ-site to get updated with the numbers.

The game we made will be up here shortly, we just need to fix some very minor stuff and get the size down a bit. It will also come with the complete source, although it was written in no-time-at-all so it might not be readable or even understandable.

The event was tons and tons of fun. Got to meet a whole bunch of new people and enjoy the wonderfully incomprehensible language of danish for a whole weekend!

All my pictures are available in my Nordic Game Jam 2009 set on flickr.

DSC_3323
From the left: Jonas, Kian, Joel, Bernie (behind), Cactus, Erik and Petri

DSC_3327
From the left: Petri, Joel, Cactus and Jonas.

DSC_3356
Heather did the keynote.

DSC_3387
Kian and Bernie

DSC_3388
Erik pretending to work

DSC_3426
Heather and Cactus making their game

DSC_3348
Cactus again.

DSC_3436
It’s me!

DSC_3398
Jonas and Joel hard at work, while I’m messing about taking pictures.

DSC_3417
LOLPETRI

DSC_3386
The IT-university was a pretty fancy place

DSC_3448
66.7% of us won a prize!

That’s the whole weekend summed up in pictures. Sadly none from the presentations or award ceremony but I’m hoping someone else got pictures of that.

More about the game we made in my next post.

Posted in News |
  1. Hoegaarden? It comes in pints? I’m having one! Also, we need more lolpetri on this blog.

  2. I’m surprised they’re taking that long to put the results up. But, judging from last year they look to be very thorough about it all, so maybe that’s why they delay.

  3. Hoegaarden is a quality beer! This is the most complete results from nordic game jam that I’ve managed to find: http://souplala.blogspot.com/2009/02/nordic-game-jam-copenhagen.html Apparently we did pretty decently even though we had our doubts.

  4. Wow, i miss that weekend already. Great pics! Atleast the ones i took 🙂

  5. Mmm hoegaarden! I can still taste that watery, fake-beer. Great pictures, Martin! 🙂

World of Goo in hands, various bodily fluids in pants


I got my dirty hands on my copy of World of Goo just over two hours ago. Two hours well spent in aforementioned land of thick, viscous matter. It’s a great game, every level so lovingly crafted. Go Preorder it Buy it Give them money this instant or I will kick your ass!
Now I need to get some sleep, damn this worldly body of mine, it’s all about eating and sleeping and way too little about gaming (and possibly even less about getting a occasional game up on this here blog)

Posted in News |
  1. Hm.. N1ce game btw

  2. Vilken härligt beskrivande rubrik!

The need for stupid amounts of objects.


The other day I got an email from someone who wanted to know how the “infinite” drawing in isotope3 worked. I figured this would be a excellent time both to share some code and get a post done around here.

The source code for this is available under the MIT license

I’m using a technique I first started to use in my game Eater of Worlds, it has since appeared in a few other things I’ve made.
Just piling hundreds of objects in a single DisplayObject causes Flash to redraw all of them each frame. Drawing vectors in Flash is pretty fast, but having to redraw them each frame is a bit unnecessary if they aren’t really changing. Enter cacheAsBitmap, this does exactly what you would expect it to. And it’s great. Until the content changes, then you have to redraw everything again. Taking both the hit of the redraw with the added punishment of creating the cache (not sure how big that is though).
In isotope3 I redraw each and every frame, negating any boost cacheAsBitmap would give.

So what I do is i create a “cache” bitmap, basically the same as flash would do automatically, but this bitmap I’m controlling.
This makes stuff a tiny bit more complicated, since you will need to explicitly tell flash what to draw to the bitmap each frame (or whenever you feel like it really). Another drawback is that if you’re using it to pile in large amounts of objects and want to remove something it gets tricky. A good way to solve this would be to keep the DisplayObjects, but not attached to any visible clip, and updating them as needed.

Enough with the talking for now, here’s a demo (Click it to make it go!)

This is how you set it up:

// initializing the canvas at 500x500, not using the
// autoclear and with a full size back buffer.
// if you're going to use blurring or some other "destructive"
// effect, you can use a smaller back buffer that means
// setting a bigger buffer divisor as the fourth argument
var _canvas:Canvas = new Canvas(500, 500, false, 1);
addChild(_canvas);

// this color transform is applied each update(),
// here i set the alpha multiplier to .5 making
// whatever was in the buffer the last time around
// gets faded by that amount
var colorTransform:ColorTransform = new ColorTransform(1, 1, 1, .5, 0, 0, 0, 0);
_canvas.colorTransform = colorTransform;

// a simple blur filter
// (it's faster with multiples of two for the blur-setting btw)
var blurfilter:BlurFilter = new BlurFilter(4, 4, 1);
// feed it in like this, this is too run on each update()
_canvas.addFilter(blurfilter);

This is what you do each frame to apply fades, blurs or whatever effects you put in there:

// if you don't apply any effects this isn't even needed.
_canvas.update();

To draw something on the canvas you do this:

// draws a white box
var box:Shape = new Shape();
box.graphics.beginFill(0xffffff);
box.graphics.drawRect(0, 0, 50, 50);
_canvas.draw(box);


Get the source, example and flashdevelop project here and try it yourself!

Big thanks to my friend Richard who gave me some feedback on the code making it possible to read for people that are not me.

Comments are very much appreciated!

Posted in News | Tagged , , , |
  1. Nice. Will put it to good use.

  2. ok 😉 thank’s a lot

  3. It turns out that Flex also has a class that is named Canvas. The Canvas I use here is my custom class, so you need to add that to your libraries and then import com.grapefrukt.display.canvas.Canvas instead of mx.containers.Canvas I’m sorry for the confusion.

  4. Console log said : draw() function is not defined in FLEX Builder 3 ex: import flash.display.*; import mx.containers.Canvas; var box:Shape = new Shape(); box.graphics.beginFill(0xffffff); box.graphics.drawRect(0, 0, 50, 50); _canvas.draw(box); var _canvas:Canvas = new Canvas(); addChild(_canvas); _canvas.draw(box); ——- Why ? Thank’s Matthieu

  5. Awesome. I’ve been trying to figure out this concept for some drawing apps that use a lot of alphas (and a stupid amount of objects 🙂 ). Thanks for the great post and insight!!

readspeeder


This is yet another entry in line with my recent non-game posts. I’ve always been a reasonably fast reader, both in English and my native language Swedish. However, it’s always nice to have some numbers to back up that general feeling. Thus I created readspeeder. It uses the complete book Down and Out in the Magic Kingdom by Cory Doctorow, which he has graciously made available under a Creative Commons license.

You control the speed with your mouse, move it to the right to go faster and towards the center to go slower. If you move to the left you will go in reverse, farther to the left will move faster in reverse.

You can click the progress bar at the bottom to skip ahead. The Words per minute counter is an average of your last 50 words. I’ve made it so that it makes slightly longer pauses for words with more syllables. It also makes a small pause between sentences, I’ve found that really helps with reading comprehension. I guess it gives your brain a chance to process the actual meaning of the sentence before getting on with the next one.

According to Wikipedias entry on speedreading anything above 600 wpm can be considered quite good. 1000-2000 wpm is on a World Championship level. The very fastest readers claim speeds of 10 000 wpm or more. But I find that somewhat hard to believe.

Posted in Games |
  1. It’s a bit hard controlling words per minute, would be easier with a slider i think …

It moves!


This is more of a tech demo than anything else. It’s something that’s in damn near every game they make nowadays, but i still haven’t seen in a 2D game, maybe because nearly no one makes those anymore.
I’ve made bloom. I’ve been wanting to make this ever since bitmap effects were introduced back in Flash player 8, but AS2 is far to slow to pull it of with performance to spare for an actual game.

The following is a bit actionscript focused, so if you just want the pretty pictures feel free to skip ahead.
The way it works is that it, instead of just adding the different sprites to the stage, i have a canvas (essentially a Bitmap) i draw them on. This canvas is then copied into a lower resolution bitmap. It could just aswell be the same size, but I’m running it at a half or a quarter of the original resolution for better performance. This copy is then transformed into a black and white image by lowering the saturation to zero, in this step i also crank up contrast way up to get nice big white fields. Then i apply a simple BlurFilter to get the fuzzy effect.
This is then drawn on top of the canvas with additive blending.

The effect works a lot better if you can do some pseudo (or actual) HDR, since what it does is that it takes the very brightest pixels and makes them glow. This is all fine and dandy, but having variable exposure really makes it pop.

As an added bonus a beta of the Flash Player 10 was released this week, this gives amongst other things, a nice speed boost for blitting. It also supports something called Pixel Bender, which basically is pixel shaders, they run on the graphics card and everything. This demo however, does not use them.

See the demo after the break.

In other news; I attended the Nordic Game Conference this week. The conference itself was so-so, in my opinion a bit too many lectures/panels. I realize that you need the wide appeal for a conference like this, but that can’t be at the expense of quality. It is still nice to have something like that almost on your own doorstep though.
The real highlight of this was however that I got to meet a bunch of indie people. I mostly hung out with Petri Purho of Kloonigames and Erik Svedäng that is making the very interesting looking Blueberry garden. We also did some beer drinking with thewreck and jeb of Oxeye games. Pure gold.

Continue reading

Posted in Games, News |
  1. Oh yeah. Works now. Wow, really fast reply! 🙂 Thanks.

  2. You’ll need Flash Player 10 installed. I’ve updated the post to be a bit clearer on that.

  3. I don’t see anything. It’s just a white space where the flash app is.

Super Moustache Generator 500


I thought it would be easier to work all week and then be creative on nights/weekends, but as you’ve no doubt seen here it wasn’t all that easy. There’s a reason for “all” this posting all of a sudden, I am now a little bit less of a working man. I’ve taken Wednesdays off for the foreseeable future to try and make some more fun little apps and games for you to enjoy.
There’s also a little bit bigger project in the works, but that’s a bit too early to talk about now, it might not even make it into development if i jinx it by writing about it here.
But enough with the rants already.

In other news, I’ve spent the last two days failing miserably at growing some form of upper-lip facial hair.
Today I channeled this frustration into Flex and came up with the Super Moustache Generator 500. It’s a bit dodgy in almost every sense as I wrote it in about four hours. You get what you pay for, as they say. Play around with the sliders to make your very own ‘stache, once you’re done I recommend saving the image, print it and then cut it out and play grown up for a while. That’s what I did.

You can send the patterns to your friends, isotope-style. The images stay on the server “permanently”, but if I see a lot of hotlinking going on I’ll change that in a jiffy.

Please do post any fun patterns you find in the comments, preferably with what you would call that particular type o’ stache!

Posted in Games |
  1. -2;22;5;58;0.88;-146;16;-18;0.96;1.51;0.8;0.87

  2. this is amazing.Gonna use it to make some simple wall art!

  3. Yaaay it works! cool moustaches! hahah. if only you could change the accual like ‘shape’ of the moustache curve.

  4. Mmmkay, I recompiled it using static linking instead. So now it should work for everyone that has a reasonably new flash player.

isotope3


So, this is yet another of those few and far between posts around here these days. But this time I’ve got something to show you. I bring you, the updated, super pimped-out, isotope3:

isotope3

The game/app/toy itself is on another domain, mostly to keep the url’s shorter for sending them to friends. I put this up last night and fed it to the stumbleupon-tubes and figured i’d write about it here today. Somehow I’ve managed to get 17k visitors on it already. Cool stuff.

Improvements over the old version include:

  • Massive epic speed improvement, more than 1000x faster
  • Customizable colors, both for isotope and background
  • Better, live pattern recognition (updates as you type)
  • You can now export settings, not just the pattern
  • And, as always, heated seats and cupholders

If you want to put this little thingie on your own little part of the interblags, here’s what you’ll need:

no flash

And oh, if you’ve missed it somehow, play with it here: isotope3

Posted in Games, News |
  1. Lovely work. I love the bitmap filter effects. I have to admit I like Isotope2 a bit more, though.

  2. Very nice and blindingly fast. AS3 I take it?

  3. Awesomeness! blurryblurry with fadyfady i likyliky. goodyjobby