Pardon the mess, Play My Code is in beta!

READY TO PLAY?
CLICK TO LOG IN!

sign up - lost password

Read Our Blog!

News, updates and more from the world of Play My Code. Keep informed, follow @playmycode on Twitter or subscribe via RSS.

Updates: New Server, User Profile Improvements, Transformations and More

Posted: by Seb under Play My Code Announcements

Our latest update is quite possibly our biggest yet, with extensive changes and additions made to both the site structure itself as well as the API. This is also the first post from our fabulous new server! Since this is a big one, there’s bound to be a few bugs- if you spot any then drop us an email via the feedback box, or send a tweet to @playmycode. Anyway…

New, Faster Server

We’ve ditched our ghetto shared hosting and gone pro, whilst a series of server-side optimisations and the implementation of a CDN means PMC should now be running blazing fast. It also gives us a great deal more options and flexibility in terms of what we can do in the future, as well as more room to grow- watch this space.

New User Profile Pages

Users now have better profile pages, to which they can add a personal biography plus Twitter, Facebook, Youtube and Website links as well as their geographical location. You should also notice we’ve added a drop-down menu from the top login box through which you can edit your account information. Make sure to log in and get your account populated with your details.

What’s more, each user now has an RSS feed, accessible via the RSS icon on their profile. Subcribing to a user RSS feed allows you to be kept informed of any new games they put out, without having to keep visiting their profile page.

Password Reset

An “obvious” feature which has been missing for far too long- password reset- is now in. To reset your password, click the Lost Password link underneath the loginbox.

‘About’ Page

We’ve added an About page to the site, in order to help inform newcomers to Play My Code of who we are, what we’re doing and how to get involved. If you have any other ideas on how we can make the site more accessible to new coders and designers, then please drop us a line (find contact details on the About page itself!).

Transformations Added to the API

We’re thrilled to announce that rotation, scaling and translation- amongst our most-demanded features- are now part of the Quby/PMC API. Expect a blog post very shortly showcasing transformations in more detail, but in the meantime find details in the documentation right about here, or check out the demo at the top of this post to see it in action.

Continue reading

one comment

JavaScript Per-Pixel HTML5 Canvas Image Collision Detection

Posted: by Joe under Under the Hood

Recently Play My Code gained per-pixel image collision detection. Here is a small demo of it in action:

Like the previous blog post about our image tinting implementation, here’s some behind the scenes information on how we added pixel-perfect collision detection to Play My Code- using a different approach to the usual algorithm.

Before We Begin

First I want to clarify that this is not an image to image collision detection, but between two ‘ImageData’ objects. The ImageData objects represents the pixels behind an image.

You can convert an image to imageData by drawing it to a canvas, and then calling ‘getImageData’ on the canvas object to retrieve its pixels. The code to do that can be found online.

Continue reading

2 comments

Updates: Full Screen, Auto Play, API Additions, Bug fixes and More

Posted: by Joe under Play My Code Announcements

We’ve finished a new round of updates for Play My Code including bug fixes, new API additions and some changes to the site and player.

Bug Fixes

Most of these were internal bugs, which rarely occurred or were quite minor. For example, missing titles on forum topics. Amongst notables ones are a bug fix for Safari when drawing a tinted image; for this we had to work around a WebKit issue. We have also improved fallback support for JavaScript AJAX errors, which makes the game player more robust.

A major bug some users might have noticed are the broken login sessions: on selection, the “remember me” checkbox on login now works as billed, keeping you logged in after closing the browser window.

Game Player Size Changes, and Full Screen Mode

We have altered the size of the game player slightly, to remove a shadow from the bottom of the player. It’s a minor yet necessary change, but those who have the player embedded somewhere might now notice a slight black border on the top and bottom of the game window. If you’d like to fix this on your embed, change the ‘height’ attribute of the player’s iframe to 438 in the embed code.

Sorry if this inconveniences anyone, there’s a couple of reasons behind this trivial yet important change: first, it’s to ensure the game player is just a menu and the game. Any styling around that should be left up to the site using it.

