ElectroServer 3.7.2 Documentation

<root>

class PluginAPI

Object
  |
  +--PluginAPI


class PluginAPI
extends Object



Field Summary


#include
Pulls in another ActionScript file

Method Summary


ban ( username, time )
Kicks a user and bans for a specified time


callRemotePlugin ( pluginName, hash )
Calls another plugin and gets a response


clearInterval ( intervalID )
Clears an interval set with setInterval


createDirectory ( path )
Creates a directory


createRoomVariable ( name, value, locked )
Creates a room variable


createUserVariable ( user, name, value )
Creates a user variable on a specific user


deleteDirectory ( path )
Deletes a directory from hard drive


deleteFile ( path )
Deletes a file fromt he hard drive


deleteRoomVariable ( name )
Deletes a room variable


deleteUserVariable ( user, name )
Deletes a specific user variable


doesDirectoryExist ( path )
Checks for the existence of a directory


doesFileExist ( path )
Checks for the existence of a file


getAllZones ( )
Returns an array of zones


getLoggedInUserCount ( )
Returns the number of users logged into the server


getPluginName ( )
Returns the name of the plugin


getRoomName ( )
Returns the name of the room that the plugin is in


getRoomsInZone ( zone )
Returns an array of rooms in a specific zone


getRoomVariables ( zoneName, roomName )
Returns the room variables for a specific room.


getServerTimer ( )
Returns the time in milliseconds since 1970


getUserServerVariable ( username, name )
Returns a user server variable


getUsersInRoom ( zone, room )
Returns an array of users in a specific room in a specific zone


getUserVariables ( user )
Returns an array of user variables


getZoneName ( )
Returns the name of the zone that the plugin is in


hashToObject ( hash )
Converts a hash to a normal object


isDirectory ( path )
Returns true or false if the directory exists, or doesn't


isFile ( path )
Returns true or false if the path points to a file


isUserLoggedIn ( name )
Returns true if user is logged in


kick ( username )
Kicks a user from the server


LoadVars.load ( url )
Loads name value pairs from a remote URL


LoadVars.sendAndLoad ( url, destOb )
Sends variables and loads name value pairs from a remote URL


logger.config ( info )
A level of logging


logger.fine ( info )
A level of logging


logger.finer ( info )
A level of logging


logger.finest ( info )
A level of logging


logger.info ( info )
A level of logging


logger.severe ( info )
A level of logging


logger.warning ( info )
A level of logging


objectToHash ( ob )
Converts and object to a hash map


pluginDestroy ( )
Function called when room level plugin is being destroyed


pluginInit ( hash )
A required event handler. It is executed when the plugin is first created.


pluginInterop ( hash )
Event fired when a plugin is trying to be reached by another plugin


pluginRequest ( hash )
Event handler that intercepts all inbound messages from the client.


pluginUserEnter ( username )
Event fired when a user enters room


pluginUserExit ( username )
Event fired when a user leaves room


readFile ( filePath )
Loads a local text file into a variable.


removeUserServerVariable ( username, name )
Removes a user server variable


sendRawMessage ( type, message, users )
Sends a raw message to a room or to an array of specific users


server.createRoom ( roomOb )
Creates a room


server.moveToRoom ( who, zoneName, roomName, password, numbered )
Moves a user to a room


server.sendMessage ( type, one, two, three )
Sends message to specific user(s), the room, a specific zone, or the whole server


setInterval ( functionName, interval )
Enables a function to be automatically executed once per time interval


setUserServerVariable ( username, name, value )
Sets a variable on a user that the client doesn't know about


trace ( info )
Shows output on the ElectroServer console


updateRoomVariable ( name, value, locked )
Updates an existing room variable


updateUserVariable ( user, name, value )
Updates a specific user variable


writeFile ( filePath, content, append )
Writes a text file to the hard drive.



Field Documentation

#include

var #include
Pulls in another ActionScript file

Works just like #include in Flash. When the plugin is created external ActionScript file(s) are pulled in where ever a #include is found. It is a placeholder, not actually code. See below.
#include "C:\\ElectroServer 3\plugins\SomeAlgorithm.as"
function pluginInit(hash) {
	//
}


Method Documentation

ban

function ban(username,
 time)
Kicks a user and bans for a specified time

Kicks a user from the server disconnecting him. The user is banned from reconnecting for a specified time. See also kick.

Parameters:
username
Username
time
Time in milliseconds
Example:
var minutes = 60;
var time = 60*60*1000;
ban("kelly", time);

callRemotePlugin

function callRemotePlugin(pluginName,
 hash)
Calls another plugin and gets a response

This function is very useful. You can send a request to another plugin. It is important to note that using this function only room level plugins can talk to server level plugins. And server level plugins can talk to other server level plugins. But a server level plugin cannot initiate contact with a room level plugin (although there is a trick for doing that.)

This function takes a plugin name parameter, and a hash map. The target plugin has its pluginInterop function executed to capture the even. See pluginInterop, objectToHash, hashToObject.

The target plugin will handle the request and return another hash map.

