Player.IO is the next version of the Nonoba Developer Tools.

More Features, No Branding, Integrates with Everything. Read more »

Getting started with the Nonoba Multiplayer API

Nonoba Multiplayer game basics

When you have a flash multiplayer game on the internet, there are several parts that you need: A website to host the game, the flash game itself, a server that the flash game can connect to, a program that runs on the server and handles the logic of the game and communication with the flash game clients, a chat for the players of a game to talk to each other in, and some sort of system where players can find and join and creates games.

With the Nonoba Multiplayer API, we take care of most of those things. Your game will be hosted on the Nonoba website, your multiplayer games will run on the Nonoba Game Servers, the communication is handled by the Nonoba Multiplayer API, and your game will automatically get a lobby and a chat. This leaves only two parts for you to develop: First, you will have to develop the flash part of the game, which we will call the client, and second, you have to develop the part that runs on our game servers, which we will call the server. To help you create these programs, there is a clientside API in Actionscript 3, and a serverside API in C# 2.0.

Although you can use any .Net 2.0 language such as Visual Basic 2005 or J# 2.0, we strongly recommend that you use C# 2.0, since all our example games are written in it, and since it is the .Net language that is most similar to Actionscript 3.

If you are unfamiliar with the C# 2.0 programming language, you can check out the following guides:
C# 2.0 Programming Guide
C# 2.0 Reference

Lobby

In the lobby for each game there is a common chat so that users can talk to each other and find people they want to play with. When a user creates a game, the Nonoba Game Server will create a new instance of your game, and redirect the user to a unique URL that represents that instance. Joining an existing game simply redirects the user to that instance's unique URL. When this happens, the user's web browser will load your flash game client, which will then automatically connect to the right game server and the right game instance.

When you develop your game locally, there will not be a lobby, and you will only have one instance of your game on the development server. Only when you upload your finished game to Nonoba will it get a lobby. The lobby functionality is included in the Multiplayer API, so you do not need to develop your own.

Chat

The clientside API will automatically include a chat in your game, and you must make room in your flash file for this. The chat will take up a minimum of 200 pixels on the right hand side, so sohould you for example want a game area of 400x400 pixels you should make your flash file 600x400 pixels large. The chat functionality is included in the Multiplayer API, so you do not need to develop your own.

Note that both the lobby and the chat will work even if you embed or upload your game to other 3rd party websites.

Client-server messaging

Your client and server will communicate via messages over the connection. The actual network code for this is handled and abstracted by the clientside and the serverside API so that on both ends there is a Message object, methods for sending a message to the other end, and event handlers that are called whenever a message is received.

All messages have a type and can have any amount of data attached, and you use the methods in the respective api to get and set the data so that your actual game logic can then act on it and perform the appropriate actions. The typical flow is that when one of the players does something in the game, that client sends a message to the server, it receives the message, performs some validation or calculations given the data, and sends out messages to the clients of the other players, updating them on what the first player did.

What will you need before you can get started?

To create multiplayer games using the Nonoba Multiplayer API you need Adobe Flash CS3 or above, Microsoft Visual Studio 2008 or above and an internet connection.

Should you not have a version of Adobe Flash CS3, you can download a 30 days trial here: http://www.adobe.com/go/BONQS, when the trial ends you will have to buy a version of Adobe Flash to continue to develop flash games.

You will also need a development environment for .Net, either Microsoft Visual Studio, or the free Microsoft Visual C# 2008 Express Edition which you can download here: http://www.microsoft.com/express/download/

Last but not least, you will need an internet connection while developing, as some of the modules used by our API are downloaded from our servers directly to ensure that they are always up to date.

Ok, I have all that. Lets make a new game!

If you haven't done so already, you need to download the newest version of the API. Simply go to the download section and get the newest version of the Multiplayer API. Make sure you're not downloading the ActionScript 2 & 3 API, that is only for single-player games.

When the API is done downloading, extract the files, then make a copy of the folder called NewGame to wherever you want your game to reside on your hard drive. We suggest you also rename the folder to the name of the game you are making. You will use this copy as a template for your first game.

Now open up the folder. In it you should find the following six files and folders:

Flash This folder contains all the files related to the client
Nonoba .NET Libraries This folder contains libraries the server needs, you should stay away from this folder.
Output When you compile your flash project or your Visual Studio project, the important files will end up in this folder.
Serverside Code This folder contains all the files related to the server
Flash.flp This is a Flash CS3 project file.
Serverside.sln This is a Visual Studio solution file

First you want to open and run the server, so double-click Serverside.sln and it should open in Visual Studio if you installed it correctly. When the solution has finished loading you can run it by pressing F5.

