Tag Archives: flash

Cambridge University’s NRICH chooses TWILGO

NRICH TWILGO

Mesmotronic are proud to announce that, from December, NRICH TWILGO will be a regular feature of the mathematical games, problems and articles available for free at http://nrich.maths.org

Always on the lookout for new ways to enrich the experience of the mathematics curriculum for all learners, Cambridge University’s NRICH team chose TWILGO as the perfect way to introduce students of all ages to programming.

Can’t wait till December? The original TWILGO is still online and open to everyone at http://twilgo.com

What can you create in 140 characters?

Static initializers in AS3

Recently, several people have asked whether it’s possible to create some kind of constructor for static classes in ActionScript 3, and the answer is: yes!

The solution is  a static initializer. This is a block of code, surrounded by curly brackets but no function or var declaration, that runs the first time a property or method of a static class is called. Static initializers are called before any property value is returned or function executed, in the same way a constructor always runs before you can access the properties or methods or a regular class.

package
{
    public class MyStaticClass
    {
        // This is the static initializer
        {
            trace("Running static initilizer!");
            staticInitializer();
        }
        
        // We're calling a secondary method so we can use local variables
        static private function staticInitializer():void
        {
            var now:Date = new Date;
            baseColor = now.hours > 16 ? 0x000066 : 0x0000FF;
        }

        static public var baseColor:uint;
    }
}

Although it’s not strictly necessary to call a secondary method, Flash Player will throw an error if you declare local variables within the static initializer itself.

To prove that the static initializer is running first, simple trace out the baseColor property:

trace(MyStaticClass.baseColor);

If it’s after 4pm, this will result in the following output in the console window:

Running the static initializer!
102

Too good for 2.5… Mesmotronic Multiuser Server 3 is coming!

Mesmotronic Multiuser Server 2
Mesmotronic Multiuser Server 2.5 was supposed to be a stepping stone to 3, but as development progressed it became clear that all the cool new stuff being added would go far beyond a simple point-release.

So, we’ve taken the decision to cancel 2.5 and continue development towards a new multi-platform release: Mesmotronic Multiuser Server 3.

More information coming soon…

Get ready for Mesmotronic Multiuser Server 2.5

Mesmotronic Multiuser Server 2
The next major release of Mesmotronic’s real-time server solution has entered the final stages of development and has been handed to our crack team of testers to put it through its paces.

Mesmotronic Multiuser Server 2.5 makes it even easier to add push data and real-time interactivity to you Flash, Flex and AIR applications by enabling ActionScript developers to build client and server functionality using nothing more than their existing knowledge and an easy-to-use ActionScript 3 API.

Watch this space for further announcements.

Essential Eclipse plug-ins for Flash Builder 4 and Burrito

With the recent relase of Adobe Flash Builder 4, we thought we’d flag up the update URLs for a few of our favourite Eclipse plug-ins to save you having to hunt around for them.

To install plug-ins:

  1. Copy the appropriate URL to your clipboard
  2. In Flash Builder, select Install New Software… from the Help menu
  3. Click Add, paste URL in the Location field and click OK
  4. Select the plug-ins to install and click Finish

If you’ve spotted anything we’ve missed, add a comment or  tweet it to @mesmotronic.

Eclipse.org

This URL contains links to most of the plug-ins hosted on Eclipse.org, allowing you to add functionality like ANT, JDT (Java Development Tools) and PDT (PHP Development Tools). You’ll also need to add this URL to Flash Builder to enable you to install other plug-ins, like soapUI:

http://download.eclipse.org/releases/galileo/

Subclipse (SVN)

If you’re a regular user of version control, and you should be, the subclipse plug-in is essential:

http://subclipse.tigris.org/update_1.6.x

soapUI

For anyone who uses Web Services, soapUI offers a great way to view and test your services:

http://www.soapui.org/eclipse/update/site.xml

Android SDK

Now that you can develop application using AIR for Android, it could be argued that ADT (Android Developer Tools) isn’t necessarily essential, but if you’re looking to develop mobile apps for anything other than the latest handsets it’s definitely worth a look:

https://dl-ssl.google.com/android/eclipse/

TODO/FIXME

For anyone who makes regular use of the Tasks panel in FlashDevelop or Eclipse’s Java profile, this is a must.

You can download the plug-in here (requires manual installation).


	

Creating a simple HTTP proxy using PHP

Cross domain policy files, or rather a lack of them, are the bane of Flash and Flex developers’ lives. Whether it’s the Twitter API, data from Yahoo! Finance or one of any number of other data sources, the moment your SWF makes it to the web you’re faced with the same problem: Security Error!