Parameters:
pluginName
Name of the plugin to communicate with
hash
Hash map to send to the target plugin
Returns:
A hash map result from the target plugin

Example:
In this example imagine two plugins. One is a server level plugin called HighScoreListPlugin, and the other is a room level plugin called ShootemUpPlugin. The HighScoreListPlugin is used to save scores to a database and return the high score list. The ShootemUpPlugin is used to runt he game logic. It reports the scores at the end of a game to the HighScoreListPlugin.

Code in ShootemUpPlugin - (room level)
function gameOver(winner, winnersScore) {
	var ob = new Object();
	ob.winner = winner;
	ob.winnersScore = winnersScore;
	var hash = objectToHash(ob);
	var resultHash = callRemotePlugin("HighScoreListPlugin", hash);
	var resultOb = hashToObject(resultHash);
	//resultOb.highScoreList contains: jobe,300|kelly,200|mike,150
	server.sendMessage("public", "GameOver", resultOb);
}
Code in HighScoreListPlugin - (server level)
function pluginInterop(hash) {
	var ob = hashToObject(hash);
	saveUsersScoreInDatabase(ob.winner, ob.winnersScore);
	var returnOb = new Object();
	returnOb.highScoreList = getHighScoreList();
	return objectToHash(returnOb);
}

clearInterval

function clearInterval(intervalID)
Clears an interval set with setInterval

When executing setInterval an id is returned. When you want to clear the interval you take that id and pass it into this function.

Parameters:
intervalID
A number
Example:
var intervalId;
function pluginInit(hash) {
	intervalId = setInterval("moveProjectiles", 30);
}
function moveProjectiles() {
	//do something
}
function pluginDestroy() {
	clearInterval(intervalId);
}

createDirectory

function createDirectory(path)
Creates a directory

Creates a directory on hard drive.
See also deleteDirectory, isDirectory, doesDirectoryExist.

Parameters:
path
Path to directory, including the name of this new directory.
Example:
createDirectory("existingDirectory\newDirectory");

createRoomVariable

function createRoomVariable(name,
 value,
 locked)
Creates a room variable

Creates a room variable associated with the room. This only works in a room-level plugin. If a room variable is locked, then it cannot be edited unless unlocked. See also getRoomVariables, updateRoomVariable, deleteRoomVariable.

Parameters:
name
Name of variable
value
Value of variable
locked
Lock the variable (Boolean)
Example:
var name = "secreteWord";
var value = "kazam";
var locked = false;
trace("...creating a room variable");
createRoomVariable(name, value, locked);

createUserVariable

function createUserVariable(user,
 name,
 value)
Creates a user variable on a specific user

Creates a user variable on a specific user. See also getUserVariables, updateUserVariabe, deleteUserVariable.

Parameters:
user
Username that the variable should belong to
name
Variable name
value
Variable value
Example:
createUserVariable("mike", "age", random(100));

deleteDirectory

function deleteDirectory(path)
Deletes a directory from hard drive

Deletes a directory from the hard drive.
See also createDirectory, isDirectory, doesDirectoryExist.

Parameters:
path
Path to directory including name. Relative or absolute.
Example:
deleteDirectory("existingDirectory\newDirectory");

deleteFile

function deleteFile(path)
Deletes a file fromt he hard drive

Allows a plugin to delete a file from the hard drive.

Parameters:
path
Relative or absolute path to file.
Example:
var path = "myFile.txt";
deleteFile(path);

deleteRoomVariable

function deleteRoomVariable(name)
Deletes a room variable

Deletes a room variable of a given name. See also createRoomVariable, deleteRoomVariable, getRoomVariables

Parameters:
name
The name of the variable
Example:
deleteRoomVariable("secretWord");

deleteUserVariable

function deleteUserVariable(user,
 name)
Deletes a specific user variable

Deletes a user variable on a specific user. See also getUserVariables, createUserVariable, updateUserVariable.

Parameters:
user
Username that the variable should belong to
name
Variable name
Example:
updateUserVariable("mike", "age");

doesDirectoryExist

function doesDirectoryExist(path)
Checks for the existence of a directory

Checks to see if a directory exists and returns true if it does.
See also deleteDirectory, isDirectory, createDirectory.

Parameters:
path
Path to directory including name. Relative or absolute.
Example:
var path = "existingDirectory\newDirectory";
if (!doesDirectoryExist(path)) {
	createDirectory(path);
}

doesFileExist

function doesFileExist(path)
Checks for the existence of a file

This allows a plug-in to determine if a file exists on the server or not. It returns a Boolean value: true if the file exists, false if it does not.
Also see isFile, writeFile, deleteFile, readFile.

Parameters:
path
String that points to the path of the file. This can be absolute or relative.
Returns:
A Boolean value. If true, the file exists.

Example:
var filepath = "some_directory/myText.txt";
if (doesFileExist(filepath)) {
	//do something
} else {
	//do something else
}

getAllZones

function getAllZones()
Returns an array of zones

Returns an array of all of the zones on the server. Each element is an object with a Name property.

