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

18 comments:

  1. hey man
    your tutorials r really good
    i learned a lot from them
    why u word with AS2? i think most programers prefer AS3 anyway
    it will be really good if u create a tutorial about multiplayer games.
    it will be new tutorial on sfs field most guys on youtube upload about chat,sql and stuff like that
    i wish u the best and looking forward for your new tutorials

    ReplyDelete
    Replies
    1. I do both now!
      Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  2. Are you still alive? xD If so, it would be great if you could start posting tutorials again :)

    ReplyDelete
    Replies
    1. Yes, still alive! Haha Working on some soon! ;) Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  3. Can you show us how to make badges?
    So if you are a mod you get a 'mod badge' on your playercard
    How to make a catalogue so people can buy clothes from it..
    How to make an inventory?
    :D

    ReplyDelete
    Replies
    1. Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  4. Please provide full code for the tutorial...I am in urgent need of it..

    ReplyDelete
    Replies
    1. Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  5. Could you please add download links? I would rly appreciate it.

    ReplyDelete
    Replies
    1. Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  6. Could you please add download links? I would rly appreciate it.

    ReplyDelete
    Replies
    1. Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  7. hello, please, I can upload the link to download the codes? thank you!

    ReplyDelete
    Replies
    1. Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  8. Hello! I wonder if it is possible to make a system of money and purchase, please answer!

    ReplyDelete
    Replies
    1. Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete
  9. Replies
    1. Please read the update to the newest post! Specify SFS2X or SFS1X!

      Delete