More excitingly, the other reason is we’ve enabled full screen mode on all games. In the embed code for a game, copy the ‘src’ attribute and paste it into your browser location bar to view said game in fullscreen. Play a full screen version of our RayCaster tech demo right here.

Auto Play

Another game player addition is the ability to auto play a game. Some of our users are starting to embed our games on their own sites, and want a visitor to be able to play straight away when the page loads. The auto play allows just this- it will enable the game to load and start playing automatically.

To enable this, you need to add ‘?auto_play=true’ to the end of the ‘src’ value in the ‘embed’ HTML code you have for each game.

You can find more information on auto play, as well as other game embed parameters, on the new Embedding page in the Docs section.

New Recommended Games Section

Regular users might notice we include a featured game on our front-page, hand-picked and recommended by ourselves. But when we update the front-page, what happens to our old recommendations?

You can now you can find all of our featured games in the new Recommended games section.

isKeyDown / isKeyPressed Improvements

You very often want to support both arrow keys, and the WASD keys, for movement. This usually ends up looking like:

c = getControls()
if c.isKeyDown( :a ) or c.isKeyDown( :left )
    // move left
end

To improve on this, you can now pass in an array of keys to check. So the same code can be written as:

c = getControls()
if c.isKeyDown([ :a, :left ])
    // move left
end

There are also times you want to detect any key input, for example to allow a user to skip a splash screen. To achieve this you can pass in ‘null’ to ‘isKeyDown’ or ‘isKeyPressed’, or call it with no parameters at all. For example:

if getControls().isKeyPressed()
    // a key has been pressed, doesn't matter which
end

Check out isKeyDown and isKeyPressed in the API section of our documentation for full details.

array.flatten

We have also added the ‘flatten’ method to the Array class. It allows you to turn a multi-dimensional array into a single dimension. Not the most exciting new feature, but very useful. More details on the flatten method can be found in the docs, right here.

We will of course be adding more features, fixes and refinements as time goes on. Follow @playmycode on Twitter for the latest announcements, and meanwhile please keep your feedback and feature requests coming.

no comments yet

Updates: Anonymous Functions, Image Collisions and Rounded Rectangles!

Posted: by Joe under Play My Code Announcements

Since our last update, we’ve been doing more then just playing around with raycasting engines…. This latest release is primarily about bug-fixes, which easily made up more then half of the changes. We also put a lot of effort into optimizing both Play My Code and our Quby language.

We’ve also found time to add a few new features along the way, and here are some of the highlights:

Per-Pixel Image Collision

Sometimes bounding boxes and other shapes aren’t enough, what you really want is pixel-perfect accuracy on a collision check. So, we’ve added the isPixelOverlap method to the Image class, allowing you to check if one image collides with another (on a pixel-by-pixel basis).

    a = new Image( 'a.png' )
    b = new Image( 'b.png' )
    
    if a.isPixelOverlap( aX, aY, b, bX, bY )
        // there is a collision!
    end

A collision is detected if two non-transparent pixels, from each of the two images, overlap each other.

We also implemented a pure bounds version, isOverlap, as an Image friendly version of the ‘isRectOverlap’ function.

    a = new Image( 'a.png' )
    b = new Image( 'b.png' )
    
    if a.isOverlap( aX, aY, b, bX, bY )
        // the images overlap, but it's not pixel perfect
    end

We use our own algorithm which is faster then the common way to implement this. For those working with JavaScript and the canvas, we’re planning to release a blog post later this week going into this in further detail (including code).

It should be noted that per-pixel collision detection has a much greater overhead than bounding box collision, and should only be used when such accuracy is required. For the majority of cases, bounding box collision will be accurate enough.

Rounded Rectangles

We also added two new sets of drawing calls: fillRoundedRect and drawRoundedRect.
They fill, or draw the outline, of rectangles with rounded corners. A nice extra tool for making game building a little bit easier.

Both of these excellent suggestions came from Giorgio in our forum just a few days ago, so if there is something new that you’d like to see added then feel free to post it. We’ve also implemented a few suggestions that have come in via Twitter, and of course you can also use the Feedback form on the top-left of this page if you wish to send feedback anonymously.