Example:
var zones = getAllZones();
for (var i=0;i<zones.length;++i) {
	var zone = zones[i];
	trace("Zone="+zone.Name);
}

getLoggedInUserCount

function getLoggedInUserCount()
Returns the number of users logged into the server

Returns the number of users logged into ElectroServer.

Example:
var numLoggedIn = getLoggedInUserCount();
trace(numLoggedIn +" users logged in.");

getPluginName

function getPluginName()
Returns the name of the plugin

Returns the name of the plugin, as specified in the configuration.xml file.

Example:
var myPluginName = getPluginName();
trace(myPluginName);

getRoomName

function getRoomName()
Returns the name of the room that the plugin is in

Only works for room level plugins. This returns the name of the room that the plugin is in. See also getZoneName.

Returns:
Name of room

Example:
var myRoomName = getRoomName();

getRoomsInZone

function getRoomsInZone(zone)
Returns an array of rooms in a specific zone

For a specific zone it returns an array of all of the rooms in that zone. Each element in the array is an object with a Name property and Hidden property. See also getAllZones.

Parameters:
zone
Zone name
Returns:
An array of room objects

Example:
var rooms = getRoomsInZone("Chat Zone");
for (var j=0;j<rooms.length;++j) {
	var room = rooms[j];
	trace("Room="+room.Name+", hidden="+room.hidden);
}

getRoomVariables

function getRoomVariables(zoneName,
 roomName)
Returns the room variables for a specific room.

Given a room name and zone name, the room variables are returned as an array of objects. Here are the properties:
name Name of the variable
value Value of the variable
locked If the variable is locked or not (Boolean).
persistent Boolean value. If false, then this will be deleted when the user who created it leaves the room. This cannot be modified by a plugin.

Note: room variables can be created by clients. See the client-side API for more information.

Parameters:
zoneName
Zone name
roomName
Room name
Returns:
Array of objects

Example:
function traceRoomVariables() {
	var roomVars = getRoomVariables();
	trace("---Room Variables--");
	for (var i = 0; i<roomVars.length; ++i) {
		var roomVar = roomVars[i];
		var varName = roomVar.name
		var value = roomVar.value
		var locked = roomVar.locked
		var persistent = roomVar.persistent;
		trace(varName+"="+value+"   locked="+locked+", persistent="+persistent);
	}
}

getServerTimer

function getServerTimer()
Returns the time in milliseconds since 1970

Returns the time in milliseconds since 1970 as seen by ElectroServer. This is generall used to synchronize client and server or to measure how long something takes.

Example:
var startTime = getServerTime();
doSomeHeavyFunction();
var elapsedTime = getServerTime()-startTime;
trace("It took "+elapsedTime+"ms to compute.");

getUserServerVariable

function getUserServerVariable(username,
 name)
Returns a user server variable

Returns a user server variable based on a username and variable name. See also setUserServerVariable, removeUserServerVariable.

Parameters:
username
Username
name
Name of the variable
Example:
var id = getUserServerVariable("mike", "databaseId");

getUsersInRoom

function getUsersInRoom(zone,
 room)
Returns an array of users in a specific room in a specific zone

For a specific room and zone it returns an array of all of the users in that room. Each element in the array is an object with a Name property. See also getUserVariables, getUsersInZone.

Parameters:
zone
Zone name
room
Room name
Returns:
An array of user objects

Example:
var users = getUsersInRoom("Chat Zone", "Lobby");
for (var i=0;i<users.length;++i) {
	var user = users[i];
	trace("User="+user.Name);
}

getUserVariables

function getUserVariables(user)
Returns an array of user variables

Given a username, it returns an array of user variables. Each element is an object with the properties 'name' and 'value'. See also createUserVariable, updateUserVariabe, deleteUserVariable.

Parameters:
user
The username
Returns:
Array of user variables

Example:
function traceUserVariables(user) {
	//Grab the object that contains the user's user variables
	var userVars = getUserVariables(user);
	trace("----User Variables for "+user+" ----");
	for (var i = 0; i<userVars.length; ++i) {
		var userVar = userVars[i];
		var varName = userVar.name;
		var varValue = userVar.value;
		trace(varName+"="+varValue);
	}
}

getZoneName

function getZoneName()
Returns the name of the zone that the plugin is in

Only works for room level plugins. This returns the name of the zone that it is in. See also getRoomName.

Returns:
Name of zone

Example:
var myZoneName = getZoneName();

hashToObject

function hashToObject(hash)
Converts a hash to a normal object

Hash maps are used throughout ElectroServer. This function converts a hash map to a normal object. See also objectToHash.

Parameters:
hash
Hash map
Example:
function pluginInit(hash) {
	var myOb = hashToObject(hash);
	trace(myOb.someVar);
}

isDirectory

function isDirectory(path)
Returns true or false if the directory exists, or doesn't

Checks for the existence of a directory. If it exists then it returns true.
See also deleteDirectory, createDirectory, doesDirectoryExist.

Parameters:
path
Path to directory including name. Relative or absolute.
Example:
var path = "existingDirectory\newDirectory";
if (isDirectory(path)) {
	createDirectory(path+"\anotherone");
}

