Showing posts with label SmartFoxServer. Show all posts
Showing posts with label SmartFoxServer. Show all posts

Wednesday, November 2, 2011

20 Clicks Game Tutorial

{Coding and coding explanations are currently being added. Adding a little bit each day, until this tutorial is finally completed. - Will be updated again on the afternoon of July 21st, 2012.}
{Last Updated: July 20, 2012}

Hey everyone!

It's been a while since I last updated this blog, but anyway I'm going to go ahead and start this tutorial because it might be a little long. I'm going to try to explain it as much as possible. Let's begin.

In this tutorial, we will only be using ActionScript 2.0 coding on the client side. No extensions will be used in this tutorial (which is why the coding isn't the best). The main goal of this tutorial will be to create a two-player game in which the players will compete to click a button faster than the opponent. As a simple name for the game, I named it "20 Clicks." The name should be self-explanatory really.

So, to begin this game, create a new Flash ActionScript 2.0 document.

The next thing you need to do is create a user interface that contain all of the following:
  • Username field (input text box) - Instance name: nick
  • Two regular button symbols that will serve as option buttons - Instance names: hostBtn and joinBtn
  • MovieClip to tell the user which option button is selected - Instance name: chosenMC
  • Continue/Login button - Instance name: loginBtn
  • Any other little details you would like to add.
Here is what my finished user interface looks like:

Please excuse the bad quality, I resized a few things and it turned out to not look it's best and I didn't want to recreate it since this is just a quick example for you to look at, and possibly make it better.
Anyway, after you create the user interface, we will start coding the first frame in our movie. So, click on the first frame and open up your actions panel by pressing F9, or by going to Window -> Actions on the toolbar. Once you open the actions panel for the first frame, type this coding into your actions:
import it.gotoandplay.smartfoxserver.*;

stop();

_global.gameType = "Host";

_root.chosenMC._x = _root.hostBtn._x;
_root.chosenMC._y = _root.hostBtn._y;

var sfs:SmartFoxClient = new SmartFoxClient();
sfs.debug = true;
sfs.connect("127.0.0.1", 9339);
sfs.onConnection = function(success:Boolean) {
 if (success) {
  _global.serverConnected = true;
 } else {
  _global.serverConnected = false;
  _root.gotoAndStop("ConnectionFail");
 }
}
sfs.onConnectionLost = function() {
 _global.serverConnected = false;
 _root.gotoAndStop("ConnectionFail");
}

sfs.onLogin = function(resObj:Object) {
 if (resObj.success) {
  _global.myName = resObj.name;
 } else {
  _root.gotoAndStop("LoginError");
 }
}

sfs.onRoomListUpdate = function(roomObj:Object) {
 this.autoJoin();
 _root.gotoAndStop(_global.gameType);
}


Now, I would like to point out a few things in the coding.
  • On line 12, you will have to substitute the ip address 127.0.0.1 with your own server's ip address, unless you are testing the game locally.
  • The application does not tell the user if the server is connected, it just tells the user if the server cannot connect. - I am pointing this out because if you test this with your server off, it will be about 5 - 15 seconds before you really know whether or not the server has connected. You can implement this into the game yourself if you want.
Now that we have the first frame coded, I will explain the coding, line by line. Each line of explanation corresponds to each line of the coding above.
  • Line 1 - Imports the SmartFoxServer API.
  • Line 3 - Makes sure the movie stops on frame 1 and doesn't continue to play through all the frames.
  • Line 5 - Sets the gameType variable to the default, "Host".
  • Line 7 and 8 - Sets the chosenMC x and y positions on the stage in the same place the hostBtn resides.
  • Line 10 - Creates a new SmartFoxServer instance.
  • Line 11 - Turns the SmartFoxServer debugging on.
  • Line 12 - Connects to server 127.0.0.1 on port 9339. Change 127.0.0.1 to your server, unless you are playing the game locally.
  • Lines 13 through 20 - The sfs.onConnection handler is called when SmartFoxServer connects or fails to connect to a server. This function in our game basically sets the serverConnected variable to true if we connect successfully, and if we cannot connect to the server, it sets the variable to false and gotoAndStops at the frame, "ConnectionFail".
  • Lines 20 through 24 - The sfs.onConnectionLost event is called when a connected server gets disconnected for any reason, besides logging out. All we do here is set the serverConnected variable to false and gotoAndStop on the "ConnectionFail" frame.
  • Lines 26 through 32 - The sfs.onLogin event is called when we send a login request. If the login is a success, we set myName to our username. On the other hand, if we aren't able to login for some reason, we gotoAndStop on the "LoginFail" frame. (Eh, not the best way to handle this event. Probably just me being too lazy at that event. Lol.)
  • Lines 34 through 37 - The sfs.onRoomListUpdate event is called when we request the room list from the server. Since we are not using a custom login extension, the room list is requested automatically. When the room list is updated (populated) here, we join the room in the config.xml file with the attribute of autoJoin. autoJoin will be equal to true, obviously. Once we send the this.autoJoin request, we go ahead and go to the frame that the user has selected (aka, what the gameType variable contains).

The hostBtn button actions should contain this:
on (release) {
 _global.gameType = "Host";
 _root.chosenMC._x = _root.hostBtn._x;
 _root.chosenMC._y = _root.hostBtn._y;
}


The joinBtn button actions should contain this:
on (release) {
 _global.gameType = "Join";
 _root.chosenMC._x = _root.joinBtn._x;
 _root.chosenMC._y = _root.joinBtn._y;
}


That coding should be self explanatory. :P

Another thing we have to code is the Continue/Login button, so let's do that now. Here is the coding I used in my example:
on (release) {
 if (_global.serverConnected) {
  _global.myName = _root.nick.text;
  _root.sfs.login("20CLICKS", _global.myName, null);
 }
}


Here is the button coding explanation:
  • Line 1 - Sets up the coding to be called when the button is released.
  • Line 2 - Basically saying "if the server is connected"...
  • Line 3 - Sets myName variable to equal the username entered into the text box.
  • Line 4 - Sends the SmartFoxServer login command so the user will login to the zone "20CLICKS", with the username entered into the text box, with no password.
  • Line 4 - Closes the if statement.
  • Line 5 - Closes the on (release) handler.

Now, go ahead and create another frame in our file. This frame will be used to create a game so that someone else can play it with you. In order to make this work correctly, you have to make a few new symbols and a text box on this frame. Here is a list of things you need to put on this frame:
  • A start game button - Instance name: startGameBtn
  • A "game name" input text box - Instance name: gamename
  • Give this frame a name of "Host" without the quotations
Those are the only two symbols you will need in this frame. Here is a picture of what my second frame looks like:

So, now that the second frame is setup and both of the symbols have been added, it's time to start coding this part of the game. The first part we will code is the frame. Here is the coding you will need to put on the second frame:
import it.gotoandplay.smartfoxserver.*;

sfs.onRoomAdded = function(roomObj:Object) {
 if (roomObj.name == _root.gamename.text) {
  _root.sfs.joinRoom(roomObj.name);
  _root.gotoAndStop("GameV1");
 }
}

sfs.onJoinRoom = function(roomObj:Object) {
 var roomVars:Array = new Array();
 roomVars.push({name: "player1", val: _global.myName});
 roomVars.push({name: "player2", val: "..."});
 _root.sfs.setRoomVariables(roomVars);
 _root.sfs.sendPublicMessage("I have entered the room.");
}


Here is the coding explanation:
<CODING EXPLANATION>

Now we have to code the start game button. The start button will create a new room on the server so that when someone else wants to join your game, they will type your game name, and they will join into your game. So, here is the coding you will need to place on the start button:
<CODING>

And here is the coding explanation:
<CODING EXPLANATION>

After you put the coding above into your start game button, you are done coding the second frame and it is time to move onto the third frame! So, here are the new symbols you will need for this frame:
  • A game name (to join) input text box - Instance name: gamename (just like the second frame)
  • A join game/start game button - Instance name: startGameBtn (again, just like the second frame)
  • Give this frame a name of "Join" without the quotations
Those are the only two symbols you need to put in the third frame for this game. Also, I am having you put the same symbols as the second frame onto the third frame because the coding is different but if you want, you can just copy and paste the second frame symbols onto the third frame and just change the coding. Here is what my third frame looks like:

So, with that being said, let's code the third frame:
<CODING>

And here is the coding explanation:
<CODING EXPLANATION>

Now you are ready for one of the easiest parts in this tutorial - creating the error messages. The first thing you will need to do is create another frame (this should be frame number four). The only special thing you will have to do to this frame is give it a name. Make this frame's name be "ConnectionFail" without the quotation marks, of course. Once you name the frame, all you have to do is use the text tool and create a static text box with an error message saying that the application could not connect to the server or the connection was lost. Here is what my error message said on this frame:
  • Could not connect to the server, or the connection was lost!
  • Give this frame a name of "ConnectionFail" without the quotations
Here is a picture of what my fourth frame looks like:

Now you are done with this frame. No coding is required is this frame. I bet you think the easy part is over now, right? Wrong. You now have to make another frame very similar to this, but with a different frame name and error message. So go ahead and create another frame (this should now be frame number 5) and give it a frame name of "LoginError" (and again, without the quotes). The only thing you should have to write in this frame (static text box using the text tool) is a simple login error message. I kept mine very simple with writing the following error message.
  • Login error!
  • Give this frame a name of "LoginFail" without the quotations
Here is a picture of my fifth frame:

Finally, now that we have most of the frames setup, it's time to create the actual frame that our users will be playing the game in. So, go ahead and make a new frame. This frame isn't required to have a name.
Okay, now that the frame has been made, let's go ahead and create the symbols. The symbols I used in my game are listed as follows:

  • A dynamic text box that will be used to show how many times you have clicked the object. - Instance name: myScore (Somewhere around this box, you can put a static text box letting the user know this is their score.)
  • A dynamic text box that will show how many times your opponent has clicked the object. - Instance name: theirScore
  • A dynamic text box that will show your opponent's name. - Instance name: theirName (Put this somewhere around the theirScore dynamic text box so that you know who your opponent is.)
  • A button, serving as the object being clicked to increase your score. - Instance name: clickBtn
Just a reminder: This is frame number six!

Here is what frame number six looks like on my game:

In the picture above, I started a game on 2 different clients, just to show how the system will work.

But, before the system works, we need to get to coding it! So, to code this part of the game, we first need to open up this frame's actions panel by going to Window -> Actions, or by simply pressing F9 on your keyboard.
Once the actions panel has been opened, enter in the following coding:
<CODING>

And, here is the coding explanation:
<CODING EXPLANATION>

  • Make 2 more frames after all that. Give them the names of "winner" and "loser". In the frames, Put some text on them saying whether or not the user won the game.

Now that the coding has been posted and explained, we only have two things left to do before it's time to launch the game! Those two things are make two more frames. Once you make the two frames, name one of them "winner" and the other one "loser", both without the quotes. Once you do that, just put a little static text box on each one of them and fill them with some text saying "Winner!" or "Loser!" on them, and you're done...on the client side. The very last thing we have to do is add the zone into the config.xml file, which is located in the {SFS-Installation}/Server/ folder. Open the config file in any text editor (preferably Notepad++ or regular Notepad. I don't suggest using WordPad because it alters the encoding of the file sometimes.). Once the config file is opened up, add this coding somewhere in the <Zones> tag, but DON'T add it anywhere inside a <Zone> tag, as that means you are trying to add a zone inside another zone, which obviously will cause an error:
<CODING>

What that coding does is create a new zone, "20CLICKS", with a room named "Main", which is what room you automatically join when you press the continue button after you type a username on the first screen. That's all the coding does.

Finally, now that I'm done with this long tutorial, it's time for you all to test out the application in action! To test my game, <LINK HERE>.

Also, now this tutorial has been published, I can get to other specific user-requested tutorials. I have cleared all of the comments except for one. The one comment I have not cleared is about a string/raw protocol extension. Basically, just another simple extension example. I really want to do this tutorial next because I haven't done much in the past with string extensions, and this might be a little fun to write a tutorial on it. Plus, it's way faster than the regular XML protocol, and that's really useful if you plan on running a big game with many users online at the same time.

Source File: Download
Config File: Download

Wednesday, July 6, 2011

SmartFoxServer Tutorial: How to Make a Virtual World / MMO - Part 2 (1): Logging Into the Game From a Database


The SQL coding is in the video description on YouTube (as well as the source code), so in case you don't want to go to YouTube to get the SQL code, here it is:

CREATE TABLE MMOUSERS(ID INT AUTO_INCREMENT PRIMARY KEY, USERNAME VARCHAR(20) NOT NULL UNIQUE, PASSWORD VARCHAR(255) NOT NULL, EMAIL VARCHAR(60) NOT NULL DEFAULT '', COINS VARCHAR(9000) NOT NULL DEFAULT '5000', INVENTORYLIST VARCHAR(9000) NOT NULL DEFAULT '', SAVEDITEMS VARCHAR(9000) NOT NULL DEFAULT '', ITEMSON VARCHAR(9000) NOT NULL DEFAULT '', ISBANNED VARCHAR(3) NOT NULL DEFAULT 'No', WARNINGS VARCHAR(4) NOT NULL DEFAULT '0', ISMODERATOR VARCHAR(3) NOT NULL DEFAULT 'No');

Tuesday, June 7, 2011

SmartFoxServer Tutorial: How to Make a Virtual World / MMO - Part 1: Connecting to the Server

For part two, hopefully it will be a voice tutorial if I can get my microphone to work correctly. Anyway, enjoy this video!

Thursday, May 5, 2011

Future Updates - Voting Now Closed!

Hey everyone,

Due to the fact that I haven't had enough time recently to work on new tutorials, I'm posting two polls below so you can request a series of tutorials, which will let me stay on one specific topic and create more tutorials in a faster time.







So, be sure to vote on the polls above and I'll check out the results soon and start working on the series of tutorials that the majority of the voters select.

Wednesday, March 23, 2011

SmartFoxServer Tutorial: Moderator Message Tutorial

Hello everyone.

To start off this post, I'm going to tell you this: I plan to start updating this site much more as time passes by. I'd also like to apologize for not posting this tutorial sooner than I had expected.

Anyway, let's just jump right on into the tutorial.

In this tutorial, I'll be showing you how to make a "Mod Message" system. I will be using SmartFoxServer objects again because some people requested that in the "Mod Magic" tutorial I did not to long ago.

So, the first thing I want to tell you is that I'm using the SmartFoxSerer avatarChat file for this tutorial, but you can use any file you want. So, let's go ahead and open up the file.

The next thing you will want to do is to skip straight into the "chat" frame (on the avatarChat.fla example file) or whatever frame your users will interact with each other and open up the coding for that frame.

Now, in this area (at the very bottom of all the other coding), we are going to add this coding into our file:

smartfox.onObjectReceived = function(obj, sender) {
if (_global.myName == obj.toUser) { //Only if my name matches the specified one, do the actions below
_root.modMsgMC._visible = true;
_root.modMsgMC.modMsgText.text = obj.myMsg;
}
}


We are also going to go right under that and make a new function named "sendModMessage." So, in order to do that, we need to add this coding under the smartfox.onObjectReceived handler:

function sendModMessage(toUser, myMsg) {
if (toUser != _global.myName) { //If specified user doesn't have my name then
var obj:Object = {}; //Create a new object
obj.toUser = toUser; //Set the .toUser parameter on the object
obj.myMsg = myMsg; //Set the .myMsg parameter on the object
_root.smartfox.sendObject(obj); //Send the object to all users in room
trace("The mod message has been sent to " + toUser + ".");
}
}

Now, if you tested your movie right now, you would see that nothing has changed. So at this moment, adding all that coding hasn't been really useful yet. It's time to change that and tie all that coding together. To do that, first we need to make a button to call the 'sendModMessage' function. You can give the button (or movieclip) any instance name you want.


Now that something is calling the function, we need some visual evidence that it is really being called. So, the next thing to do is to create a movieclip and give it the instance name of 'modMsgMC'. Inside that movieclip, go ahead and create a dynamic text field which will be used as the actual 'message' part of the 'mod message'. Give this text field an instance name of 'modMsgText'.


After you do that, test your movie and you should see that the moderator message is working completely fine.

Now, currently, as you can see from the file your making, the user is being defined by you and cannot change, as well as the message. So, my next objective is to show you how to alter the coding so you can type in the user's name and the message to send to them.

The first the you have to do is create two text fields on the stage. Give them instance names of 'sendTo' and 'msgToSend'.


Now, once that is done, just open up the button coding which calls the sendModMessage function, and change it to this:

on (release) {
_root.sendModMessage(_root.sendTo.text, _root.msgToSend.text);
}

Test your movie with TWO instances, and you should see your moderator message working fine. I didn't show you how to add a close button to the moderator message, but a simple one could have this coding:

on (release) {
_root.modMsgMC._visible = false;
}

Well, that's all for this tutorial! Be sure to request more, and as usual, if you have any questions about this tutorial, feel free to leave a comment!

NOTE 1: It is required that you test this movie out with two different clients, because if you test it with one and send it to your own username, nothing will happen. When you send an object, the server sends it to everyone in the room except yourself.

Source File: Download

Tuesday, March 8, 2011

SmartFoxServer Tutorial: How to Stop Walking on Walls (How to Set Walking Parameters)

Hey everyone.

In this tutorial, as you can most likely tell from the title, I'm going to explain one way to stop people from 'walking on walls', or other places the characters shouldn't be able to walk.
The coding is quite simple to understand in my opinion, but might not be for an absolute beginner. Anyway, shall we get started?

The first thing I did was open up the Flash file, in which for me is the SmartFoxServer avatarChat example file that they provide you with when you download the program.
Once it is open, I quickly skimmed over the coding once again to figure out one quick and easy approach to do this. Anyway, someone once told me (when I was new to SmartFox), that one method to do this was to make the walls unclickable.

So, in a way, we will do just that. So for this method, we are first going to take a look at SmartFoxServer's original coding and alter it just a little.

Take a look at the myMouse.onMouseDown function. Let's go ahead and delete the if (px.......) statement (as well as it's closing bracket), BUT DO NOT DELETE THE CODING INSIDE THE IF STATEMENT, and now test your movie.

You should move somewhere everywhere that you click your mouse. That's not the best thing to do, considering that most games have buttons in them. You may not want your character to walk when the button is pressed. Some people (like me) thinks that is a little annoying. Keep the if statement out of the coding anyway though.

Anyway, now it's time to add in our own coding. What we need to do is to add a function. Add this coding to the very bottom of your frame coding:

function isWalkable(canWalk:Boolean) {
if (canWalk) {
_global.isBusy = false;
useHandCursor = false; //This line is optional!
} else {
_global.isBusy = true;
}
}


Once the coding is added, if you test your movie, you should see nothing has happened since the first time you tested your movie. So, now that we have a function, we need to add some coding somewhere to actually make the call to the function.

So, what you should do now, is create movieclips as either the ground or the wall and make the calls to the function when the movieclip is either hovered, or when you move your mouse out of the selected symbol.

What I did was use a movieclip as the ground and add this coding to it:

on (rollOver) {
_root.isWalkable(true);
}
on (rollOut) {
_root.isWalkable(false);
}


Well, now that you have done all that, you can now test your movie. You should be able to click on your movieclip and see your avatar move to the desired place you have clicked.

NOTE 1: This is not the 'best' method to do this as I'm almost sure it will have a couple of glitches in it somewhere along the line. After reading this, if not before, I'm sure you can come up with a way better method for this, as this is mainly for the beginners.

NOTE 2: In my source file, I used the big gray space on the left for my 'ground'.

If you have any questions or comments, feel free to leave them on this post and I will reply to them as soon as I get a chance to!

Source File: Download

Thursday, March 3, 2011

SmartFoxServer Tutorial: Dynamic Room Creation

Hey everyone!

As you can tell from the title of this post, this tutorial is going to be on dynamic room creation. So, with dynamic room creation, you are able to create new rooms straight from the client, without even restarting the server, unlike adding rooms from the config.xml file.

One disadvantage of creating rooms from the client is that the room is not persistant. To make the room persistant, you would have to use an extension, which isn't all on the client, more on the server than the client. Anyway, let's begin with this short and fast tutorial.

The first thing your going to want to do in this particular tutorial is to go ahead and create the function for our coding. To do this, open up the chat frame coding (I'm using the avatarChat example file) and add this coding to the very bottom of the frame:

function createDynRoom(rName, rPass, rMax) {
var rObj:Object = {};
rObj.name = rName;
rObj.password = rPass;
rObj.maxUsers = rMax;
_root.smartfox.createRoom(rObj);
}


Now, that's all for the frame coding. So now we have to figure out a way to call the function. So, as you can see from our function, we need three parameters. So what I did was create three input text boxes and give them an instance name of newRName, newRPass, and newRMax.

Now that we have our text fields setup, we can create a button to actually call the function and execute it. So, make a button (or movieclip as these symbols can both contain button events), and add this coding to the button:

on (release) {
_root.createDynRoom(_root.newRName.text, _root.newRPass.text, _root.newRMax.text);
}


Also, just in case you got confused on what all to add to the stage, here is a picture of what I added to my avatarChat example file:


So, that's basically all you needed to add. Once you test your movie, you should see that it works!

NOTE 1: If the new room is empty, it might delete itself (I'm not sure if this is the correct way to say it), but I do know that if no one is in the room and you logout and login again to the avatarChat example file, the room is deleted by itself.

NOTE 2: When the smartfox.createRoom() command is called, I believe it fires the smartfox.onRoomAdded handler.

Source File: Download

Monday, February 28, 2011

SmartFoxServer Tutorial: "Mod Magic" Tutorial (Sending Objects)

Hello everyone!

I'm finally back to posting as you can see. I've been really busy with a game I'm working on and other things so I haven't had time to check the blog. Anyway, let's get started on the "Mod Magic" tutorial, or as I like to call "Mod Magic", SmartFoxServer objects.

This technique is very simple to learn, and I'm going to try to explain what each line does carefully enough so that a beginner can understand it, much like the SmartFoxserver Docs already does. Anyway, let's begin now.

First off, I'm using the provided SmartFoxServer avatarChat example file for this tutorial, just like all my other tutorials. So, open your Flash file up and go to the frame you want to add your Mod Magic and open the actions for that frame.

On the SmartFoxServer avatarChat file, I went to the chat frame and added this coding at the very bottom of all the other actions in the movie:

_root.showM1._visible = false;//Hides magic at start
function doMagic(magicName:String) {
var sfsObj = {}; //Makes new object
sfsObj.magicName = magicName;//Adds to object
_root.smartfox.sendObject(sfsObj);//Sends object
if (magicName == "magic1") {//Shows on sender's side
_root.showM1._visible = true;//Shows on sender's side
}//Shows on sender's side
}
smartfox.onObjectReceived = function(o:Object) {
if (o.magicName == "magic1") {//If magicName == magic1
_root.showM1._visible = true;//Show the mod magic to other people, not you
}
}


Now, the first line should tell you that we need to create a symbol in our Flash file. So, what I did was create a very simple rectangle shape and wrote some words on it and made it a movieclip by selecting it and converting it to a symbol by right clicking and choosing the "Convert to Symbol..." option. I gave it the instance name of "showM1", which, for me, stands for "showMagic1."


Now, the next thing to do is to create the doMagic() function, which basically perfoms the magic on the sender's side, then send the magic to all the other clients. So, now we need to create a button or movieclip to call the function. I chose a button. On the button I added this coding:

on (release) {
_root.doMagic("magic1"); //Calls function
}


The next and final thing to do is to setup the smartfox.onObjectReceived handler, which is in the coding above. So now you are able to test your movie. You should be able to see that when a user clicks the button, it shows your "Mod Magic."

NOTE: When the smartfox.sendObject() command is called, since your user is the sender of the object, the object will not be broadcasted to you, so you have to make a code so it shows the mod magic on the sender's side as well, which is exactly what we did.

If you have any questions or comments, please leave them on this post and I'll get back to you as soon as I can!

Source File: Download

Thursday, February 3, 2011

SmartFoxServer Tutorial: Extensions Introduction

Hey everyone!

I first would like to say I'm sorry for not updating the site as much as I have been. I'm going to try to get back to updating it more often, now that I am introducing you to extensions.

Anyway, extensions are VERY useful in SmartFoxServer. They can be used for various things, such as a kick user extension and a ban user extension. Those are the two most common extensions I see asked for in the SmartFoxServer Forums, so eventually, I'll post tutorials on these two extension. But for now, I'm going to introduce you to extensions.

First of all, we are going to write a 'Hello world!' extension. The first step in doing this is to setup the extension's ActionScript file. So, open up Flash, and click the Create New -> ActionScript file option.


After the ActionScript file is opened, we have to create the SmartFoxServer extension layout, as I call it. SmartFoxServer ActionScript extensions always contain a minimum of four required functions, which are: init, destroy, handleRequest, and handleInternalEvent.

To setup these functions I am going to add this coding to my ActionScript file:

function init() {

}

function destroy() {

}

function handleRequest(cmd, params, user, fromRoom) {

}

function handleInternalEvent(e) {

}


Now that the default functions have been created, we can start writing our extension.

Since this is going to be a very simple 'Hello world!' extension, we aren't going to be writing much more coding than what has already been written above. So, here is what the rest of the extension will look like:

function init() {
//This is called when the extension loads (when the server first starts).
trace("Simple extension is starting.");
}

function destroy() {
//This is called when the extension is destroyed.
trace("Simple extension is ending.");
}

function handleRequest(cmd, params, user, fromRoom) {
if (params.simpleParam == "paramOne") { //If statement opener one.
if (cmd == "simpleCmd") { //If statement opener two.
trace("Hello world!"); //Traces 'Hello world!' on the server.
} //If statement two closer.
} //If statement one closer.
}

function handleInternalEvent(e) {
//This is called when any internal event is executed.
trace("Internal event: " + e.name + " was called."); //Traces the internal event that was executed.
}


As I said, not much more coding than what has already been written. Basically, it is just a couple of trace statements and two if() statements. The comments I added in the script can be taken out, but they are in there just so you know what each line of coding does.

Now all we need to do is save the file and add the extension in the config.xml file. So, save the file to the directory {sfs-installation}/Server/sfsExtensions. Make sure the file name is "simpleExtTut" and make sure the file type is a '.as' file type.

To add the extension into the config.xml file, first we need to open the config.xml file up. Open up your favorite text or XML editor (maybe Notepad or WordPad), and open your config file, which should be located in in the directory {sfs-installation}/Server/config.xml.

Now that your config file is opened up, since I'm using the avatarChat example file, the zone I need to add this extension to is the simpleChat zone. So, after I scroll down and find the simpleChat zone, I will come across the tags somewhere in the simpleChat zone. After I find that, I have to add this in between those tags:



Now save your config.xml file.

The next thing to do, is to work on the client side (the Flash file). In my Flash file, I'll be using the SmartFoxServer avatarChat example file, as usual. After you open your Flash file, create a button or a movieclip which will call the extension.


After the button or movieclip has been created, add this coding to it's actions:

on (release) {
var dataObj:Object = {};
dataObj.simpleParam = "paramOne";
_root.smartfox.sendXtMessage("simpleExtTut", "simpleCmd", dataObj);
}


All that coding does is tell Flash to send SmartFoxServer an extension request to the extension name "simpleExtTut" and make the command (cmd) equal "simpleCmd" and to send the data from the object dataObj along with the extension request.

Now you can test your movie. This is what your final product should look like:


Well, that's all for this tutorial.

If you have any questions are comments, feel free to leave them in a comment on this post and I'll reply to them as soon as I get a chance!

avatarChat.fla Source File: Download
simpleExtTut.as Source File: Download

Monday, January 24, 2011

SmartFoxServer Tutorial: Chat Log

Hello everyone!

It's been a while since I posted on this site. I'm sorry about that, I've just been a little busy on a new project I'm working on. Anyway, as you can tell from the post title, this tutorial is on how to create a chat log. The chat log we create in this tutorial will have an auto-scrolling feature. Anyway, let's get started!

First things first, I'm using an avatarChat example file from SmartFoxserver. So, let's go ahead and open that file up.

After the file is opened, go to the 'chat' frame and put a dynamic text box on the stage and give it an instance name of chatLog and make sure you tick the box shown below so that it has HTML abilities.


After you do that, you need to open up the 'chat' frame's coding. After the coding is up, scroll down until you find a SmartFoxServer handler called "smartfox.onPublicMessage." Add this coding inside that handler:

//New Chat Log Coding:
//--Basic Add Message Coding:
chatLog.htmlText += user.getName() + ": " + msg + newline; //Add text to textbox
//--Basic Auto-Scroll Coding:
var logVar = 1; //Creates a variable, you might want to increase this
chatLog.scroll = logVar; //Scrolls textbox to variable amount
logVar++; //Increases variable value

Pretty basic coding, as you can see. Here is an image of where I added that coding in my Flash file:



(Coding in the image isn't correct, use the coding as shown above!)

Well, after you do that, test the movie and it should be working fine.

If you encounter any problems with this be sure to leave a comment and I'll get back to you as soon as I can.

Source File: Download

Monday, January 10, 2011

SmartFoxServer Tutorial: Playercards

Hey everyone!

In today's tutorial, I'm going to show you how to make a playercard, which when an avatar is clicked, a playercard will appear and show the user's username. Anyway, let's get started, shall we?

To begin with, I'm going to let you know that I'm using the avatarChat example file for this tutorial. Anyway, the first thing your going to want to do is open up the actions panel for the chat frame and add this coding to it:

function showPlayerCard() {
loadMovieNum("playercardSWF.swf", 1);
}

Basically all that coding does is tell the Flash file to load an external file, which I'll be using to display the playercard.

The next thing you'll want to do is open up the avatar movieclip from the Flash library. In this movieclip, you will be able to clearly see all the instances in your avatar.


Anyway, on with the tutorial. Click on the disc movieclip (don't double click) and add this coding:

on (release) {
_global.lastP2 = _parent;
_global.lastP2Name = _parent.name.text;
_root.showPlayerCard();
}

That coding basically tells the Flash file what the username of the player is and to load the playercard.

The next, and last, thing to do is to make the playercard. I quickly made a playercard SWF file, saved it, and published it with the name playercardSWF. I also saved it in the same location as the avatarChat example file that I'm using for this tutorial.

Now, the architecture I used when making my playercard SWF file was making a text file to display the user's username and adding a background to it as well. I also added a few extra things to my file for interactivity, which aren't required.

Anyway, after adding a dynamic text field with an instance name of playerName, I put the background of the playercard and the dynamic text field both in a movieclip named thePlayerCard.

The last thing I did, was add some coding on the first, and only frame of the playercardSWF file. The coding I added to the playercardSWF file on the root frame was this:

function loadPlayer(mc, uname) {
thePlayerCard.playerName.text = uname;
}
loadPlayer(_global.lastP2,_global.lastP2Name);

After you do all the above, test your movie and you should clearly see that it works just fine.

If you have any questions, comments, or if you run into any errors when following this tutorial, be sure to leave a comment and I'll reply to it as soon as I can.

Download playercardsTut Source File: Download
Download playercardSWF Source File: Download

Saturday, January 8, 2011

SmartFoxServer Tutorial: How to Add Rooms

Hello everyone.

In this tutorial, I'm going to show you how to add rooms into the SmartFoxServer config.xml file. This tutorial is in a video that I posted on YouTube. Here is the video:



If you have any questions or comments, feel free to leave them in a comment and I'll reply to them as soon as I get a chance.

SmartFoxServer Tutorial: Multi-Colored Chat Bubbles

Hello again everyone.

In this tutorial, I'm going to teach you how to make multi-colored chat bubbles. One example of what I mean by this is below.

Let's say the creator of a virtual world wants to be known in his virtual world for being the creator of the game. Everytime he says something publicly, we can indicate his chat bubble to be blue, instead of white, like the SmartFoxServer example file's default color.

So, with that being said, let's get started.

The first thing I'm going to do is open the Flash library and edit the avatar movieclip inside the _GUI and _Avatars folders. I'm now going to double click on the bubble movieclip to edit the avatar's chat bubble.

At this point, I'm going to add a new keyframe on each layer. In the new keyframe, I made the chat bubble blue and put some static text on top of the bubble which says "Creator."


I'm also going to name the one of the second frames "creator" as an easier way to go to that frame.

Now after that's done, it's time to code it into the avatarChat file. The coding for this will go inside the chat frame inside the onPublicMessage handler. This is what I added in my Flash file:

if (user.getName() == "nameHere") {
mc.bubble.gotoAndStop("creator");
}
Here is a picture of where I added the coding to in my file:


Also, you are going to have to edit the part of coding that says 'nameHere' to a username you want. After you do that, the user's chat bubble should be at the creator frame whenever the user says something publicly.

So, that's really all for this tutorial.

As usual, if you have any questions or comments, don't hesitate to make a comment on this post!

Source File: None

SmartFoxServer Tutorial: Arrow Key Rotation

Hello everyone.

In this tutorial, we are going to make a simple avatar rotation, as some would call it. This tutorial can be very easily compared to my first tutorial on this site, which was a setUserVariables tutorial. In this tutorial, we are going to learn how to change avatar directions by using the arrow keys. So, let's get started with this very simple tutorial.

Before i started typing up this post, I created an example file, which the download link can be found at the bottom of this post, and it is very easily done. So, the first thing you are going to want to do is open up your Flash library (Window -> Library or Ctrl+L).

After you open up the library, find the _GUI folder and open the folder to reveal the contents. Now open the _Avatars folder to reveal it's contents as well. Right click on the disc movieclip and press the Edit option.

Now that you are able to edit the movieclip, I added two more layers to my file. One named Labels and the other one named Arrows. I made each frame a blank keyframe by selecting the new frames and right clicking, then clicking "Convert to blank keyframes."

After you do that, you need to name four frames in that movieclip to four directions, which are left, up, right, and down. Do this by clicking on a frame and opening the Flash properties menu (Windows -> Properties or Ctrl+F3).


I then made directional arrows on the correct frame. Example: Left arrow on the "left" frame.

Now that the hardest part is done, it's time for the simplest part in this whole tutorial: the coding. All the coding in this tutorial goes on the chat frame of the avatarChat example file.

Here is the coding I used:

_root.onEnterFrame = function() {
if (Key.isDown(Key.LEFT)) {
_root.smartfox.setUserVariables({col:"left", init:true});
_root.myAvatar.disc.gotoAndStop("left");
}
if (Key.isDown(Key.UP)) {
_root.smartfox.setUserVariables({col:"up", init:true});
_root.myAvatar.disc.gotoAndStop("up");
}
if (Key.isDown(Key.RIGHT)) {
_root.smartfox.setUserVariables({col:"right", init:true});
_root.myAvatar.disc.gotoAndStop("right");
}
if (Key.isDown(Key.DOWN)) {
_root.smartfox.setUserVariables({col:"down", init:true});
_root.myAvatar.disc.gotoAndStop("down");
}
}
I put the coding at the very bottom of the chat frame. Well, basically all the coding does is constantly check to see if an arrow key is down or not. If an arrow key is down, it updates the user variables (which is handled by the event onUserVariablesUpdate) and then makes the action to the server, then the client as well.

Well, that's all for this tutorial!

If you have any questions or comments, feel free to ask by making a comment! :)

Source File: Download

Friday, January 7, 2011

SmartFoxServer Tutorial: Private Messaging

Hello again.

In this tutorial, as you can probably tell from the title of this post, is about private messaging. Anyway, let's get started with this tutorial. By the way, for this tutorial I'm using the SmartFoxServer avatarChat example file.

First of all, you have to make a button which will open the send message window.


Now, I just labeled mine with the text "Open." You can label yours with something else, such as send if you want. You can also give the button an instance name if you want. This isn't required, but I do that with all my symbols.

The next thing we will do, is make the private message window. In the window, this is where you will see the messages received and it will also be used to send messages. Here is the window I made:


I have multiple items in my private message window, so now I'm going to explain each one to you. Also, my window's instance name is pmWindow.

1 - Dynamic text box, which I gave an instance name of whoToSend.
2 - Input text box, which I gave an instance name of msgToSend.
3 - Button symbol, which will be used to send the private message to the desired user.
4 - Dynamic text box, which I gave an instance name of msgText.
5 - This is optional, but I made the top part of my window draggable.
6 - Button symbol, which will be used to close the window.

Now all that we need to do is code the updates to the avatarChat file. For the main coding, I'm going to just use functions for simplicity.

I'm just going to paste on the coding that I added to the chat frame of the Flash file at this point.

_root.pmWindow._visible = false;

function openPm() {
var uPm = _root.userList_lb.getSelectedItem().data;
var targetUser = _root.userList_lb.getSelectedItem().label;
if (uPm != _root.smartfox.myUserId()) {
_global.tUser = targetUser;
_global.uPm = uPm;
_root.pmWindow._visible = true;
_root.pmWindow.whoToSend.text = "Do you want to send a private message to " + _global.tUser + "?";
} else {
trace("You can't send a private message to yourself.");
}
}

function sendPm() {
var pMsg = _root.pmWindow.msgToSend.text;
if (pMsg != "") {
_root.smartfox.sendPrivateMessage(pMsg, _global.uPm);
_root.pmWindow.msgToSend.text = "";
}
}

function closePm() {
_root.pmWindow._visible = false;
}

smartfox.onPrivateMessage = function(msg:String, sender:User) {
_root.pmWindow._visible = true;
_root.pmWindow.msgText.text += newline + sender.getName() + ": " + msg;
trace(msg);
trace(user.getName());
}
I wrote that coding all that coding at the very end of the chat frame coding. That's all the frame coding, so we're almost done. All we have left to do is add the button coding. On the send private message button, add the following coding.

on (release) {
_root.sendPm();
}
Now, on the close window button, add this coding:

on (release) {
_root.closePm();
}
Also, on the open window button, be sure to add this coding:

on (release) {
_root.openPm();
}
Now, to use the private message feature, you have to click a username on the userlist and click the open button. You can't click on yourself because this was just a quick little tutorial I rushed through.

Anyway, that's all for this tutorial.

If you have any questions or comments, then be sure to comment on this post and I'll reply as soon as I get a chance!

Source File: Download

Wednesday, December 29, 2010

SmartFoxServer Tutorial: How to Create Emoticons

Hello again!

In this tutorial, I am going to teach you how to create emoticons in the SmartFoxServer avatarChat example. So, let's begin.

First, I am going to start off with the coding. In the chat frame of the avatarChat example file, find the onPublicMessage handler. It should look similar to this:



After you find that handler, it's pretty much simple coding from there. So, with that being said, let's begin coding.

The method I am using for this does the following:

  1. When a message is said, it hides the emotes movieclip by default.
  2. If the message contains :) then show the emotes movieclip and goes to the smile frame of the emotes movieclip.

Now, here is the coding I used in my example file:

mc.bubble.emotes._visible = false;
if (msg == ":)") {
mc.bubble.message.text = "";
mc.bubble.emotes._visible = true;
mc.bubble.emotes.gotoAndStop("smile");
}

I also rearraged some of the coding, so rearrange your coding to match mine, as shown below:



The next thing to do is setup the avatar. To do this, open up the library (Window -> Library), and click on the _GUI folder two times to open it (or you can click the gray arrow beside the folder icon) and look at the contents inside it. Once that folder is opened, you should see another folder named _Avatars. Open that folder as well.

Once the _Avatars folder is opened, you should see a movieclip named avatar. Right click on the symbol in the library and click the Edit option.

Now we need to get inside the bubble movieclip. To do this, simply click on the avatar's chat bubble two times. You should now be inside the bubble movieclip.



Here, is where you will create your emotes. For this tutorial, I'm going to make a smiling emoticon. After your done making your emote, convert it to a movieclip symbol and give it an instance name of emotes. Also, be sure to give your emote's smile frame a frame name of smile.

That's all for this tutorial!

If you have any questions, comments, or if you find any problems with my scripts, please leave a comment and I'll reply to it as soon as possible.

SmartFoxServer Tutorial: Simple Buddylist Tutorial

Hello everyone.

In this tutorial, we are going to make a very simple buddy list. That's all we will be doing in this tutorial. So, with that being said, let's begin.

To begin with, I'm using SmartFoxServer's avatarChat example file. What I do in this tutorial, you should be able to just copy and paste all the coding to your Flash file, and it should work just fine. Anyway, let's do all the coding first, then go back and setup the Stage.

The first line of coding you need to add is this:

var bListLoaded = false;
Add that line of coding somewhere near to the place I added mine in the picture below, or in the same exact spot if you want.



Next, you have to add something to the onJoinRoom handler, so the buddylist loads when you enter the room. This is where the variable above comes in. Add this coding somewhere in the onJoinRoom handler:

if (!bListLoaded) {
bListLoaded = true;
_root.smartfox.loadBuddyList();
}
I added it to the end of the onJoinRoom handler after the avatar is setup. Here is a picture of where I added the coding:



After you add that coding, you have to create a new handler. By that I mean add more coding. Anyway, what I did here was add some coding under the onJoin Room handler. Here is the coding you need to add:

smartfox.onBuddyList = function(bList:Array) {
theBList.removeAll();
for (var i in bList) {
var buddyName = bList[i].name + " (" + (bList[i].isOnline ? "Online" : "Offline") + ")";
theBList.addItem(buddyName, bList[i]);
}
theBList.sortItemsBy(buddyName, "ASC");
}

I added that coding right under the onJoinRoom handler, as shown in the picture below.



Now, we only have two more handlers to create. The two more handlers are onBuddyListUpdate and onBuddyListError. After that, it is just simple coding. Anyway, here is the coding for the onBuddyListUpdate handler:

smartfox.onBuddyListUpdate = function(b:Object) {
var buddyName = b[i].name + " (" + (b[i].isOnline ? "Online" : "Offline") + ")";
for (var i:Number = 0; i < theBList.getLength(); i++) {
var item = theBList.getItemAt(i);
if (item.data.name == b.name) {
theBList.replaceItemAt(i, buddyName, b);
break;
}
}
}

I added that handler under the onBuddyList handler, as in the picture below.



Now, the last handler you have to add, and the simplest in my own opinion, is the onBuddyListError handler. For this tutorial, I'm not going to get much into this handler because it is a very simple handler. All I do in this handler, at this time, is just setup a trace command, so that if an error occurs in the buddylist, it traces it to the output panel. Here is the coding for the onBuddyListError handler:

smartfox.onBuddyListError = function(theError:String) {
trace("Buddylist Error: " + theError);
}

I added that handler under the onBuddyListUpdate handler, as shown in the picture below.



Those are all the handlers you need to setup, but that's not all the coding. Now, we move onto functions. The functions we are going to add in this tutorial are addBuddy and removeBuddy. First, I'll make the addBuddy function.

Just to make the file look "cleaner" in coding, I add all my functions at the end of the Flash movie. So, I'm skipping all the way down and I'm going to add this coding:

function addBuddy() {
var user = userList_lb.getSelectedItem().label;
if (user != _global.myName) {
if (user != undefined) {
_root.smartfox.addBuddy(user);
}
}
}

Here is a picture of where I added the coding:



(I know the image isn't the correct coding as it has ...getSelectedItem().data.label; - Take out the ".data" part and it should work fine.)

Now, I skipped down two more lines after adding that coding, and I then added the removeBuddy function, which contains this coding:

function removeBuddy() {
var user = theBList.getSelectedItem().data.name;
if (user != _global.myName) {
if (user != undefined) {
_root.smartfox.removeBuddy(user);
}
}
}

Here is a picture of where I added that coding as well:



(I know the image isn't the correct coding as it has ...getSelectedItem().label; - Take out the ".label" part and add ".name" instead, then it should work fine.)

Now, after you do all that above, it is now time to setup the Stage. By the way, all the coding above these words go on the chat frame of the avatarChat.

To setup the Stage, all you have to do is click Window from the menu bar at the top of Flash, then click on the Components option. The components window should then open. Look through the components window until you find the component called "List." Drag it to the Stage and give it an instance name of theBList.

Now make two buttons and put them somewhere on the Stage, give them any instance name you want. For the button that will be used to add the buddy, add this coding to the button:

on (release) {
_root.addBuddy();
}

Now, for the button that will be used to remove the buddy from your buddylist, use this coding:

on (release) {
_root.removeBuddy();
}

That's all for this tutorial!

If you have any problems or errors, or any questions on this tutorial, please leave a comment on this post and I will reply to it soon.

NOTE: Due to the coding I used in this tutorial, you will need to open the SWF file two times to test it, as if you try to test it with yourself by attempting to add yourself onto your own buddylist, it won't work.

Saturday, December 25, 2010

SmartFoxServer Tutorial: setUserVariables()

Hello everyone!

I just received a request from Bobhead202 asking about how to change moderator outfits on a SmartFoxServer avatarChat file. Anyway, the command to do this in-game is server.setUserVariables().

setUserVariables basically sets user variables. There is no other simpler definition than that.

So, I'm going to go ahead and start this tutorial now. This is pretty simple so I'm not going to have any pictures in this tutorial. Plus, the computer I'm currently doesn't have Flash installed.

Anyway, let's begin.

1. Open up your Flash ActionScript 2.0 avatarChat file.

2. Make a button anywhere on the stage and give it any instance name you want.

3. Add the following coding inside the button:

on (release) {
var newCol = frameNumberHere;
_root.smartfox.setUserVariables({col:newCol, init:true});
_root.myAvatar.disc.gotoAndStop(newCol);
}
That's pretty simple coding - only 5 lines of coding. I'm now going to break up each line of ActionScript and explain what each one does.

on (release) { - This handler indicates to perform the action on the release of the button.
var newColor = frameNumberHere; - This line creates a variable. (Replace "frameNumberHere" with the frame number of the new avatar in the myAvatar.disc movieclip.)
_root.smartfox.setUserVariables({col:newCol, init:true}); - This line calls the setUserVariables command and updates the current user's variables. After doing this, it calls the onUserVariablesUpdate event. Anyway, the reason we use the curly brackets inside the normal brackets is because the data inside is an object. "col" is the name of the user variable pre-set in the avatarChat file. "init" - When this is set to true, it updates all clients right then. If it's set to false, then it does the opposite and doesn't update at that time.
_root.myAvatar.disc.gotoAndStop(newCol); - This line of coding updates the client side so that the disc's frame goes to the one defined in the newCol variable.
} - Indicates the end of the coding handler.

That's basically all for this tutorial. If you encounter any problems or errors, or if you don't understand something, make a comment on this post and I will be glad to assist you further.

~Cool Boy 714