Now open up the Flash.flp file using Flash CS3, then hit CTRL+ALT+P. This will compile and run the flash project.

If everything worked as it should, you should now be connected to the server after entering a Username in the dialogue that pops up. You should also have a bunch of stuff showing up both in trace, and in the debug area of the server application.

To start up one of the other example projects like Fridge Magnets or DrawPad, you simply go trough the same process. Open the Visual Studio solution and start with F5, open the Flash project, and start with CTRL+ALT+P

The Flash.flp project

Lets first take a look at the flash project, and how everything fits together. In Adobe Flash, you might have to select Window->Project from flash menu to make the flash project view show. In this view you should see a project called MyGame containing the two files MyGame.fla and MyGame.as. Both of these files can physically be found in the folder Flash as described above.

MyGame.fla - This file will contain all your resources and frames should you wish to use such. You should also note that it contains two frames, and has the document class defined as MyGame.as

MyGame.as - This is the document class for your game, and will therefore contain most of your code. It looks like this:

package {
        import flash.display.MovieClip
        import flash.events.Event
        import Nonoba.api.*
        public class MyGame extends MovieClip{
               private var connection:Connection
               function MyGame(){
                       stop();
                       connection = NonobaAPI.MakeMultiplayer(stage);
                       connection.addEventListener(MessageEvent.MESSAGE, onMessage)
                       connection.addEventListener(ConnectionEvent.DISCONNECT, function(e){
                               gotoAndStop("error")
                       })
                       connection.Send("hello")
               }
               
               private function onMessage(e:Object){
                       var message:Object = e.message;
                       switch(message.Type){
                               case "hi":{
                                       trace("Got response from server on hello message");
                                       break;
                               }
                               case "welcometogame":{
                                       trace("Got welcome! - There are " + message.GetInt(0) + " other users in the game")
                                       break;
                               }
                               case "tick":{
                                       trace("Got Tick!")
                                       break;
                               }
                               case "delayedhello":{
                                       trace("Got Delayed Hello")
                                       break;
                               }
                               default:{
                                       trace("Got unhandled message > " + message)
                               }
                       }
               }
        }      
}

The first thing you should see is that we are importing the namespace Nonoba.api.*, this allows us to access all the code we provide for you in the client.

If you then look at the constructor method MyGame, you see that the first thing we do is calling stop() to ensure that the flash file does not just start looping endlessly between the two frames in MyGame.fla. The second thing we do is to initialize the Multiplayer API by calling NonobaAPI.MakeMultiplayer(stage). This initializes the game as a Multiplayer game and returns a Connection object which we can use to send and receive messages from the server. We also attach two event listeners to the connection object:

ConnectionEvent.DISCONNECT – This triggers if we are unable to connect or the connection is lost. In this case we simply just go to frame 2, which contains an “unable to connect message”

MessageEvent.MESSAGE – This triggers when we receive a message from the server. This event is bound to the method onMessage.

The last thing we do in the constructor is calling the method connection.Send(“hello”). This will send a message object with the type hello, and no data to the server. Note that even though we call this method before we can be sure we are connected to the server, the API will store such messages and send them to the server once the game connects.

As described above we receive the messages from the server using the method onMessage. The message is passed to onMessage as the attribute message on the event object e.

To handle the different kind of messages we simply just have a switch on Type. Also note how we read the amount of users online using message.GetInt(0) when the message type is welcometogame.

The Serverside.sln solution

When you open the solution you will see two projects called Test Server and Serverside Code. The project Test Server contains the actual test server that allows you to test your game locally and is provided entirely by us, so you don't need to touch it. The Serverside Code project is however where you write your server-side code.

In this project you should see the two files, Player.cs and Game.cs. Player.cs is pretty empty but Game.cs contains a lot of example code which interacts with the Actionscript client code we just discussed. It should look like this:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Threading;
using Nonoba.GameLibrary;

namespace ServersideGameCode {
        /// <summary>
        /// Each instance of this class represents one game.
        /// </summary>
        public class Game : NonobaGame<Player> {
                /// <summary>
                /// Game started is called *once* when an instance
                /// of your game is started. It's a good place to initialize
                /// your game.
                /// </summary>
                public override void GameStarted() {
                        // You can explicitly setup how many users are allowed in your game.
                        MaxUsers = 8;

                        // You can schedule a onetime callback for later. 
                        // In this case, we're sending out a onetime "delayedhello"
                        // message 10000 milliseconds (10 seconds) after the 
                        // game is started
                        ScheduleCallback(delegate {
                                Broadcast("delayedhello");
                        }, 10000);

                        // You can setup timers to issue regular callbacks
                        // in this case, the tick() method will be called
                        // every 100th millisecond (10 times a second).
                        AddTimer(new TimerCallback(tick), 1000);
                }

