Tuesday, September 28, 2010

Multiplayer Online Gaming - Actionscript and Red Dwarf Server: Part 3

In the first two parts of this tutorial series I walked you through the standard RDS server tutorials.  Thus far we have not actually done anything with Actionscript, but the groundwork is down and we can finally get started.


If you havent already, now is the time to download FlashDevelop as well as Darkstar-as3.  The latest release of FlashDevelop will download the Flex SDK for you as well, make sure you dont skip this step in the FlashDevelop install.


First, you need to make sure to change the server protocol version to 4 by adding the following to the app.properties:
com.sun.sgs.impl.protocol.simple.protocol.version=4



Here is the Actionscript code we are going to implement.  If your already familiar with FlashDevelop and Actionscript you can just jump in and create an application that should be compatible with lesson 6 using this code:


 package   
 {  
   import com.alienos.sgs.as3.client.*;  
   import flash.display.*;  
   import flash.events.*;  
   import flash.text.*;  
   import flash.ui.*;  
   import flash.utils.ByteArray;  
   /**  
   * ...  
   * @author   
   */  
   public class Main extends Sprite   
   {  
    private var fieldFormat:TextFormat = new TextFormat('Arial', 12, 0x444444, true);  
    private var nameField:TextField = new TextField();  
    private var chatField:TextField = new TextField();  
    private var messageField:TextField = new TextField();  
    private var sgsClient:SimpleClient = null;  
    private var chatChannel:ClientChannel = null;  
    public function Main():void   
    {  
      if (stage) init();  
      else addEventListener(Event.ADDED_TO_STAGE, init);  
    }  
    private function init(e:Event = null):void   
    {  
      removeEventListener(Event.ADDED_TO_STAGE, init);  
      stage.align   = StageAlign.TOP_LEFT;  
      stage.scaleMode  = StageScaleMode.NO_SCALE;  
      createGUI();  
    }  
    private function createGUI():void  
    {  
      var title:TextField = new TextField();  
      title.defaultTextFormat = new TextFormat('Arial', 20, 0x444444, true);  
      title.text = 'Simple PDS Chat Client';  
      title.autoSize = TextFieldAutoSize.LEFT;  
      title.x = title.y = 5;  
      addChild(title);  
      nameField.x = chatField.x = messageField.x = 5;  
      nameField.y = 35;  
      chatField.y = 60;  
      nameField.defaultTextFormat =   
       chatField.defaultTextFormat =  
       messageField.defaultTextFormat = fieldFormat;  
      nameField.type =
       messageField.type = TextFieldType.INPUT;  
      nameField.border =  
       chatField.border =  
       messageField.border = true;  
      nameField.borderColor =  
       chatField.borderColor =  
       messageField.borderColor = 0x444444;  
      nameField.width =  
       chatField.width =  
       messageField.width = 300;  
      nameField.height =  
       messageField.height = 20;  
      chatField.height = 300;  
      nameField.background =  
       chatField.background =  
       messageField.background = true;  
      chatField.selectable = false;  
      nameField.text = 'Name';  
      messageField.text = 'Message';  
      addChild(nameField);  
      addChild(chatField);  
      addChild(messageField);  
      messageField.addEventListener(KeyboardEvent.KEY_UP, messageKey);  
    }  
    private function messageKey(evt:KeyboardEvent):void  
    {  
      if (evt.keyCode == Keyboard.ENTER) {  
       if (sgsClient != null) {  
         sendMessage();  
       } else {  
         sgsClient = new SimpleClient('localhost', 1139);  
         sgsClient.login(nameField.text, "password");  
         sgsClient.addEventListener(SgsEvent.CHANNEL_JOIN, channelJoin);  
       }  
      }  
    }  
    private function sendMessage():void  
    {  
      var buf:ByteArray = new ByteArray();  
      buf.writeUTFBytes(nameField.text + ': ' + messageField.text);  
      sgsClient.channelSend(chatChannel, buf);  
    }  
    private function channelJoin(evt:SgsEvent):void  
    {  
      chatChannel = new ClientChannel(evt.channel.name, evt.channel.rawId);  
      sgsClient.addEventListener(SgsEvent.CHANNEL_MESSAGE, channelMessage);  
      sendMessage();  
    }  
    private function channelMessage(evt:SgsEvent):void  
    {  
      addMessage(evt.channelMessage.readUTFBytes(evt.channelMessage.bytesAvailable));  
    }  
    private function addMessage(msg:String):void  
    {  
      chatField.appendText(msg + "\n");  
      chatField.scrollV = chatField.maxScrollV;  
    }  
   }  
 }  


If you havent used these tools before, here is a quick explanation of how to create the project:


Start FlashDevelop and create a new AS3 project (Project->New Project):






Copy and past the code above into Main.as.






Download the swc for darkstar-as3-0.9.8.swc and place it into the lib folder.   Right click the swc and select the "Add to Library" option.




Start the server and then compile and launch the client (F5 is the shortcut in FlashDevelop).  You should now have a client that can communicate with the server via channels.


Lets take a quick look at how the Actionscript code is accomplishing this.