isFile

function isFile(path)
Returns true or false if the path points to a file

This function allows a plug-in to determine if the destination is a file or not.
Also see doesFileExist, writeFile, deleteFile.

Parameters:
path
Relative or absolute path to file on local system
Example:
var path = "myFile.txt";
if (!isFile(path)) {
	writeFile(path, "hi");
}

isUserLoggedIn

function isUserLoggedIn(name)
Returns true if user is logged in

For a specific username it returns true of logged in, false if not.

Parameters:
name
The username
Returns:
Boolean value, true if logged in

Example:
var isLoggedIn = isUserLoggedIn("mike");
trace(isLoggedIn);

kick

function kick(username)
Kicks a user from the server

Kicks a user from the server. The user is disconnected. The user can immediately reconnect. See also ban.

Parameters:
username
Username
Example:
kick("jobe");

LoadVars.load

function LoadVars.load(url)
Loads name value pairs from a remote URL

Loads name value pairs from a remote URL. This is usually used to contact a server-side script.
See also LoadVars.sendAndLoad. Check out the LoadVarsExample plugin in the plugins directory.

Parameters:
url
The URL to contact
Example:
function load_test(url) {
	//Equivalent to using the load() method on the LoadVars object in ActionScript. 
	//This loads data from a remote URL as name value pairs (results are loaded into this object)
	//When finished, the callback function that you assigned is called
	myLoadVars = new LoadVars();
	myLoadVars.onLoad = load_callback;
	myLoadVars.load(url+"?data=Wazzup");
}
function load_callback(success, error) {
	trace("____________")
	trace("Finished executing the 'load_test()' fxn.");
	if (success) {
		trace("It was a success!")
		for (var i in this) {
			if (i != "onLoad" && i!="sendAndLoad" && i!="Method" && i!="owner" && i!="load" && i!="refName") {
				//The above != strings are methods/properties on the object that aren't hidden
				trace(i+"="+this[i]);
			}
		}
	} else {
		trace("It failed to load");
		trace(error)
	}
}

LoadVars.sendAndLoad

function LoadVars.sendAndLoad(url,
 destOb)
Sends variables and loads name value pairs from a remote URL

Sends variables and loads variables from a remote URL. This is usually used to contact a server-side script.
See also LoadVars.load. Check out the LoadVarsExample plugin in the plugins directory.

Parameters:
url
The URL to contact
destOb
Example:
function sendAndLoad_test(url) {
	//Equivalent to sendAndLoad method on the LoadVars object in ActionScript. 
	//This loads data from a remote URL as name value pairs into the destination LoadVars object that you specify
	//When finished, the callback function that you assigned is called
	myLoadVars = new LoadVars();
	myLoadVars.data = "yo";
	destination = new LoadVars();
	destination.onLoad = sendAndLoad_callback;
	myLoadVars.sendAndLoad(url, destination);
}
function sendAndLoad_callback(success, error) {
	trace("____________")
	trace("Finished executing the 'sendAndLoad_test()' fxn.");
	if (success) {
		trace("It was a success!")
		for (var i in this) {
			if (i != "onLoad" && i!="sendAndLoad" && i!="Method" && i!="owner" && i!="load" && i!="refName") {
				//The above != strings are methods/properties on the object that aren't hidden
				trace(i+"="+this[i]);
			}
		}
	} else {
		trace("It failed to load");
		trace(error)
	}
}

logger.config

function logger.config(info)
A level of logging

There are 7 levels of logging, increasing in severity. In the configuration.xml file you set the level of loggin to one of those levels of severity and all log attempts at that level or higher are logged. The default logging level is set to WARNING. Here are the levels:

FINEST See logger.finest
FINER See logger.finer
FINE See logger.fine
CONFIG See logger.config
INFO See logger.info
WARNING See logger.warning
SEVERE See logger.severe

Parameters:
info
String to log
Example:
logger.config("Log this!");

logger.fine

function logger.fine(info)
A level of logging

There are 7 levels of logging, increasing in severity. In the configuration.xml file you set the level of loggin to one of those levels of severity and all log attempts at that level or higher are logged. The default logging level is set to WARNING. Here are the levels:

FINEST See logger.finest
FINER See logger.finer
FINE See logger.fine
CONFIG See logger.config
INFO See logger.info
WARNING See logger.warning
SEVERE See logger.severe

Parameters:
info
String to log
Example:
logger.fine("Log this!");

logger.finer

function logger.finer(info)
A level of logging

There are 7 levels of logging, increasing in severity. In the configuration.xml file you set the level of loggin to one of those levels of severity and all log attempts at that level or higher are logged. The default logging level is set to WARNING. Here are the levels:

FINEST See logger.finest
FINER See logger.finer
FINE See logger.fine
CONFIG See logger.config
INFO See logger.info
WARNING See logger.warning
SEVERE See logger.severe

Parameters:
info
String to log
Example:
logger.finer("Log this!");

logger.finest

function logger.finest(info)
A level of logging