Anonymous Functions

You can now create first class functions in Quby, similar to in JavaScript and Ruby. This allows you to wrap up a piece of code and hold it in an object, with the ability to call it later.

The syntax is very similar to defining a function or method, only without the name:

    myFun = def( a, b )
        return a + b*2
    end

The objects are of type Function and you can then call it later using the ‘call’ method, passing in any arguments.

    result = myFun.call([ 1, 4 ])

This is especially useful for building event based systems where you want to be able to hold the actions within an object.

Faster, Faster!

Finally I mentioned at the start that the site is now faster. Some of this work is obvious improvements, such as our CSS and JavaScript being minified on every future deployment. We have also gone through optimizing lots of our CSS styles, reduced the amount of HTML served by the PMC game player, and performed a long list of other small tweaks to further keep the site as lean as possible.

Using Google Page Speed’s benchmarks, some pages now have a score as high as 95 out of 100; up to 20 points higher then they used to receive. However, we will continue optimising to ensure the site, and more importantly your games, run even faster.

no comments yet

Play My Code as a Rapid Prototyping Tool

Posted: by Seb under Game Development

PMC user Jayenkai (of A Game A Week/Socoder fame) has spent the past couple of weeks conducting a little experiment: knocking out small games in devastatingly quick succession, testing ideas and gameplay concepts. The experiment has been a resounding success: not only has he produced a cracking set of excellent games, he’s also demonstrated the effectiveness of Play My Code as a tool for rapid game prototyping.

Each game apparently took around an hour to make, a key factor towards this brevity-of-code being his having first written a framework which he has used as a foundation for each game (you will notice they’ve all got similar front ends, for instance). The results of this process demonstrate how easy and quick it can be to put a simple game together using Play My Code, leveraging the platform as a method of testing gameplay concepts. Doing this, one can test whether a game idea works (and by extension, is fun to play) while avoiding the potential pitfalls of spending a large amount of time creating rich assets or code for a title which ends up not really working gameplay-wise.

For those who are new to the concept of frameworks in software: at the most basic level a framework is a generic code template which can be re-used again and again to provide the basic foundation for software to be written upon. Most games will require similar (if not the same) code to manage things like game state, game input and resource loading (to name but a few), so writing a framework to handle these commonalities and building upon it can save countless hours of valuable programming time. For an example of a simple framework, have a look at the code for my Bombs ‘n’ Booty game. Strip out the game logic itself, and one ends up with a primitive game state manager which could be used as a basis for new titles- if you would like to use this as the basis for your own projects, then please do so.

Anyway, back to Jay’s games! Read on for a round-up of our favourites:

Continue reading

no comments yet

Realtime Image Tinting on HTML5 Canvas

Posted: by Joe under Under the Hood

We’ve improved our setColor() API function, so it can now be used to set the colour of images as well as text and primitives. See below for an example:

However the HTML5 canvas doesn’t support tinting images out of the box, so we’ve had to emulate it on top. Searching online, I found many questions but no definitive answer on how to achieve this quickly enough in realtime without compromising the quality of the image. So, how did we do it?

Common Approaches

The first method I tried for doing this is to simply take the pixels from the image, iterate over those pixels whilst adding the tint, and then re-apply the pixels back to the image (or to a new image). This works, but it’s simply too expensive.

The second method is to get a spare canvas and fill it with a coloured rectangle and draw the image on top. You can also have the canvas use the alpha value from your image. This works in realtime, but the quality is less than adequate. Here’s an example of our tinting (on the left) compared to this rectangle technique (on the right).

It’s a nice fast way of tinting an image and would be useful for certain situations, but as you can see it leaves the original image very whitewashed. We wanted a tint that was more like light, where if the draw color is just red then only the image’s red components would appear. With the rectangle approach you’ll still have some of the remaining blue and green components remaining.

So how do we do it?

First, you should be aware of the ‘globalCompositeOperation’ property on the canvas. This allows you to make the canvas mix colours in different ways when you draw to it. The downside is that it doesn’t have many options, and most are based around the alpha channels of the destination and the source (rather then on how the colours thenselves will be mixed).