The solution is to create a simple proxy on your server that can load the data for you and pass it to your application. If you’re using PHP, then this is about as simple as it gets:

// Too simple! (see comment below)
<?=file_get_contents($_REQUEST['url'])?>
<?php
$url = $_REQUEST['url'];
if (preg_match('/\b(https?|ftp):\/\/*/', $url) !== 1) die;
echo (file_get_contents($url));
?>

The preg_match ensures that the requested URL is valid and offers basic protection against anyone trying to maliciously access files on your server.

That’s it. Just paste that into a text file, save it as proxy.php and upload it to your server. You can then access any data you like simply by passing it a URL. Best of all, it works with both GET and POST, for example:

http://www.mydomain.com/proxy.php?url=http://blog.mesmotronic.com/index.php/feed

Happy proxy-ing!

Introduction to server-side applications for Mesmotronic Multiuser Server

Mesmotronic Multiuser Server 2
Server-side applications can add vital functionality to multiuser applications and games created using Mesmotronic Multiuser Server 2, including the ability to load and save files, communicate between rooms and applications, and push data to clients.

A server-side application is a standard ActionScript 3 SWF like any other, except that it cannot display any graphics and extends the MultiuserServerApplication class, rather than Sprite or MovieClip. Applications can therefore be created using any ActionScript 3 IDE, including Flex/Flash Builder, Flash CS3/4 and FlashDevelop.

In this tutorial, we’re going to create a very simple server-side application which sends, on request, a random colour to the client which the client will then apply to the stage. As usual, we’re assuming you have a reasonable working knowledge of ActionScript 3 and have Mesmotronic Multiuser Server installed locally, with the API added to your library path.

The first step in creating any new server-side application is to create a new document class which extends MultiuserServerApplication. Your initial class structure would typically look something like this:

package
{
    import com.multiuserserver.server.MultiuserServerApplication;

    public class RandomColourApp extends MultiuserServerApplication
    {
        override public function main():void
        {
            // Entry point
        }
    }
}

The main entry point is called immediately after the application property of your class (inherited from MultiuserServerApplication) has been initialized, enabling you to communicate with the outside world, and should be used in preference to a class constructor. Although we won’t be doing anything here in this tutorial, this is where you would normally configure your application and add any event listeners you may require.

By default, all calls made to the server by clients, via the MultiuserServerClient call method, will invoke public functions of your application class. So, to allow clients to request a random colour, we need to add a function called getColour:

package
{
    import com.multiuserserver.server.MultiuserServerApplication;

    public class RandomColourApp extends MultiuserServerApplication
    {
        override public function main():void
        {
            // Entry point
        }

        public function getColour():uint
        {
            return Math.round(Math.random()*0xFFFFFF);
        }
    }
}

Now that the function is in place, you simply need to publish your class in the usual way and copy the resulting SWF, RandomColourApp.swf, to a folder of the same name within the applications directory of Mesmotronic Multiuser Server. Based on the default installation folder, this would be:

 C:\Program Files\Mesmotronic\Mesmotronic Multiuser Server\applications\RandomColourApp\

Once copied, your application is ready to go.

Now, all we need to do is create a simple client application to test that our server-side application works (the elements which relate to the server call are highlighted):

package
{
    import com.multiuserserver.events.MultiuserServerEvent;
    import flash.events.IOErrorEvent;
    import flash.events.MouseEvent;

    public class RandomColourClient extends Sprite
    {
        public var client:MultiuserServerClient;

        public function RandomColourClient()
        {
            client = new MultiuserServerClient();
            client.addEventListener(MultiuserServerEvent.CONNECT, onConnect);
            client.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
            client.delegate = this;
            client.connect("localhost", 2040, "RandomColourApp", 10);

            stage.addEventListener(MouseEvent.CLICK, onClick);
        }

        public function onConnect(event:MultiuserServerEvent):void
        {
            trace("Connected!");
        }

        public function onIOError(event:Event):void
        {
            trace("Connection Error.");
        }

        public function onClick(event:MouseEvent):void
        {
            client.call("getColour", null, "setColour");
        }

        public function setColour(colour:uint):void
        {
            graphics.clear();
            graphics.beginFill(colour);
            graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
        }
    }
}

Publish the class above and you will find that every time you click on the stage it will change to the colour received from the server!

Obviously, this is just scratching the surface of what’s possible with server-side applications, but it should give you a good idea of how basic client-server interaction can be implemented.

We’ll be taking a look at more advanced functionality at a later date, but if you’d like to find out more in the mean time, there are several examples included with your Mesmotronic Multiuser Server installation (follow the link on your start menu), which are also available as a separate download.