There are 7 levels of logging, increasing in severity. In the configuration.xml file you set the level of loggin to one of those levels of severity and all log attempts at that level or higher are logged. The default logging level is set to WARNING. Here are the levels:

FINEST See logger.finest
FINER See logger.finer
FINE See logger.fine
CONFIG See logger.config
INFO See logger.info
WARNING See logger.warning
SEVERE See logger.severe

Parameters:
info
String to log
Example:
logger.finest("Log this!");

logger.info

function logger.info(info)
A level of logging

There are 7 levels of logging, increasing in severity. In the configuration.xml file you set the level of loggin to one of those levels of severity and all log attempts at that level or higher are logged. The default logging level is set to WARNING. Here are the levels:

FINEST See logger.finest
FINER See logger.finer
FINE See logger.fine
CONFIG See logger.config
INFO See logger.info
WARNING See logger.warning
SEVERE See logger.severe

Parameters:
info
String to log
Example:
logger.info("Log this!");

logger.severe

function logger.severe(info)
A level of logging

There are 7 levels of logging, increasing in severity. In the configuration.xml file you set the level of loggin to one of those levels of severity and all log attempts at that level or higher are logged. The default logging level is set to WARNING. Here are the levels:

FINEST See logger.finest
FINER See logger.finer
FINE See logger.fine
CONFIG See logger.config
INFO See logger.info
WARNING See logger.warning
SEVERE See logger.severe

Parameters:
info
String to log
Example:
logger.severe("Log this!");

logger.warning

function logger.warning(info)
A level of logging

There are 7 levels of logging, increasing in severity. In the configuration.xml file you set the level of loggin to one of those levels of severity and all log attempts at that level or higher are logged. The default logging level is set to WARNING. Here are the levels:

FINEST See logger.finest
FINER See logger.finer
FINE See logger.fine
CONFIG See logger.config
INFO See logger.info
WARNING See logger.warning
SEVERE See logger.severe

Parameters:
info
String to log
Example:
logger.warning("Log this!");

objectToHash

function objectToHash(ob)
Converts and object to a hash map

Converts and object to a hash map. Hash maps are used throughout plugins to send containers full of multiple variables. This method will create a hash map from a normal object. See also hashToObject.

Parameters:
ob
Object to convert
Example:
var ob = new Object();
ob.score = 32;
ob.level = "Level of Death";
var hash = objectToHash(ob);

pluginDestroy

function pluginDestroy()
Function called when room level plugin is being destroyed

A room level plugin is instance based. Each instance is associated with a specific room. When that room is removed from the server, so too is the plugin. This function is called when that happens. It is usefull for cleaning up intervals, among other things.

Important note If you use setInterval in your plugin, you must clean it up using clearInterval in this function. If you don't then the interval will keep going forever and you'll have a memory leak. Eventually the server will run out of memory.

Example:
This example shows a setInterval being used and cleaned up:
var intervalId;
function pluginInit(hash) {
	intervalId = setInterval("moveProjectiles", 30);//calls every 30 ms
}
function moveProjectiles() {
	//do something
}
function pluginDestroy() {
	clearInterval(intervalId);//Cleans up interval
}
 

pluginInit

function pluginInit(hash)
A required event handler. It is executed when the plugin is first created.

This is a required function. It is executed when the plugin is first created. The parameter is a hash map. A hash map is easy to use. You access a veriable on it just by using syntax like this: hash.get("SomVar").

The hash contains variables that were specified in one of two places:
1.) The configuration file. When "installing" a plugin you add a bit of XML to the configuration.xml file. In this XML you can specify some initialization variables. In this example the variables 'DefaultWeapon' and 'NumberOfLevels' would exist in the hash map.
<Plugin>
	<Name>MyGame</Name>
	<Type>Script</Type>
	<Scope>Room</Scope>
	<File>plugins\MyGame.as</File>
	<Variables>
		<Variable>
			<Name>NumberOfLevels</Name>
			<Value>10</Value>
		</Variable>
		<Variable>
			<Name>DefaultWeapon</Name>
			<Value>Rail Gun</Value>
		</Variable>
	</Variable>
</Plugin>
2.) The other way to add variables (or overwrite variables) in the hash map is to do so at the time the plugin is created. See example.

Parameters:
hash
A hash map
Example:
From the Flash client you can create a room with a plugin like this:
//create room ob
var ob:Object = new Object();
ob.roomName = "Game2";
ob.zone = "Game Zone";
//add plugins array to room ob
ob.plugins = new Array();
//create plugin ob
var myPlugin:Object = new Object();
myPlugin.name = "MyGame";//Name must match whats in config
myPlugin.variables = {NumberOfLevels:10, DefaultWeapon:"Rail Gun"};
//add plugin ob to plugins array
ob.plugins.push(myPlugin);
//send it all to ElectroServer
es.createRoom(ob);
In the plugin, you'd have this function:
function pluginInit(hash) {
	var numLevels = hash.get("NumberOfLevels");
	var defaultWeapon = hash.get("DefaultWeapon");
}

pluginInterop