The brainwave I had is that by separating out the components of an image, you can then tint it by re-mixing those components with different proportions. Separating the components out requires iterating over all pixels, but you only need to perform this once per image (and even then only those which will be tinted).

Specifically the image is split into a red, green, blue and black version. Each of these are then stored within their own canvas.

    function generateRGBKs( img ) {
        var w = img.width;
        var h = img.height;
        var rgbks = [];

        var canvas = document.createElement("canvas");
        canvas.width = w;
        canvas.height = h;
        
        var ctx = canvas.getContext("2d");
        ctx.drawImage( img, 0, 0 );
        
        var pixels = ctx.getImageData( 0, 0, w, h ).data;

        // 4 is used to ask for 3 images: red, green, blue and
        // black in that order.
        for ( var rgbI = 0; rgbI < 4; rgbI++ ) {
            var canvas = document.createElement("canvas");
            canvas.width  = w;
            canvas.height = h;
            
            var ctx = canvas.getContext('2d');
            ctx.drawImage( img, 0, 0 );
            var to = ctx.getImageData( 0, 0, w, h );
            var toData = to.data;
            
            for (
                    var i = 0, len = pixels.length;
                    i < len;
                    i += 4
            ) {
                toData[i  ] = (rgbI === 0) ? pixels[i  ] : 0;
                toData[i+1] = (rgbI === 1) ? pixels[i+1] : 0;
                toData[i+2] = (rgbI === 2) ? pixels[i+2] : 0;
                toData[i+3] =                pixels[i+3]    ;
            }
            
            ctx.putImageData( to, 0, 0 );
            
            // image is _slightly_ faster then canvas for this, so convert
            var imgComp = new Image();
            imgComp.src = canvas.toDataURL();
            
            rgbks.push( imgComp );
        }

        return rgbks;
    }

The black is needed as a base color. If the tint has very little red, green or blue then the image will end up being mostly black. This matches the light model- if there is very little red, green or blue light then the things around you will appear very black in real life.

To draw you then produce a spare canvas, and draw the black component first. To add the red, green and blue you set the 'globalCompositeOperation' to 'lighter', which adds the components to the canvas as they are drawn. Because we have separated out the components, we can now have complete control over how much of he component is used through manipulating the canvas' globalAlpha property.

    function generateTintImage( img, rgbks, red, green, blue ) {
        var buff = document.createElement( "canvas" );
        buff.width  = img.width;
        buff.height = img.height;
        
        var ctx  = buff.getContext("2d");

        ctx.globalAlpha = 1;
        ctx.globalCompositeOperation = 'copy';
        ctx.drawImage( rgbks[3], 0, 0 );

        ctx.globalCompositeOperation = 'lighter';
        if ( red > 0 ) {
            ctx.globalAlpha = red   / 255.0;
            ctx.drawImage( rgbks[0], 0, 0 );
        }
        if ( green > 0 ) {
            ctx.globalAlpha = green / 255.0;
            ctx.drawImage( rgbks[1], 0, 0 );
        }
        if ( blue > 0 ) {
            ctx.globalAlpha = blue  / 255.0;
            ctx.drawImage( rgbks[2], 0, 0 );
        }

        return buff;
    }

Finally you have your tinted image, and you simply draw it as usual.

    var img = new Image();
    img.onload = function() {
        var rgbks = generateRGBKs( img );
        var tintImg = generateTintImage( img, rgbks, 200, 50, 100 );
        
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "black";
        ctx.fillRect( 0, 0, 100, 100 );
        
        ctx.drawImage( tintImg, 50, 50 );
    }
    img.src = "http://example.com/my_image.png";

Don't store the black?

Rather then storing the black component within a canvas, you can generate it on the fly. This can be done by filling the spare canvas with a black rectangle and then drawing the image on top by setting the 'globalCompositeOperation' on the canvas to 'destination-in'. In this scenario, this will cause the canvas to apply the images alpha channel to the black rectangle on the canvas.

