The following code is for the login.
Code: Select all
import it.gotoandplay.smartfoxserver.*
#include "lib/[flashAPI].as" // walking equstions
#include "lib/easingEquations.as" // walking equstions
#include "lib/easing.as" // walking equstions
/*
* ----------------------------------------------------------------------------
* [ Avatar Chat ] version 1.1.0 -- Actionscript 2.0
* a SmartFoxServer sample application
*
* www.smartfoxserver.com
* (c) 2004 gotoAndPlay()
* ----------------------------------------------------------------------------
*/
stop()
Stage.showMenu = false
//----------------------------------------------------------
// Setup global variables
//----------------------------------------------------------
var stageW:Number = 780
var stageH:Number = 490
// hide semi-transparent panel
// used when a dialog box is shown
disabler._visible = false
// isBusy is true when the application
// is requiring input through a dialog box
// When true all other controls are temporarily disabled
_global.isBusy = false
// An event queue
var evtQueue:Array = []
//----------------------------------------------------------
// Setup global variables
//----------------------------------------------------------
showLogin(false)
status_txt.text = "Connecting..."
//----------------------------------------------------------
// Server configuration
//
// ip = IP address of the server, if the server is running
// locally use 127.0.0.1
// port = default value is 9339
// zone = the Server "zone" name for this application
//----------------------------------------------------------
var ip:String = "127.0.0.1"
var port:Number = 9339
var zone:String = "Turtles"
var smartfox:SmartFoxClient = new SmartFoxClient()
smartfox.onConnection = handleConnection
smartfox.debug = true
// Connect to the server
smartfox.connect(ip, port)
//----------------------------------------------------------
// Handle connection response from server
//----------------------------------------------------------
function handleConnection(success:Boolean)
{
if (success)
{
status_txt.text = "Connected, please login:"
showLogin(true)
butt_login.onRelease = sendLogin
}
else
{
status_txt.text = "Can't connect!"
}
}
//----------------------------------------------------------
// Send login params to the server
// server.login(zone, nickName, password)
//----------------------------------------------------------
function sendLogin()
{
if(login_txt.length > 3 && password_txt.length > 5){
if (!_global.isBusy) play();
smartfox.login(zone, login_txt.text, password_txt.text);
}
else {
status_txt.text = "You must have a username greater than 4 letters and a password that is greater than 4 letters.";
}
}
//----------------------------------------------------------
// A couple of needed variables
//----------------------------------------------------------
var hexcase = 0;
var b64pad = "";
var chrsz = 8;
//----------------------------------------------------------
// The server must handle an extention response
//----------------------------------------------------------
smartfox.onExtensionResponse = function(resObj:Object) {
if (resObj._cmd == "logOK") {
// Login Success Example Code
_global.myName = resObj.name
gotoAndStop("chat")
} else if (resObj._cmd == "logKO") {
// Login failed example code
_global.isBusy = true
status_txt.text = "Something has gone wrong. Please refresh the page and try logging in again.";
redoLogin();
}
}
//----------------------------------------------------------
// function redoLogin
//----------------------------------------------------------
function redoLogin(){
gotoAndPlay(1);
}
//----------------------------------------------------------
// Handle login response from server
//----------------------------------------------------------
smartfox.onLogin = function(resObj:Object)
{
if (resObj.success)
{
// Login Succesfull
_global.myName = resObj.name
}
else
{
// Login Failed
_gloabl.isBusy = true
// Show an error window
var win:MovieClip = showWindow("errorWindow")
win.errorMsg.text = resObj.error
}
}
//----------------------------------------------------------
// Handle the onRoomListUpdate here and keep it in the
// queue. We'll handle it in the next frame.
//----------------------------------------------------------
smartfox.onRoomListUpdate = function(o:Object)
{
evtQueue.push(o)
gotoAndStop("chat")
}
//----------------------------------------------------------
// Handle unexpected server disconnection
//----------------------------------------------------------
smartfox.onConnectionLost = function()
{
gotoAndStop("load")
status_txt.text = "Connection with the server was lost";
}
//----------------------------------------------------------
// Show / Hides the login input field and submit button
//----------------------------------------------------------
function showLogin(bool:Boolean)
{
butt_login._visible = bool
login_txt._visible = bool
loginBox._visible = bool
if (bool)
Selection.setFocus("login_txt")
}
//----------------------------------------------------------
// Shows a popup window and disables all other controls
//----------------------------------------------------------
function showWindow(linkageName:String):MovieClip
{
_global.isBusy = true
disabler._visible = true
roomList_lb.setEnabled(false)
userList_lb.setEnabled(false)
var win = _root.attachMovie(linkageName, linkageName, 9999)
win._x = (stageW / 2) - (win._width / 2)
win._y = (stageH / 2) - (win._height / 2)
return win
}
Code: Select all
//----------------------------------------------------------
// Hides a popup window and re-enable the controls
//----------------------------------------------------------
function hideWindow(wName:String)
{
this[wName].removeMovieClip()
roomList_lb.setEnabled(true)
userList_lb.setEnabled(true)
disabler._visible = false
_global.isBusy = false
}
import it.gotoandplay.smartfoxserver.*
stop()
//----------------------------------------------------------
// Setup components callback functions
//----------------------------------------------------------
roomList_lb.setChangeHandler("changeRoom")
mc.onPress = function()
{
_root.card._visible = true;
}
//----------------------------------------------------------
// Setup textfields
//----------------------------------------------------------
userName_txt.text = "Logged as: " + _global.myName
input_txt.text = ""
_root.we = 40;
_root.he = 40;
//----------------------------------------------------------
// Setup global vars
//----------------------------------------------------------
var areaW:Number = 600 // width of the are where avatars can move
var areaH:Number = 335 // hieght of the are where avatars can move
var avatarW:Number = _root.we // width of the avatar
var avatarH:Number = _root.he // height of the avatar
var inited:Boolean = false // flag to see if the application has been initialized
var myAvatar:MovieClip // my Avatar symbol
//----------------------------------------------------------
// Setup Mouse Listener
//----------------------------------------------------------
var myMouse:Object = {}
myMouse.onMouseDown = function()
{
if (inited)
{
if (!_global.isBusy)
{
var px:Number = int(avatarMC._xmouse)
var py:Number = int(avatarMC._ymouse)
if (_root._ymouse<440)
{
// save new variables
// Please note that init is set to false:
// this means that we're only moving somewhere and we don't need to init tha avatar
smartfox.setUserVariables({px:px, py:py, init:false})
// method derived from the [flashAPI].as
// moves the mc using the "Quint" equation, with "InOut" easying
// to the new px,py position in 100 milliseconds.
myAvatar.easingTo("Sine", "In", px, py, 100)
}
}
}
}
onEnterFrame = function(){
getUserCount()
}
//----------------------------------------------------------
// Handles the RoomList response from server
//----------------------------------------------------------
// roomList is an array of room objects
// Each room objects has these methods:
//
// getId() = get room id
// getName() = get room name
// isPrivate() = is the room private ? (0 = false, 1 = true)
// isTemp() = is the room temporary ? (0 = false, 1 = true)
// isGame() = is the room holding a game ? (0 = false, 1 = true)
// getUserCount() = get # of users in the room
// getMaxUsers() = get capacity of the room
// getUser(id) = get the user Object from a known user id
// getUserList() = get the userList Object
// variables = a property Object containing all room variables
//----------------------------------------------------------
smartfox.onRoomListUpdate = function(roomList:Object)
{
roomList_lb.removeAll()
for (var i:String in roomList)
{
var room = roomList[i]
roomList_lb.addItem(room.getName() + " (" + room.getUserCount() + ")", room.getId())
}
roomList_lb.sortItemsBy("label", "ASC")
// Join the default room
this.autoJoin()
}
// Handle roomListUpdate events that occurred before the playhead was moved to this frame
if (evtQueue.length > 0)
{
smartfox.onRoomListUpdate(evtQueue[0])
delete evtQueue
}
//----------------------------------------------------------
// Handles the JoinRoom response
// Upon joining a room the client receives the userList of
// that room. By calling the getUserList() method on the
// room Object you get the userList Object
//
// You can use these methods on every user Object:
//
// getId() = get user unique id
// getName() = get user nickname
// variables = a property Object containing all user vars
//----------------------------------------------------------
smartfox.onJoinRoom = function(roomObj:Object)
{
cleanAvatars()
var roomId:Number = roomObj.getId()
var userList:Object = roomObj.getUserList()
resetRoomSelected(roomId)
_global.currentRoom = roomObj
// Update Room Name in the avatar area
currentRoom.htmlText = "Current room: <b>" + roomObj.getName() + "</b>"
// Clear current list
userList_lb.removeAll()
for (var i:String in userList)
{
var user:User = userList[i]
var uName:String = user.getName()
var uId:Number = user.getId()
userList_lb.addItem(uName, uId)
if (uName != _global.myName)
{
var uVars:Object = user.getVariables()
var mc:MovieClip = avatarMC.attachMovie("avatar", "avatar_" + uId, Number(uId))
mc._x = uVars.px
mc._y = uVars.py
mc.disc.gotoAndStop(uVars.col)
mc.name.text = uName
}
}
// Sort names
userList_lb.sortItemsBy("label", "ASC")
setupMyAvatar()
}
_root.card.red.onPress = function()
{
col = int(2)
}
//----------------------------------------------------------
// Handles Join Room Errors
//----------------------------------------------------------
smartfox.onJoinRoomError = function(errorMsg)
{
var win:MovieClip = showWindow("errorWindow")
win.errorMsg.text = errorMsg
// Put the selected room in the combo box back to its old value
resetRoomSelected(smartfox.activeRoomId)
}
//----------------------------------------------------------
// Handles a new user entering the room
//----------------------------------------------------------
smartfox.onUserEnterRoom = function(fromRoom, user)
{
_root.admin.gotoAndStop(2);
_root.admin.info.text += newline+"User: "+ user.getName() + " just entered the room";
_root.admin.info.text += newline+"There are now "+ getUserCount() + " in the room";
var userId:Number = user.getId()
var userName:String = user.getName()
// Add user to the userList listbox
userList_lb.addItem(userName, userId)
// Sort names
userList_lb.sortItemsBy("label", "ASC")
updateRoomStatus(fromRoom)
// Show the user avatar
var mc:MovieClip = avatarMC.attachMovie("avatar", "avatar_" + userId, userId)
mc._x = user.variables["px"]
mc._y = user.variables["py"]
mc.name.text = userName
mc.disc.gotoAndStop(user.variables["col"])
}
//----------------------------------------------------------
// Handles a new user leaving the room
//----------------------------------------------------------
smartfox.onUserLeaveRoom = function(fromRoom:Number, usrId:Number)
{
for (var i:Number = 0; i < userList_lb.getLength(); i++)
{
var item:Object = userList_lb.getItemAt(i)
if (item.data == usrId)
{
var usrName:String = item.label
userList_lb.removeItemAt(i)
break
}
}
// Destroy avatar from screen
avatarMC["avatar_" + usrId].removeMovieClip()
// Sort names
userList_lb.sortItemsBy("label", "ASC")
updateRoomStatus(fromRoom)
}
//----------------------------------------------------------
// Handles a change of variables in User
//----------------------------------------------------------
smartfox.onUserVariablesUpdate = function(user:User)
{
var currRoom:Number = this.getActiveRoom()
var id:Number = user.getId()
var uVars:Object = user.getVariables()
var mc:MovieClip
if (uVars.init)
{
mc = avatarMC.attachMovie("avatar", "avatar_" + id, Number(id))
mc._x = uVars.px
mc._y = uVars.py
mc.disc.gotoAndStop(uVars.col)
mc.name.text = user.getName()
}
else
{
mc = avatarMC["avatar_" + id]
mc.easingTo("Quint", "InOut", uVars.px, uVars.py, 100)
}
}
//----------------------------------------------------------
// Handles a user count change in the room
//----------------------------------------------------------
smartfox.onUserCountChange = function(roomObj:Room)
{
updateRoomStatus(roomObj.getId())
}
//----------------------------------------------------------
// Handles a public message
//----------------------------------------------------------
smartfox.onPublicMessage = function(msg:String, user:User)
{
var mc:MovieClip = avatarMC["avatar_" + user.getId()]
chat_txt.htmlText += "<b> " + user.getName() + " :</b> " + msg
main_sb.setScrollPosition(chat_txt.maxscroll)
if (msg.length > 50)
msg = msg.substring(0,48) + "..."
mc.bubble._visible = true
mc.bubble.message.text = msg
mc.deactivate()
}
//----------------------------------------------------------
// Handles an admin message
//----------------------------------------------------------
smartfox.onAdminMessage = function(msg:String, user:User)
{
var mc:MovieClip = showWindow("adminWindow")
mc.errorMsg.text += msg + "\n"
}
//----------------------------------------------------------
// Handles a new room added to the zone
//----------------------------------------------------------
smartfox.onRoomAdded = function(roomObj:Object)
{
roomList_lb.addItem(roomObj.getName() + " (" + roomObj.getUserCount() + ")", roomObj.getId())
roomList_lb.sortItemsBy("label", "ASC")
}
//----------------------------------------------------------
// Handles a new room deleted in the zone
//----------------------------------------------------------
smartfox.onRoomDeleted = function(roomObj:Object)
{
for (var i = 0; i < roomList_lb.getLength(); i++)
{
if (roomObj.getId() == roomList_lb.getItemAt(i).data)
{
roomList_lb.removeItemAt(i)
break;
}
}
}
//----------------------------------------------------------
// Sends a new public chat message to the other users
//----------------------------------------------------------
function sendChatMsg()
{
if (input_txt.text.length > 0)
{
smartfox.sendPublicMessage(input_txt.text)
input_txt.text = ""
}
}
//----------------------------------------------------------
// Handle changes in the roomList listbox
//----------------------------------------------------------
function changeRoom()
{
if(!_global.isBusy)
{
var item:Object = roomList_lb.getSelectedItem()
// new Room id
var newRoom:String = item.data
if (newRoom != smartfox.activeRoomId)
{
// Check if new room is password protected
var priv:Boolean = smartfox.getRoom(newRoom).isPrivate()
if (priv)
{
// Save newroom as _global for later use
_global.newRoom = newRoom
showWindow("passwordWindow")
}
else
{
// Pass the room id
smartfox.joinRoom(item.data)
}
}
}
}
//----------------------------------------------------------
// Create my Avatar
// Randomly generate the x,y position and a color
//
// Then initiliaze my user variables saving:
// px = mc._x position
// py = mc._y position
// col = avatar color
// init = a flag, that tells that the avatar is initializing
//----------------------------------------------------------
function setupMyAvatar()
{
if (!inited)
{
var col:Number = int(_root.colort)
myAvatar = avatarMC.attachMovie("avatar", "avatar_" + smartfox.myUserId, 99999)
myAvatar.disc.gotoAndStop(col)
myAvatar.name.text = _global.myName
var px:Number = 645;
var py:Number = 250;
myAvatar._x = px
myAvatar._y = py
// Store the avatar position on the server
smartfox.setUserVariables({px:px, py:py, col:col, init:true})
// Testing ONLY!!!
trace("Variables SET")
trace("---------------------------------------------")
trace("myID : " + smartfox.myUserId)
var self = smartfox.getRoom(smartfox.activeRoomId).getUser(smartfox.myUserId)
trace("User Obj: " + self)
trace("Vars: " + self.variables)
trace("px: " + self.variables["px"])
trace("py: " + self.variables["py"])
inited = true
Mouse.addListener(myMouse)
}
}
//----------------------------------------------------------
// Clean all Avatars from screen, except mine
//----------------------------------------------------------
function cleanAvatars()
{
for (var mc:String in avatarMC)
{
if (avatarMC[mc] != myAvatar)
avatarMC[mc].removeMovieClip()
}
}
//----------------------------------------------------------
// Enter a password protected room
// This function is being called by the pwdWindow movieclip
//----------------------------------------------------------
function loginProtectedRoom(pwd:String)
{
hideWindow("passwordWindow")
smartfox.joinRoom(_global.newRoom, pwd)
}
//----------------------------------------------------------
// Reset the selected item in the RoomList listbox
// Used when a password protected login has failed
//----------------------------------------------------------
function resetRoomSelected(id:Number)
{
var status:Boolean = roomList_lb.getEnabled()
roomList_lb.setEnabled(true)
for (var i:Number = 0; i < roomList_lb.getLength(); i++)
{
var item:Object = roomList_lb.getItemAt(i)
if (item.data == id)
{
roomList_lb.setSelectedIndex(i)
break
}
}
roomList_lb.setEnabled(status)
}
//----------------------------------------------------------
// Update the label of a Room in the listbox
// Used when updating the # of users in the room
//----------------------------------------------------------
function updateRoomStatus(roomId:Number)
{
var room:Room = smartfox.roomList[roomId]
var newLabel:String = room.getName() + " (" + room.getUserCount() + ")"
for (var i:Number = 0; i < roomList_lb.getLength(); i++)
{
var item:Object = roomList_lb.getItemAt(i)
if (roomId == item.data)
{
roomList_lb.replaceItemAt(i, newLabel, item.data)
break;
}
}
}
function addBuddy()
{
var item:Object = userList_lb.getSelectedItem()
if (item != undefined)
{
smartfox.addBuddy(item.label)
}
}
//----------------------------------------------------------
// Remove the currently selected buddy from the buddy list
//----------------------------------------------------------
function removeBuddy()
{
var item:Object = _root.buddy.buddyList_lb.getSelectedItem()
if (item != undefined)
{
smartfox.removeBuddy(item.data.name)
}
}
//----------------------------------------------------------
// Sends a private message to the currently selected buddy
//----------------------------------------------------------
function sendBuddyPrivateMessage()
{
var item:Object = _root.buddy.buddyList_lb.getSelectedItem()
if (item != undefined && item.data.id != -1)
{
_global.pmUid = item.data.id
showWindow("pmWindow")
}
}
//----------------------------------------------------------
// Removes all buddies from the buddy list
//----------------------------------------------------------
function clearBuddyList()
{
smartfox.clearBuddyList()
}
//----------------------------------------------------------
// In order to join the buddy we have to ask where he's
// currently located
//----------------------------------------------------------
function joinBuddy()
{
var item:Object = _root.buddy.buddyList_lb.getSelectedItem()
if (item != undefined)
{
smartfox.getBuddyRoom(item.data)
}
}
//----------------------------------------------------------
// Sends a private message to a user
// This is called by the private message dialog box (pmWindow)
//----------------------------------------------------------
function sendPrivateMessage(m:String, recipient:Number)
{
hideWindow("pmWindow")
smartfox.sendPrivateMessage(m, _global.pmUid)
}
smartfox.onBuddyList = function(bList:Array)
{
_root.buddy.buddyList_lb.removeAll()
for (var i in bList)
{
var label:String = bList[i].name + " [ " + (bList[i].isOnline ? "On" : "Off") + " ]"
_root.buddy.buddyList_lb.addItem(label, bList[i])
}
_root.buddy.buddyList_lb.sortItemsBy("label", "ASC")
}
var buddyListLoaded:Boolean = false
if (!buddyListLoaded)
{
buddyListLoaded = true
smartfox.loadBuddyList()
}
//----------------------------------------------------------
// Handles errors in loading the buddyList from server
//----------------------------------------------------------
smartfox.onBuddyListError = function(errorMsg:String)
{
var win:MovieClip = showWindow("errorWindow")
win.errorMsg.text = errorMsg
}
//----------------------------------------------------------
// A Buddy has changed status
//----------------------------------------------------------
smartfox.onBuddyListUpdate = function(buddy:Object)
{
var label = buddy.name + " [ " + (buddy.isOnline ? "On" : "Off") + " ]"
for (var i:Number = 0; i < _root.buddy.buddyList_lb.getLength(); i++)
{
var item:Object = _root.buddy.buddyList_lb.getItemAt(i)
if (item.data.name == buddy.name)
{
_root.buddy.buddyList_lb.replaceItemAt(i, label, buddy)
break
}
}
}
//----------------------------------------------------------
// The server responds sending the room(s) where the user is
// currently located. You can then use this id to join
// the user.
//----------------------------------------------------------
smartfox.onBuddyRoom = function(list:Array)
{
var roomId:Number = list[0]
if (roomId != smartfox.activeRoomId)
{
// Check if new room is password protected
var priv:Boolean = smartfox.getRoom(roomId).isPrivate()
if (priv)
{
// Save newroom as _global for later use
_global.newRoom = roomId
showWindow("passwordWindow")
}
else
{
// Pass the room id
smartfox.joinRoom(roomId)
}
}
}
//----------------------------------------------------------
// Log out, and shut down connection
//----------------------------------------------------------
function closeConnection()
{
smartfox.disconnect()
gotoAndStop("connect")
}