The Main, init, and createGUI classes are establishing the visual layout.


The messageKey class is an event listener that is listening for keystrokes.  It checks to see if ENTER is being pressed, and if it is it connects to the server and sends the message via the sendMessage class.  Note that if a session is already established it skips the connection creation.


channelJoin is an event listener for SgsEvent that creates a new channel .  It adds another event listener that will be responsible for receiving message and decoding them


the channelMessage class actually receives the messages and reads the ByteArray into a string which it then displays using the addMessage class.


Well thats the basics of getting Actionscript to talk to RDS.  As you can see, this is a very bare bones system.  In my next tutorial I will introduce a more robust server framework and a complimentary Actionscript framework.

Multiplayer Online Gaming - Actionscript and Red Dwarf Server: Part 2

Welcome to Part 2 of my Actionscript and RDS server tutorial series.  In this tutorial I will run through the remaining RDS tutorials leading up to the client/server tutorial where I will subsitute a Flash client.


Lesson Two: Hello Logger!
Create a new java project called tutorial2 and dont forget to add the the sgs-server-api-0.10.1.jar reference library.


Add the code from the tutorial folder ( C:\projects\rds\sgs-server-dist-0.10.1\tutorial\src\com\sun\sgs\tutorial\server\lesson2 )


Copy over the META-INF folder and edit the app.properties for the HelloLogger name and listener properties.

 com.sun.sgs.app.name = HelloLogger  
 com.sun.sgs.app.listener = com.sun.sgs.tutorial.server.lesson2.HelloLogger  
 com.sun.sgs.impl.transport.tcp.listen.port=1139 

Build the Fat Jar, and either copy it into the RDS deploy folder or edit the sgs-boot.properties.  Run the "launch_clean.bat" and you should see the following:




Lesson Three: Tasks, Managers, and Hello Timer!
At this point I think you should have the hang of setting up these lessons, its more of the same again.  The result of this tutorial should look something like this:




Lesson 4: Hello Persistence!
This tutorial is a 3 parter, and its demonstrating persistence, something that my handy batch script is obliterating.  So, for this tutorial we will need a second batch script that doesnt wipe the backing database every time we start the server.  Go ahead and follow the same proceedure to create "launch_standard.bat".  This batch file contains only the second line of the "launch_clean.bat".


 java -jar C:\projects\rds\sgs-server-dist-0.10.1\bin\sgs-boot.jar  


Use the launch_clean script the first time you run each tutorial and then launch_standard to observe persistence.


The rest of this tutorial is straight forward enough.  You will have to juggle the app.properties as you add multiple versions of the HelloPersistence class, but other than that just remember to rebuild the jar each time.


Lesson 5: Hello User!


Ok, now we are getting past the super simple examples and moving on to network connectivity.  This tutorial requires a client as well as a server.  The java client can be found here:
sgs-c-client-dist-0.10.1.zip

For this tutorial you will need to make two projects, one for the client and one for the server.  The server follows the same setup as the last several lessons.  Once you have the server up and running, a client will be needed to make it work.


For the client, create another project "tutorial5_client".  You will need to add a different set of external jar libraries for the client.  Navigate to your c:\projects\rds\sgs-client-0.10.1\lib folder and just grab everything in the folder.  You wont need the META-INF folder used on the server.  Create the HelloUserClient class based off the sample code found in :\projects\rds\sgs-client-0.10.1\tutorial\src\com\sun\sgs\tutorial\client\lesson1


Once the client is ready, start the server via the normal script.  Then start the client through the Eclipse IDE, choosing to run the application as a Java Application.  See the image below:




You should get a result that looks like this:



The rest of the client tutorial should be straight forward, its just improving the server's layout but the setup is more of the same stuff.  Create your classes, modify your app.properties, recompile the fat jar and you should be good to go.


The HelloEcho lesson is fun to finally input some data and see the server send it right back.


Lesson 6: Hello Channels!


Well finally we are at the last lesson in the document.  This one is very similar to the last lesson, it will need a client and a server project.  Go ahead and implement it and see the channels in action.  The only slightly tricky part to this one is that the client includes the HelloUserClient class from Lesson 5, which isnt in the tutorial 6 folder.  Just grab it from your tutorial 5 client and the client should build.


Here is a look at the finished product:






Its important not to skip this lesson because in the next part of my tutorial I will be demonstrating this same server code with a Actionscript client.


Ready for more?  Click here for part 3

Multiplayer Online Gaming - Actionscript and Red Dwarf Server: Part 1

Hello and welcome to my multi part tutorial on how the basics of creating multiplayer Actionscript(Flash) games. The advent of casual gaming has really seen this type of game taking off, and more and more there is demand for simple but powerful solutions to creating online multiplayer games rapidly without sacrificing quality or scalability.  I think that Flash in conjunction with Red Dwarf Server(RDS) is an excellent solution to this need.  The open source nature of RDS also makes it much easier to get started with for programmers of all levels.


First, before we begin let me state that this is not intended to be a beginner level Actionscript or Java tutorial, and if you are not reasonably comfortable with the basics of these languages then you should probably start there instead.