I personally found this a tiny bit slower, but it also reduces your memory footprint which is especially important for big images.

Skip the secondary canvas?

If you do store the black, then you can also just draw direct to your main canvas rather then using a secondary canvas. This is quicker then generating the tint image, but also means you can't cache the tint image.

This has the advantage of reducing the memory usage, but also increases the rendering time. For Play My Code I went with the decision to store the black and draw direct to the main canvas for small images, but use a secondary canvas and to generate black on the fly for larger images.

Firefox 4

The less intensive method of mixing colours also seems to be generally slow in Firefox. The example at the top runs at around 15fps in Firefox 4, but closer to 40fps in IE 9! Although it's usable in FireFox if you only have a couple of tinted images. Hopefully in time this will be sorted as hardware acceleration improves for browsers.

There is also a much faster method I've been building which avoids the use of lighter (and it's about 4 times faster), but so far only handles greyscale images (which is why I'm not using it). So stay tuned for that!

5 comments

Building A Game From Start To Finish With Play My Code – Part 3

Posted: by Seb under Game Development

And now, the conclusion of our three part tutorial on building a game from scratch using Play My Code. if you’re new to this tutorial, make sure you’ve read part one and part two before you begin. Find a reference for how your code should look so far here if you need one.

While the guts of our game are in place it still needs some icing to finish it off. Currently, when a player gets killed they would have to refresh the browser window to play again. This isn’t really acceptable (and more to the point, most players wouldn’t bother to do this more than once if at all!) so to fully round things off we need to add a simple state handling system so that the game will display its title screen, “Game Over” when the player dies, allow them to have another go afterwards and so on. Before we proceed, ensure you’ve read part one and part two first.

State of Play

As ever, lets stop and think about what we’re looking to do: we want a title screen, then the game itself when the player presses space, and then Game Over if the player runs into a bomb. From there another press of space would reset the game back to the beginning for another go.

The simplest way of achieving the above is to define a variable which holds the current state, and then divide the main loop into a series of if statements representing each state. For example, when the game begins your gameState variable could be assigned the value “title”, and then only the code inside an if( gameState == “title” ) statement would execute. Once the variable was assigned the value “game”, the code inside its respective if statement would run, and so on. Time to jump in:

Continue reading

no comments yet

Sound Support, Editor Improvements and More

Posted: by Joe under Play My Code Announcements

The past few weeks have seen a slew of brand new functionality and improvements on Play My Code. Here’s a summary of all the new features we’ve been rolling out:

Sound Support!

It’s been a long time coming, but audio support- our most-requested feature- has finally arrived! Check out this great audio example built by topHatStuff:

In the Project IDE, notice the ‘Images’ button has been changed to ‘Assets’- in there you can upload your sounds.

Asset Manager - Sounds

Once uploaded, you can then use a sound just like you would an image using the Sound class. It’s streamed on the fly when played, so the user doesn’t have to wait for it to download in its entirety.

Currently we only support MP3 and Wav, these being the only way to ensure good support across multiple platforms. Even then we have to fall back onto Flash to add mp3 support to FireFox, but this is handled seamlessly by the excellent SoundManager2 library (games will still work without complaint, albeit without sound, on a Flashless Firefox however).

New Editor

We’ve also begun using a new code editor within our IDE. Having previously used CodeMirror, we’ve moved on to Ace Editor.

New Code Editor

Recently merged with Mozilla’s Bespin/SkyWriter, Ace has much better support for very large files (over 100,000 lines long), works better under IE9, is more efficient performance-wise and also has a much cleaner system for setting syntax highlighting and indentation under the hood. This last feature has allowed us to fix lots of known bugs in one fell swoop.

Overall, Ace helps our IDE feel more like a “real” editor, being much more stable than our old one. It even features lots of very handy keyboard shortcuts, such as ctrl+d for delete line (cmd+d on Mac) and alt+up/down for moving selections vertically. Check out our new Editor Commands page for the full list.

Project Size Indicator

The Assets window within the IDE now displays an indication of how much space is remaining for a given project, under the “Remaining” tab on the right. Click it for a breakdown of how much space you have left, as well as to see how much is currently being consumed by your project’s graphics and sound.

Quby API Enhancements

We’ve also added block support for setFont, just like setColor has already.

    setFont( 'Arial', 100 ) do
        fillText( "Big Text!", 100, 100 )
    end
    // font changes back to original font here

The font will be altered solely for the duration of the block, and then reset to the original font when the block ends.

DrawRect, fillRect, drawCircle, fillCircle, drawEllipse and fillEllipse all now have x and y alignment parameters. Like…

    fillRect( x, y, width, height, :center, :right )

The x and y alignment parameters specify the point where the shape is handled from, similar to drawText/fillText. One can also pass in ‘true’ or ‘false’ to set whether alignment should be centered or not:

    // these two are the same
    fillRect( x, y, width, height, :left, :center )
    fillRect( x, y, width, height, false, true    )

Finally this is one of those necessary yet dull features: we’ve added the methods index and indexes to the Array class. Index allows you to find out the index of an array element, such as:

    // i gets set to 2
    i = [ 'a', 'b', 'c', 'd', 'e' ].index( 'c' )

You can also pass in a starting index to search from. In the example below it will begin searching from the third index in the array:

    // i gets set to 5
    i = [ 'a', 'b', 'c', 'd', 'e', 'c' ].index( 'c', 3 )

The starting index can also be negative, beginning the search from the end of the array:

    // i gets set to 5
    i = [ 'a', 'b', 'c', 'd', 'e', 'c' ].index( 'c', -3 )

The new version of indexes allows all indexes for a specific value to be obtained. This is useful if you have lots of duplicate values in your array. When used on the same example:

    // is is set to: [ 2, 5 ]
    is = [ 'a', 'b', 'c', 'd', 'e', 'c' ].indexes( ‘c’ )

Last, But Not Least

We’ve also made a range of other minor improvements to the site as a whole: the Quby parser is faster and more efficient than ever before (meaning faster & smoother gameplay), tasks such as uploading an avatar image are now more user-friendly than they were previously, and a long list of internal improvements and bugfixes have been made.

We’ll be rolling out even more improvements and new features over the next few weeks, so keep watching this blog or follow us on Twitter for the latest info.

no comments yet

Building A Game From Start To Finish With Play My Code – Part 2

Posted: by Seb under Game Development

This post is the second in our miniseries on building a browser game from start to finish using Play My Code. If you’ve yet to read the first part then we’d recommend you do so before continuing.

A recap: we got as far as creating the background and controllable character in the first part. This time around we’re going to add in the bombs & booty, making it a “real” game in the sense that the player can accrue a score and ultimately be killed. In the third and final part we’ll be adding a simple game state structure including Game Over and Title Screen messages to finish the game completely. Let’s begin:

Continue reading

2 comments

Building A Game From Start To Finish With Play My Code – Part 1

Posted: by Seb under Game Development

Below is my latest creation: Bombs ‘n’ Booty! Have a quick go: use the WASD keys to move, avoid the bombs, collect the valuable booty and see how high you can score.

Now, the reason I built this game was so I could guide both novice coders and the more experienced alike through the process of making a complete (if, simple) game using the Play My Code platform. While this post isn’t intended as a complete programming guide or reference, it will provide some context from which you can further your programming knowledge as well as giving you a simple codebase which you can tweak, extend and mod into your own creations. Strap yourself in, as we’re going to be running through this very quickly! Don’t worry if you come across something which you don’t understand, just keep going and all the bits will fall into place by the end.

Language Basics

Play My Code games are written using a language called Quby, which makes creating browser-based games fun and simple. The language’s simplicity means a beginner can hack out a basic game within a few hours, while being sophisticated enough to cater for more experienced coders. The Quby API provides lots of “helper” methods and functions out-of-the-box, geared towards game development, which aren’t present in most other languages used for browser-based game creation. Once finished, projects are compiled into native JavaScript, meaning they run blazing fast in all modern browsers without needing any plugins. If you want to know more, have a nose through the documentation- otherwise, read on…

Continue reading

8 comments