Getting started with Mesmotronic Multiuser Server using ActionScript 3

We believe that Mesmotronic Multiuser Server 2 is the quickest, easiest way to create real-time multiuser and with the Adobe Flash Platform, including Adobe Flash, Flex and AIR, and if you haven’t already installed Mesmotronic Multiuser Server, you can download the latest version here.

This tutorial shows how to create a basic peer-to-peer application to track other users’ mouse positions using Mesmotronic Multiuser Server 2 and ActionScript 3 (AS3), so it’ll work regardless of whether you’re using Flash, FlashDevelop or Flex Builder. We’ll take a look at Flex/MXML and client-server applications at a later date.

We’re assuming at this point that you’ve already installed Mesmotronic Multiuser Server 2, made the ActionScript API available to your chosen IDE and have a reasonable understanding of AS3.

The first thing you need to do is create a new document class which extends flash.display.Sprite, let’s call it Main, and import the classes you’ll need to use the Mesmotronic Multiuser Server API:

import com.multiuserserver.client.MultiuserServerClient;
import com.multiuserserver.events.MultiuserServerEvent;
import flash.events.IOErrorEvent;

Next, declare an instance of the MultiuserServerClient class. Once instantiated, this will handle all of the communication with the other clients:

public var client:MultiuserServerClient;

You’re now ready to set up your connection by instantiating the MultiuserServerClient class and configure your connection. For this example, we’ll do everything in the class constructor, but the chances are you’ll want to do things like connect via a button in your own multiuser applications:

public function Main()
{
    client = new MultiuserServerClient();
    client.addEventListener(MultiuserServerEvent.CONNECT, onConnect);
    client.addEventListener(MultiuserServerEvent.CLIENT_DISCONNECT, onClientDisconnect);
    client.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    client.delegate = this;
    client.connect("localhost", 2040, "AS3Tutorial", 10);
}

The events we’re using are pretty self-explanatory: CONNECT is dispatched when you initially connect to the server, CLIENT_DISCONNECT when a client disconnects and IO_ERROR if there’s a problem with your connection.

The delegate property indicates where the functions you’d like to make available to other clients and/or the server live. In this case, we’re setting it to the current class.

The connect method has 4 required parameters: server name (or IP address), server port (2040 is the default), application name (this must be unique for each application you create) and the maximum number of clients that can be in each room at any give time.

In this example, we’re assuming that you’ll just want to test locally, but if you’d like to test over a network, simply change localhost to the name or IP address of the computer running Mesmotronic Multiuser Server.

Everything you need to connect to Mesmotronic Multiuser Server is now in place, so now we need to create the properties and methods to actually make something happen once you’re connected.

First, we import a the MouseEvent class:

import flash.events.MouseEvent;

Then we create the properties and methods we need to bring the application to life:

public var cursors:Array = [];

// Announce the connection and start to broadcast your cursor position
public function onConnect(event:MultiuserServerEvent):void
{
    trace("You've connected to Mesmotronic Multiuser Server!");
    stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}

// Remove the blobs when clients leave
public function onClientDisconnect(event:MultiuserServerEvent):void
{
    var cursor:Sprite = cursors[event.clientIndex] as Sprite;
    removeChild(cursor);
    cursors[event.clientIndex] = null;
}

public function onIOError(event:IOErrorEvent):void
{
    trace("Connection Error: is Mesmotronic Multiuser Server installed and running?");
}

// Broadcast your mouse position
public function onMouseMove(event:MouseEvent):void
{
    // The run method is used to call a function on 1 or more clients
    client.run("setCursorPosition", [client.info.clientIndex, mouseX, mouseY]);
}

// This is the function that clients call to let you know where their mouse cursor is
public function setCursorPosition(clientIndex:uint, cursorX:Number, cursorY:Number):void
{
    var cursor:Sprite;

    // Create a coloured blob to represent the client's cursor if it doesn't exist
    if (!cursors[clientIndex])
    {
        cursor = new Sprite();
        cursor.graphics.beginFill(0xCCCCCC/client.info.clientsPerRoom*clientIndex);
        cursor.graphics.drawCircle(0,0,10);

        cursors[clientIndex] = addChild(cursor);
    }

    cursor = cursors[clientIndex] as Sprite;
    cursor.x = cursorX;
    cursor.y = cursorY;
}

That’s it! Just publish the class in the normal way, open up a few copies of the SWF and watch in amazement as the blobs follow your cursor around the screen. It really is that easy.

For more information about the events, properties and methods of the MultiuserServerClient class, take a look at the API reference or browse through the examples included with your Mesmotronic Multiuser Server installation, a link to which can be found on your Start Menu.