                /// <summary>
                /// Timer callback scheduled to be called 10 times a second in the AddTimer()
                /// call in GameStarted()
                /// </summary>
                private void tick() {

                        Console.WriteLine("Use Console.WriteLine() for easy debugging");

                        RefreshDebugView(); // update the visual debugging view
                        Broadcast("tick");
                }

                /// <summary>
                /// This message is called whenever a player sends a message into the game.
                /// </summary>
                public override void GotMessage(Player player, Message m) {
                        // here we're sending "hi" back to any user sending in "hello"
                        switch (m.Type) {
                                case "hello":
                                        player.Send("hi");
                                        break;
                                
                        }
                }

                /// <summary>When a user enters this game instance</summary>
                public override void UserJoined(Player player) {
                        // send a message with the amount users in the game
                        player.Send("welcometogame", Users.Length); 
                }

                /// <summary>When a user leaves the game instance</summary>
                public override void UserLeft(Player player) {
                }

                /// <summary>
                /// This method can be used to generate a visual debugging image, that
                /// will be displayed in the Development Server. 
                /// Call RefreshDebugView() to update image.
                /// </summary>
                public override Image GenerateDebugImage() {
                        // example code creating a 100x100 image
                        // and drawing the string "hello world" on it.
                        Bitmap image = new Bitmap(100, 100);
                        using (Graphics g = Graphics.FromImage(image)) {
                                g.FillRectangle(Brushes.DarkGray, 0, 0, 100, 100);
                                g.DrawString("Hello World",new Font("verdana",10F), Brushes.Black, 0,0);
                        }
                        return image;
                }
        }
}

The primary methods you want to look at here are GameStarted(), UserJoined(), UserLeft() and GotMessage().

GameStarted() – This method is called when a new instance of your game has been created from the lobby. Here you want to write the code that needs to run when your game initializes. In the provided example code we explicitly set the maximum amount of users in one game to 8 with the line MaxUsers = 8, and we set up some example timers to show the functionality.

UserJoined() – This method will be called every time a user joins the game, with the Player object representing the user that joined.

UserLeft() – This method is called when a user leaves the game, and is supplied with the Player object representing this user.

GotMessage() – This method is called when a client sends a message to the server, with the Player object of the sending user, and a Message object containing the message type and contents.

Beside the above methods, the NewGame example also contains the methods tick, and GenerateDebugImage.

tick – This is an example of how you would make something execute on the server with a specific interval. The timer is initialized in the GameStarted method where we add a timer with a callback that takes the name of this method as an argument.

GenerateDebugImage – Allows you to generate a debug image for your game. This is really helpful if you need to debug the state of your game on the server as you will be able to visualize your game state using the drawing tools bundled with C#.

To get this method to execute and update the server interface correctly you simply call the method RefreshDebugView. In this case RefreshDebugView is called from the tick method, but you could call it in GotMessage, UserJoined, or any of the other events.

As you can see from the above, the NewGame example contains a lot of example code which you most likely do not need. We simply suggest that you use this project as a template, comment out all the parts you do not need and work forward from there.

Publishing your game.

So, you made the best multiplayer game ever and want to share it with the world?

Well, the first thing you should do is go back and test it some more. We like well tested games, and if your game uses too much memory or cpu per player online, we will detect this and take off your game automatically, so make sure your game isn't wasting resources needlessly.

Done testing? Cool!

When you compile the server or publish your flash project, the generated files will end up in the folder called Output found in your project folder. Having compiled both the client and the server you should find yourself the lucky owner of a .dll file and a .swf file.

Next, go to the Upload Game page and in the Game Files section, supply the .swf file in the Flash file field, and the .dll file in the Game Dll field. As with single-player games, you of course need to supply a name, description and an icon. We recommend that you also set the status of your first version to Under Development so you and your friends can test your game before making it available for everyone.

When you finally have a version that works great and set the state to Beta or Full Release, it should be available to everyone on Nonoba. If you want to put your game on other gaming portals or your own website, simply go to the game page and use the embed html there, or download the wrapped flash file from “Download this file for your website” and upload that to the other gaming portals.

About Fltron | Latest News | FAQ | Support & Contact | Privacy Policy
Copyright ©2007-2010 Fltron™ - All rights reserved.
15,6001ms on NONOBA-WEB2
Support & Contact | Privacy Policy