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

Friday, September 23, 2011

Updates

Well, as you can see, since I have started the new series of tutorials, I have not had much time to update them. When I started this series, I found out it actually took longer to make these tutorials, which makes the site way less productive than it was before.
Because of this, I'm going to stop the series of tutorials, and just continue with regular tutorials for now.
So, on that note, start commenting a few tutorial requests! :)

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 14, 2011

Webkinz Introduction

Hey everyone!

I usually don't make any other posts than posts about SmartFoxServer, but I just wanted to tell you all about one amazingly well programmed virtual world for kids called Webkinz.

For all of those people who do not know what Webkinz is, it is a game where you buy a collectible stuffed animal in a store located all over the world and on the stuffed animal is a secret code, which allows you to virtually adopt your pet and unlock the world of Webkinz online. Once you have adopted your pet online, you are able to play multiplayer games with other online users, visit your friend's house, earn KinzCash, go gem mining, and much more. Another thing I would like to include about Webkinz is that I can tell that the creators of Webkinz planned out the game extremely well.

The reasons I think Webkinz is an amazing game is really because of all the features it has and because of how well programmed the game is. Webkinz has so many different things to do, such as multiplayer games, single player games, daily activities (such as gem mining and spinning the Wheel of Wow), decorate your house, and much more.

Now, one other thing I have to include about this game, is that it uses isometrics and pathfinding while inside a house in Webkinz. Isometrics is basically a 'tiled' way to design something. The best way to know when something contains isometrics is to look at the game's environment. In Webkinz, when I look at the ground while inside someones house, I can tell that the ground is divided into separate tiles because when I hover my mouse over a place, the tile that is selected highlights itself, as shown in the picture I found off of Google below.


Pathfinding is a way of moving an object when using an isometric environment. What pathfinding does is find a path to the specified tile which uses the least amount of tiles to get to a specific tile. An example a game with pathfinding would be Habbo Hotel.

Anyway, my point is Webkinz is a well programmed game that you should check out.

Also, be sure to check out the Webkinz Facebook page and 'like' it by clicking here!

Here are a few links about Webkinz that you should be sure to check out:

http://webkinz.com/
http://twitter.com/Webkinz
http://facebook.com/webkinz

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