function pluginInterop(hash)
Event fired when a plugin is trying to be reached by another plugin

A plugin can send a request to another plugin. The target plugin captures this request in the pluginInterop event handler. A hash map is passed in. The pluginInterop function should return a hash map result. See also callRemotePlugin.

Parameters:
hash
Hash map
Returns:
Hash map

Example:
In this example imagine two plugins. One is a server level plugin called HighScoreListPlugin, and the other is a room level plugin called ShootemUpPlugin. The HighScoreListPlugin is used to save scores to a database and return the high score list. The ShootemUpPlugin is used to runt he game logic. It reports the scores at the end of a game to the HighScoreListPlugin.

Code in ShootemUpPlugin - (room level)
function gameOver(winner, winnersScore) {
	var ob = new Object();
	ob.winner = winner;
	ob.winnersScore = winnersScore;
	var hash = objectToHash(ob);
	var resultHash = callRemotePlugin("HighScoreListPlugin", hash);
	var resultOb = hashToObject(resultHash);
	//resultOb.highScoreList contains: jobe,300|kelly,200|mike,150
	server.sendMessage("public", "GameOver", resultOb);
}
Code in HighScoreListPlugin - (server level)
function pluginInterop(hash) {
	var ob = hashToObject(hash);
	saveUsersScoreInDatabase(ob.winner, ob.winnersScore);
	var returnOb = new Object();
	returnOb.highScoreList = getHighScoreList();
	return objectToHash(returnOb);
}

pluginRequest

function pluginRequest(hash)
Event handler that intercepts all inbound messages from the client.

When the client sends a message to the plugin, this is the function that captures it. All information from the client is contained in the hash map passed in. There are two properties on this hash map that you can always expect.

Mandatory Properties
ExecutingUserName This is the username of the user that made the plugin request. This is automatically added by ElectroServer.
Method This is the main "action" specified by the client to take. It can be any string value.

Parameters:
hash
A hash map
Example:
The client may send a request to a plugin like this:
var variables:Object = new Object();
variables.angle = 30;
variables.speed = 15;
//The 2nd parameter below comes through as the 'Method' variable on the hash in the plugin
es.pluginRequest("MyGame", "FireWeapon", variables);
In the plugin, you'd have this:
function pluginRequest(hash) {
	var caller = hash.get("ExecutingUserName");//username of person making the request
	var method = hash.get("Method");//Main 'action' they want to take
	if (method == "FireWeapon") {
		//grab the useful variables out of the hash
		var angle = Number(hash.get("angle"));
		var speed = Number(hash.get("speed"));
		//execut a function passing in the variables and the username
		fireWeapon(caller, angle, speed);
	} else if (method == "PickUpPowerUp") {
		pickUpPowerUp(caller);
	}
}

pluginUserEnter

function pluginUserEnter(username)
Event fired when a user enters room

When a user enters the room this function is executed, if it exists (not mandatory). The user's username is passed in.
See also pluginUserExit.

Parameters:
username
The username of the user entering room
Example:
function pluginUserEnter(username) {
	trace(username +" just entered!");
	spawnNewCharacterOnMap(username);//Just some function that could exist
}

pluginUserExit

function pluginUserExit(username)
Event fired when a user leaves room

When a user leaves the room this function is executed, if it exists (not mandatory). The user's username is passed in.
See also pluginUserEnter.

Parameters:
username
The username of the user leaving room
Example:
function pluginUserExit(username) {
	trace(username +" just left!");
	destroyCharacterOnMap(username);//Just some function that could exist
}

readFile

function readFile(filePath)
Loads a local text file into a variable.

Allows a plug-in to load a text file and have the contents returned.
Also see isFile, writeFile, deleteFile, doesFileExist.

Parameters:
filePath
A string pointing to file on the hard drive. This can be relative (starting with the ElectroServer 3 install directory) or absolute.
Example:
var contents = readFile("some_directory/myText.txt");

removeUserServerVariable

function removeUserServerVariable(username,
 name)
Removes a user server variable

Removes a user server variable based on a username and a variable name. See also setUserVariable, getUserVariable.

Parameters:
username
Username
name
Name of the variable
Example:
removeUserServerVariable("mike", "databaseId");

sendRawMessage

function sendRawMessage(type,
 message,
 users)
Sends a raw message to a room or to an array of specific users

Sends a raw message to a room or to an array of specific users. This is generally used when trying to conserve bandwidth. The messages sent are completely customizable and are not formatted by the server when sent.

In order for a client to send/receive a raw message it must use the registerRawHandler method. See the client documentation.

If the first parameter is "public", then only the 2nd parameter is needed. It contains the message to be sent. If the first parameter is "private", then the 2nd parameter is the message and the 3rd is an array of usernames.

Parameters:
type
"public" or "private"
message
The message to send
users
An array of usernames. Only used if the message is private
Example:
Sending a public raw message:
This sends a light weight message of around 20 bytes, but it contains 4 pipe delimited variables!
sendRawMessage("public", "a|30|s|20|x|10|y|15");//angle, speed, x, y
Sending a public raw message:
This sends a light weight message of around 10 bytes to team A.
var teamA = ["mike", "jobe", "kelly"];
sendRawMessage("private", "u|mike|h|80", teamA);