The tools we will use for this are:
- FlashDevelop - http://www.flashdevelop.org
- Darkstar-as3 - http://code.google.com/p/darkstar-as3/
- Eclipse IDE for Java Developers - http://www.eclipse.org/
- Red Dwarf Server (ver 0.10.1) - sgs-server-dist-0.10.1.zip
- Red Dwarf Client (ver 0.10.1) - sgs-c-client-dist-0.10.1.zip
- Fat Jar Eclipse Plug-In - http://fjep.sourceforge.net/
- RDS Server Tutorial - RedDwarf ServerApp Tutorial
- RDS Client Tutorial - RedDwarf Client Tutorial


Setup
Start by downloading Eclipse, Red Dwarf Server and the the RDS Tutorial document.  The RDS tutorial is an open office format document, so you may also need to install that.


Extract Eclipse to c:\projects\eclipse, and red dwarf server and client to c:\projects\rds


Follow the install instructions for Fat Jar Eclipse Plug in, its very easy.


Now the easy part of my tutorial.. RTFM!  Read the Red Dwarf Server App Tutorial.  Ok, ok, I am not actually going to be so lazy as to just tell you to RTFM, but I am also not going to rewrite the excellent tutorials RDS has set up either.  What I will do here is summarize some tips for each tutorial that should help you along.  Once we get near the end of the tutorials we will be ready to start working with Flash as well.  Also, the document is slightly out of date, so hopefully I can help you catch the issues.  The RDS download also contains the source for the tutorials which should work just fine.  The source for these tutorials is in: sgs-server-dist-0.10.1\tutorial\src\com\sun\sgs\tutorial\server


So go ahead and get started by reading the first section of the tutorial.  Nothing much for me to add here, this is the basics of RDS and you will need to learn it to get anywhere with this technology.


Once you get to Lesson One:Hello World! you should have a good basic understanding of RDS.  Lets get started with the first lesson.  Navigate to c:\projects\eclipse and start eclipse.exe.  The first thing you will need to do is set a workspace.  Go ahead and set up a new workspace anywhere you like, I am going to use C:\projects\ws for the tutorial


Next, select the icon on the right side to "Go to the workbench"


Next lets set up a project for this tutorial.  
Name it "tutorial1" and select Next:


Now we need to add the RDS server library.  Choose the Libraries tab, and select "Add External Jars".  We need to add sgs-server-api-0.10.1.jar, which should be located in C:\projects\rds\sgs-server-dist-0.10.1\lib







Lets go ahead and add the class file.  As I said before, the BEST place to get the source for these tutorials is not the tutorial document but rather the RDS download.  So head into the RDS folder and open up the file located at:
C:\projects\rds\sgs-server-dist-0.10.1\tutorial\src\com\sun\sgs\tutorial\server\lesson1
 Open this in notepad or something convenient, we will just copy and paste the class into Eclipse.  In Eclipse, create a new class for the tutorial by the name of HelloWorld.  Put it in the package name com.sun.sgs.tutorial.server.lesson1


Copy and paste the code in.  I recommend you read it thoroughly, but since this is covered in the document I wont discuss the specifics.


Next we are going to set up a few items that I found to be helpful but are not covered in the tutorial document.  Finally I am giving you something useful!


Create a new folder called META-INF in your src folder.  Add a new file called "app.properties" to this folder.  Finally, add these lines to the file:


 com.sun.sgs.app.name = HelloWorld  
 com.sun.sgs.app.listener = com.sun.sgs.tutorial.server.lesson1.HelloWorld  
 com.sun.sgs.impl.transport.tcp.listen.port=1139


Next, use Fat Jar to package up the project, its available from the right click menu off the project folder:





Next we are going to make a simple batch file for launching our projects.  Add another file to the project root called "launch_clean.bat".  Eclipse doesnt know how to edit batch files, but thats ok. Just use the text editor:




Here is the contents of the batch file:
 ECHO Y | del C:\projects\rds\sgs-server-dist-0.10.1\data\dsdb\*.*  
 java -jar C:\projects\rds\sgs-server-dist-0.10.1\bin\sgs-boot.jar  


This batch will delete the RDS database each time you run it.  Of course this isnt something you want to do in production, but its fine for development.


The final step can be done in a couple of ways.  Either copy the fat jar into the C:\projects\rds\sgs-server-dist-0.10.1\deploy directory, or you can edit the sgs-boot.properties file and redirect RDS to your project folder to find the project.  The latter is how I generally managed the tutorials, but either should work.


If you are editing the sgs-boot.properties, all you need to do is set this property:
SGS_DEPLOY = C:/projects/ws/tutorial1


The final step is to launch hello world, do this by right clicking on the launch_clean.bat and selecting Open With -> System Editor


This will also set the default editor back to System, so you can just double click the bat to launch after this.  If everything went correctly you should see a DOS prompt something like this:






Whoo hoo!  We are on the road now!


Well, this concludes Part 1 of my tutorial.  Up next I will do a quick overview of the remaining tutorials leading up to the client tutorial where we get started connecting a Flash client.


Ready for more?  Click here for part 2