server.createRoom

function server.createRoom(roomOb)
Creates a room

Creates a room in a specific zone. See below for description of each of the configurable properties of a room. See also server.moveToRoom to see how to put users into this new room.

This method returns a number as a result code. Here is what they mean:

0 - Successfully created room
1 - Invalid parameters
2 - Room already exists
3 - Failed creating room. Usually this is due to a plugin error in the room you are creating

Note: The room is created with no users in it. Normally rooms are automatically deleted when there are no users in it. That will happen here too, but only after it has at least 1 user join. So a room is created, has 0 users, 5 minutes later a user joins and then leaves. The room is automatically deleted. At this time there is no way to create a persistent room from a plugin.

Properties of the room object

The roomOb object can contain many properties to customize the room. Some of them are required while others are not.

password If blank the room is not password protected. If it contains anything then the room is password protected.

userVariablesEnabled If blank or 'false' then user variables are not enabled for this room (increases performance). If 'true', then user variables are enabled for the room. See createUserVariable, login, or userVariableUpdated for more information.

hidden If blank or 'false' then the room is not hidden. If 'true', then the room is hidden and cannot be seen by the other rooms in your zone. This is often used for game rooms.

zone This is the zone in which you want to create a room. If the zone does not yet exist then it will be created. Required.

roomName The name of the room to be created. Required.

numbered If blank or 'false' the room does not number its users.

capacity If blank or -1 then the room has no maximum size. If the number is greater than 0 then the room created can only grow to a certain user size.

description Can be left blank or be a string describing the room.

updatable If blank or 'true' then the room is updatable. If 'false' then it is not. A room that is updatable receives zone updates and roomList updates. If it is not updatable then it only receives updates regarding itself (userListUpdates, etc). This increases performance for that room, recommended for games.

FloodingFilterEnabled If blank it is set to false, which means it's not enabled. When enabled the room checks to see if users send messages too quickly to the server. This is called flooding. If flooding is detected then the user is kicked. Flooding properties can be configured in the configuration.xml file.

userListEnabled The default is true. When enabled, the users in a room are informed of the list of users in that the room. Also the room receives userListUpdated events when users join or leave. If set to false, then ElectroServer sends no information or updates about the users in a room. This can be useful to set to false in rooms that have many users to cut down on message traffic.

roomVariables Can be left blank if you don't want to create a room with room variables. This is an array of objects, each of which describes a room variable. The properties of a room variable are 'name' (name of variable), 'data' (value of variable), 'persistent' (optional Boolean), 'locked' (optional Boolean). Room variables can be created using the createRoomVariable method. See that method for more details.

plugins Optional. This property is an array of objects. Each object represents a plugin that you want to instantiate for the room. The 'name' variable on that object is the name of the plugin. The object can contain another object called 'variables' if you want to pass variables into the plugin. Using plugins is an advanced feature that requires a moderate level of understanding of ElectroServer and the ElectroServer object.

Parameters:
roomOb
An object representing the room to be created
Returns:
A result code

Example:
Here is the most basic way to create a room:
var roomOb = new Object();
roomOb.zone = "Chat Area";
roomOb.roomName = "Lobby";
var resultCode = server.createRoom(roomOb);
Here is a long-winded example of creating a room with all properties used except plug-ins:
var roomOb = new Object();
roomOb.zone = "Chat Area";
roomOb.roomName = "Lobby";
roomOb.hidden = false;
roomOb.numbered = false;
roomOb.userVariablesEnabled = false;
roomOb.password = "";
roomOb.capacity = -1;
roomOb.updatable = true;
//room vars
roomOb.roomVariables = new Array();
var ob = new Object();
ob.name = "BackgroundMusic";
ob.data = "AmbientSounds";
roomOb.roomVariables.push(ob);
//end room vars
var resultCode = server.createRoom(roomOb);
Here is an example creating a room with two plugins:
var roomOb = new Object();
roomOb.zone = "Chat Area";
roomOb.roomName = "Lobby";
roomOb.plugins = new Array();
roomOb.plugins.push({name:"ShootEmUpPlugin"});
roomOb.plugins.push({name:"ScoreSaverPlugin"});
var resultCode = server.createRoom(roomOb);

server.moveToRoom

function server.moveToRoom(who,
 zoneName,
 roomName,
 password,
 numbered)
Moves a user to a room

Moves a user to a specific room in a specific zone. See also server.createRoom.

This returns a result code. Here is what they mean:

0 - Successfully joined
1 - Zone doesn't exist
2 - Room doesn't exist
3 - Invalid password
4 - Room full
5 - User doesn't exist

Parameters:
who
The username
zoneName
The zone name
roomName
The room name
password
The password, if any
numbered
true or false (Optional. Default is false.)
Returns:
A result code

Example:
Moves a user to a room.
var resultCode = server.moveToRoom("mike", "Chat Zone", "Lobby");
Creates a room and puts a user in it.
function creatRoomAndPutUserInIt(user) {
	var roomOb = new Object();
	roomOb.zone = "Chat Area";
	roomOb.roomName = "Lobby";
	var resultCode = server.createRoom(roomOb);
	if (resultCode == 1) {
		//room created successfully
		var resultCode2 = server.moveToRoom(user, roomOb.zone, roomOb.roomName);
	}
}

server.sendMessage

function server.sendMessage(type,
 one,
 two,
 three)
Sends message to specific user(s), the room, a specific zone, or the whole server

Sends a message to an array of users, to the room, to a specific zone, or to the whole server. This function takes up to 4 parameters. The values of the parameters vary depending on the type of message being send. The parameters are explained below and there are 4 examples given.

Parameters:
type
The message type: "public", "private", "zone", or "server"
one
Varies depending on 'type'. In the order above, this can be Method, Array of Users, Zone Name, or Method
two
Varies depending on 'type'. In the order above, this can be Variables object, Method, Method, Variables object
three
Varies depending on 'type'. Its blank for "room" type, and Variables object for the other 3 types
Example:
To send room message:
function gameOver(winner, bestScore) {
	//Sends a message to everyone in a room saying that the game is over, who won, and their score
	var variables = new Object();
	variables.winner = winner;
	variables.bestScore = bestScore;
	server.sendMessage("public", "GameOver", variables);
}
To send a private message:
function pickedUpItem(array_of_usernames, user_of_importance, item) {
	//This informs a team of users in a game that 1 guy on the team picked up a special item
	var variables = new Object();
	variables.user = user_of_importance;
	variables.item = item;
	server.sendMessage("private", array_of_usernames, "PickedUpItem", variables);
}
To send a message to a specific zone:
function messageFromAdmin(message) {
	//Sends a message to everyone in a zone from the admin
	var variables = new Object();
	variables.message = message;
	server.sendMessage("zone", "Poker Zone", "MessageFromAdmin", variables);
}
To send a message to the whole server:
function messageFromAdmin(message) {
	//Sends a message to everyone on the server from the admin
	var variables = new Object();
	variables.message = message;
	server.sendMessage("server", "MessageFromAdmin", variables);
}

setInterval

function setInterval(functionName,
 interval)
Enables a function to be automatically executed once per time interval

Works much like setInterval does in Flash. The main difference is that it takes a string name for the function instead of a direct reference. See also clearInterval and pluginDestroy.

Note: You must clear the interval using clearInterval when the room is destroyed or earlier. If you do not clear the interval, then it will keep going even without the room. This will cause a memory leak and take up extra CPU.

Parameters:
functionName
String name of the function
interval
The time in miliseconds between executions
Returns:
A numeric id.

Example:
var intervalId;
function pluginInit(hash) {
	intervalId = setInterval("moveProjectiles", 30);
}
function moveProjectiles() {
	//do something
}
function pluginDestroy() {
	clearInterval(intervalId);
}

setUserServerVariable

function setUserServerVariable(username,
 name,
 value)
Sets a variable on a user that the client doesn't know about

Sets a variable on a user that the client doesn't know about. This is typically used for information that the server might want to keep track of, such as a database id of a user, etc. This is different than regular user variables, which are seen by the client.
See also getUserServerVariable, removeUserServerVariable.

Parameters:
username
Username
name
Name of the variable
value
Value of the variable
Example:
setUserServerVariable("mike", "databaseId", "27");

trace

function trace(info)
Shows output on the ElectroServer console

This method is generally used for debugging. It shows output to the console window.

Parameters:
info
A string to be printed to the console
Example:
function pluginInit(hash) {
	trace("Plugin initialized!!");
}

updateRoomVariable

function updateRoomVariable(name,
 value,
 locked)
Updates an existing room variable

Updates the value and locked property of an existing room variable. See also createRoomVariable, deleteRoomVariable, getRoomVariables

Parameters:
name
Name of variable
value
Value of variable
locked
Locked propert (Boolean)
Example:
updateRoomVariable("secretWord", "open seaseme", false);

updateUserVariable

function updateUserVariable(user,
 name,
 value)
Updates a specific user variable

Updates a user variable on a specific user. See also getUserVariables, createUserVariable, deleteUserVariable.

Parameters:
user
Username that the variable should belong to
name
Variable name
value
Variable value
Example:
updateUserVariable("mike", "age", random(100));

writeFile

function writeFile(filePath,
 content,
 append)
Writes a text file to the hard drive.

Allows a plug-in to create a text file, replace a text file, or append to the content of an existing text file.
Also see isFile, doesFileExist, deleteFile, readFile.

Parameters:
filePath
A string pointing to where the file should be written on the hard drive
content
A string containing the content to be written to the file
append
A Boolean value specifying if the content should be appended to the existing content if the file already exists, or if it should be replaced. If true then the content is appended.
Returns:
A string that is the file contents

Example:
writeFile("some_directory/myText.txt", "Hello world", false);


The documentation was generated from the following file:


Generated on 1/20/2006 10:36:46 AM by AS2Doc