Gw Temp

Menu

Tutorial - 'A Scripters Guide To Sphere' by Zennith

An item about RPGMaker 2000 posted on

Blurb

The start of a series of Sphere tutorials that will help out any new comer to Sphere!

Body

General

Scripts and Scripting
Parameters and Terms

Sphere Functions and Objects

Script Functions
Miscellaneous
Engine Functions
Log Object
Video
Graphic Primitives
Keyboard
Mouse
Time
Byte Array Object
Networking
Color Object
Maps
Input
Camera
Persons
Spritesets
Sound
Font Object
Windowstyles
Images
Surface Objects
Animations
Files
Raw Files

Credits




General



Sphere supports SpiderMonkey's version of JavaScript, as well as it's own functions and objects. JavaScript is a browser language, designed for creating web pages. As Sphere proves, it can be put to other uses. There are three parts to JavaScript - Core, Client-side and Server-side. Sphere supports only Core JavaScript, as well as it's own functions and objects.




Each game has a main script. This is the script specified in the Game Settings window, and does not necessarily have to be called main.js- it could be named anything. This script is read by the game engine when your game is run. All other scripts must be included in the main script via the EvaluateScript() and EvaluateSystemScript() functions. It is not necessary to have more than one script, as all of your code could be written directly into the main script. However, having different scripts for different things makes it easier to organize. For example you could have one script for just your menu system, and one that deals with character stats, etc.



The game function is the function that the engine immediately looks for and executes. This is the only function that is automatically executed. All other functions must be 'pointed to' through the game function or activated via triggers, personal scripts or special scripts.
Syntax: function game(parameters){commands}



Scripting may go in a script file, be included in a map or be attached to persons. Persons may have 5 different personal scripts. Maps may have Triggers, which are invisible points on the map that run scripts when the Input Character steps on it. Maps also have special scripts, which are found in Map Properties (see the Map menu on SDE's title bar).



Scripts can be made with any word processor, then saved as script (.js) files in Sphere.




Scripts and Scripting



Script Files: Scripting can go in .js files. To create a new script file, simply go to File > > New > > Script. One script will be the main script. All other scripts must be included in the main script via EvaluateScript() and/or EvaluateSystemScript().





Triggers: On maps, you may add triggers. Simply right-click on any tile, and choose Insert Entity > > Trigger. The scripting that is in a trigger will be run when the base of the input character touches the tile that the trigger is on.





Person/Personal Scripts: Each person entity has five personal scripts. They are On Create, On Destroy, On Activate (Touch), On Activate (Talk), and On Generate Commands. To see these, place a person on the map in SDE (Insert Entity > > Person) and click on the drop-down box below the word 'scripts'

On Create: The scripting is run when the person is created.


On Destroy: The scripting is run when the person is destroyed.


On Activate (Touch): The script is run when the input character touches the person.


On Activate (Talk): The script is run when the input character is within the 'talk distance' of the person and the 'talk key' is pressed. (Note: talk distance and talk key are set with SetTalkDistance() and SetTalkActivationKey())


On Generate Commands: The script will be run when the person's command queue is empty.






Special Scripts: Each map has its own 'special scripts'. To see them go to 'Map' on the menu bar, and choose the 'Properties' command. The special scripts are Entry, Exit, North, East, South, and West.

Entry: This script is run when the map is opened.


Exit: The script is run when the map is closed.


North: This script is run when the input character crosses the North border.


East: This script is run when the input character crosses the East border.


South: This script is run when the input character crosses the South border.


West: This script is run when the input character crosses the West border.






Parameters and Terms



Below is an explanation of terms and concepts that you should understand. The more difficult parameters are also explained here, as well as parameters that are used very often.




Color: Sphere uses color in various functions. A parameter that passes color is always a color object. To learn how to make a color object, see CreateColor() in the Colors section of this document.



Masks: Sphere supports various color masks. A mask is a color that blankets something - be it font, the screen, or a spriteset, etc. This alters the color of the original image. The lower the alpha of a pixel on the original image, the less the mask effects that pixel.



Filenames: Filenames are written as strings, with the extension included; "filename.extension". For example, a png file named "Portrait" would be called like so; "Portrait.png". Keep in mind that all files must be in their proper directories.



Time: All references to time in Sphere are by milliseconds. When called as a parameter, it must be a number.




Coordinates and Ordered Pairs: There is an invisible Cartesian plane over anything that can be seen - maps, the engine screen, images, spritesets, etc. A Cartesian plane is like a grid. Each square on the grid has it's own ordered pair to identify it, based on the square's location. (An ordered pair is (x, y) ). For example, the upper-left square on anything is (0, 0).



Maps: Maps actually have two different grids over them. On one grid, each square is a tile. On the other, each square is a pixel.



Below is an image to illustrate the Cartesian planes over maps. The larger blocks represent tiles. The smaller blocks inside the "tiles" are pixels.






Engine Screen: The Cartesian plane over the engine screen is a lot like the pixel Cartesian plane over maps. The difference is that all points on the engine screen are always visible (unless the screen is too big for the computer monitor).



Blitted Graphics: All graphics that are blitted to the screen also have Cartesian planes over them. (These graphics include images, surface objects, window styles, etc).



Spritesets: Each spriteset image has it's own Cartesian plane.




Throughout this document I will be referring to coordinates and ordered pairs. These refer to the screen's Cartesian plane, unless stated otherwise.





Script: Scripting as a parameter must be in quotes. It may contain one command, or multiple commands. If you use multiple commands, you will have to use semi-colons after each one. A semi-colon is not needed for one command.



It is recommended that you use one command only. If you have something that requires multiple commands, make a function and call the function as the command for the script parameter.


If the scripting is not in quotes, it may be run automatically.



Pixels: A pixel is the smallest element of computer graphics. It is a rectangle with one color and alpha. Many values are by pixel. Distance is often measured in pixels. The size of graphics is also measured in pixels. So is the movement of spritesets




Movement: Movement is by pixels. For example, moving a spriteset up one moves it up by one pixel, not by one tile.



Location You may place various things on the map (spritesets, images, window_styles, etc). Each time that you do, you will have to specify the coordinates on the map for where it will be placed. Below is a quick guide to tell you which part of the image matches the coordinates that you specify.



Location of Spritesets: goes by the pixel in the middle of the base. If the width of the base is even, it is the middle-left pixel. If height is even, it is the upper-middle pixel.



of Tile on a map: The ordered pair refers to tiles, not pixels. So (5, 0) would give you the sixth tile on the top row of the map


of Image: Upper-left pixel.


of Animation: Upper-left pixel.


of WindowStyle: Upper-left pixel of background


of String (with Font): The upper-left pixel of the first character in the string.






Back-buffer/ Video-buffer: When drawing with code, you are actually drawing to the back-buffer, not the screen. The back-buffer is a section of memory reserved for graphics that are not run by the map engine. The image(s) on the back-buffer can only be displayed with FlipScreen(). This transfers the image to the screen, clearing the back-buffer. Until the map engine updates again, the map will not be on the back buffer. If you use FlipScreen() twice or more in a row, without giving the map engine a chance to process, you will see a black screen unless you use RenderMap() before the FlipScreen() command.



In other words, the Back-buffer is like an invisible screen. You place your pictures on it just like you would put them on the real screen. Then you display them with FlipScreen()



FlipScreen: FlipScreen() displays any drawings from the back-buffer onto the screen. It clears the back-buffer. It displays the image for one millisecond. You may use a delaying function to hold the image on the screen for a longer amount of time. FlipScreen() is not needed for things that the map engine processes, such as changes to tiles and manipulation of spritesets, color masks that effect spritesets or the screen, etc.




Arrays of objects: when something returns an array of objects, use it by typing object_name[index].property or object_name[index].method. Object_name is the name of the object and index is the index value of the item in the array. Property is the name of the property and method is the name of the method. Also, array[index]; will return that particular variable. Example - var startFrame=spritesetFrames[0];




Queues: A queue is like waiting in line. One command is waiting to be processed right after the other.

Command Queues: Each person has a command queue. It is empty unless you assign commands to the person. The first command to be assigned is the first one processed, the second is processed next, etc.



Key Queues: When the player presses a key, it is put in the key queue. Normally, this does nothing at all. But, with a bit of scripting, the keys can be made to do things (change a variable, open a menu, and many other things)



Once a command is executed, or a key is used, it is taken out of the queue.



Map Engine: The map engine processes anything concerning tiles or spritesets. It also processes color masks that affect spritesets and that affect the entire screen. It also handles the position of the camera.










Sphere Functions and Objects








Script Functions




EvaluateScript(script)
Reads a script from your game's script folder and includes it in the current script.
Parameters script: the script that is read. See rules for filenames.
ExampleEvaluateScript("Menu.js"); /* the above line is essentially the same as placing every line from Menu.js there. */
Notes: This gives you more freedom than EvaluateSystemScript(script); because you create the scripts yourself.


EvaluateSystemScript(script)
Evaluates a script from Sphere's system/scripts directory and reads it into the current script.
Parameters script: the name of the system script to be evaluated.
ExampleEvaluateSystemScript("fademessage.js"); /* This is the same as including every line from "fademessage.js" in the current script */
Notes:System scripts are found in the system/scripts directory of your Sphere folder. You may not alter them, because everyone else's copy of the system script will be the original, not your copy.


GarbageCollect()
Invokes JavaScripts garbage collector
Parameters None
Example /* let's say that we have just finished using some objects, and know that we will not need them again. We can get rid of them to free some memory, using GarbageCollect() ) */GarbageCollect();
Notes: The garbage collector erases unused objects from memory. It is automatically invoked every now and then, but you can use it at will with this function.








Miscellaneous




CreateStringFromCode(code)
Creates a single character string based on the specified code.
Parameters code: must be an integer
ExampleCreateStringFromCode(49); // returns "1"CreateStringFromCode(292);// returns "$"


To figure out what the string will be take the number passed as the code and divide it by 256. The remainder will equal the font number of the character in the string.








Engine Functions




GetVersionString()
Returns a string depending on the version of Sphere that is used. (e.g, if it is Sphere.97 it returns v.97a)
Parameters None.
Examplevar text=GetVersionString();var font=GetSystemFont();font.drawText(60, 25, text);FlipScreen();Delay(1000); /* This might be used in the introduction of a game (the part where the game is loading and you see logos and such) */


GetGameList()
Returns an array of game objects. The name of each game that is in the 'games' directory of the sphere folder will be returned. The games are indexed by alphabetical order.
Parameters None.
Examplevar games=GetGamesList() /* games is now an array, and each element returns a string with the name of a game */


Game_object is any variable that returns a game object.



Game_object.name
Returns the title of the game.
Examplevar theGames=GetGameList();var thirdGame=theGames[2].name; /* this would return the name of the third game in the list */


Game_object.directory
Returns the directory for the game. The game must be in the games folder.
Examplevar theGames=GetGameList();var gamePath=theGames[0].directory;



ExecuteGame(directory)
Executes the game found in sphere/games/directory
Parameters Directory: Returns the path leading to the game file, if the file is in a games folder.
Examplevar theGames=GetGameList(); /* theGames is now an array of game objects */var gamePath=theGames[0].directory; /* gamePath returns the directory for the first game object */ExecuteGame(gamePath); /* this executes the first game object */


Exit()
Exits the Sphere engine unconditionally.
Parameters None
ExampleExit();


Abort(message)
Exits the Sphere engine unconditionally and displays "message"
Parameters Message: a string that is displayed after the Sphere engine exits.
Exampleif (error==true){Abort("There was an error. Sorry for the inconvenience"); /* provided that there is a script to make the variable error return true if there is an error, this will exit the engine when there is a problem */







Log Object



The log object is used for debugging your game and testing it. It is simply a text document that you can write to. The log is written to while the game is running, and the file is modified immediately - before you exit the game.



If you create the log as filename.log or as filename.txt or with any extension it will be openable as a .txt document. You may use other extensions to open the file with a program other than NotePad but you cannot save it as anything other than a .txt document. It is strongly recommended that you use the .txt or the .log extension. Apparently only .log or .txt log files are openable when the game is running.




OpenLog(filename)
Creates a log object from an existing log file in the log folder, or from a newly created file and new folder if necessary.
Parameters filename: the name of a log file, such as "MyGame.log"
Examplevar theLog=OpenLog("Whatever.log"); /* if "Whatever.log" already exists in the log folder, this simply opens it and returns a log object to be used. If it does not exist, it will be created. The log folder will also be created if necessary */


Log_object is any variable that returns a log object.



Log_object.write(text)
Writes the specified text in the log file.
Parameters text: a string of text
Examplevar theLog=OpenLog("Record.log");theLog.write("This is an entry in my log");



Log_object.beginBlock(name)
Creates a "block" in the text of the file. A block is denoted by a +, and it's title is the string you typed for name It is used to organize a log file.
Parameters name: A string. This string will be written in the log at the appropriate place, with a + in front of it to denote the beginning of a block.
Examplevar log=OpenLog("myGame.log");log.beginBlock("Town.rmp info");log.write("This is a map of a town"); /* in the log file you will see "+Town.rmp info", and below that will be "This is a map of a town". */


Log_object.endBlock()
Closes the current block. The ending of a block is denoted by -name_of_block.
Parameters None
Examplevar log=OpenLog("myGame.log");log.beginBlock("Town.rmp info");log.write("This is a map of a town");log.endBlock(); /* In the log file, you will see the following. +Town.rmp info This is a map of a town -Town.rmp info */









System Interfaces





Video




FlipScreen()
Displays the image from the back-buffer onto the video screen, for one millisecond. This clears the back-buffer.
Parameters None
Examplevar portrait=LoadImage("michael.png");portrait.blit(15, 35);FlipScreen();Delay(3000); /* Delay is a user-defined function */
Notes: FlipScreen must be used to see anything that has been drawn on the back-buffer



SetClippingRectangle(x, y, width, height)
Sets a clipping rectangle on the back-buffer. Anything drawn outside the boundaries of the rectangle will not be visible, even after FlipScreen() is called. The clipping rectangle is invisible
Parameters x and y: the x and y coordinates of the upper-left corner of the clipping rectangle. width: the width of the clipping rectangle, in pixelsheight: the height of the clipping rectangle, in pixels.
Examplevar BobPic=LoadImage("FullLenth.png"); var JennaPic=LoadImage("FullLength2.png")BobPic.blit(15, 20);JennaPic.blit(85, 20); /* we have drawn two images side by side */SetClippingRectangle(15, 100, 140, 85); /* both pictures are full-length portraits of Bob and Jenna. But we only want to see their faces, so we "clipped" the top parts */FlipScreen();Delay(2000); // Delay() is a user-defined function.




ApplyColorMask(color)
Blankets the screen with the specified color.
Parameters color: a color object.
Examplevar theColor=CreateColor(200, 0, 0, 90);
ApplyColorMask(theColor);
/* covers the screen with theColor */
Notes: In order to see the map beneath the color mask, the alpha of the color object must be below 255.




SetFrameRate(fps)
Sets the maximum number of frames that the engine can draw per second.
Parameters fps: frames per second. Must be a number.
ExampleSetFrameRate(80);




GetFrameRate()
Get the current frame rate of a map.
Parameters None
Examplevar framerate=GetFrameRate();
Notes: The frame rate is set when you run a map with MapEngine() and can be changed with SetFrameRate().



GetScreenWidth()
Returns the width of the engine screen, in pixels.
Parameters None
Examplevar width=GetScreenWidth();
Notes: screen width is the same number that is set in the Game Settings dialog in SDE. This number could be changed by the player if he or she prefers the screen to be bigger or smaller than you have it set, so it is best to use GetScreenWidth() instead of the number that you set.



GetScreenHeight()
Returns the height of the engine screen, in pixels.
Parameters None
Examplevar height=GetScreenHeight();
Notes: screen height is the same number that is set in the Game Settings dialog in SDE. This number could be changed by the player if he or she prefers the screen to be bigger or smaller than you have it set, so it is best to use GetScreenHeight() instead of the number that you set.






Graphic Primitives




Point(x, y, color)
The pixel located at (x,y) will be masked by the color specified in the function.
Parameters x: the x coordinate of the map. Must be a number. y: the y coordinate of the map. Must be a number. color: the color of the point. Must be a color object.
Examplevar white=CreateColor(255,255,255);Point(15, 15, white); FlipScreen();Delay(2000);




Line(x1, y1, x2, y2, color)
Plots a line on the screen from(x1, y1) to (x2, y2).
Parameters x1, y1: one end of the line. x2, y2: the other end of the line. color: the color of the line.
Examplevar white=CreateColor(255, 255, 255); Line(45, 70, 95, 70);FlipScreen();Delay(2000); /* this draws a horizontal line that is 50 pixels wide. Delay() is a user-defined function. */




GradientLine(x1, y1, x2, y2, color1, color2)
Draws a line from (x1, y1) to (x2, y2) that fades from color1 to color2.
Parameters x1: x coordinate for the first pair. y1: y coordinate for the first ordered pair. x2: x coordinate for the second ordered pair. y2: y coordinate for the second pair. color1: the color that is at (x1, y1) color2: the color that is at (x2, y2)
Examplevar blue=CreateColor(0, 0, 230);var white=CreateColor(255, 255, 255); GradientLine(30, 15, 105, 80, blue, white);FlipScreen();Delay(1000);
Notes: The pixel at (x1, y1) will match the values of color1. The pixel at (x2, y2) will be color2. The two colors will blend more and more towards the halfway point.



Triangle(x1, y1, x2, y2, x3, y3, color)
Draws a triangle filled with the specified color. The three points are (x1, y1), (x2,y2), (x3, y3).
Parameters x1, y1: one set of coordinates. x2, y2: another set of coordinates. x3, y3: the third set of coordinates. color: the color of the triangle. Must be a color object.
Examplevar theColor=CreateColor(43, 200, 57); Triangle(15, 10, 40, 5, 30, 75, theColor);FlipScreen();Delay(2000); /* this draws a triangle, with one point at (15, 10), one at (40, 5), and one at (30, 75) */



GradientTriangle(x1, y1, x2, y2, x3, y3, c1, c2, c3)
Draws a triangle that fades from one color to another to a third color.
Parameters x1, y1: an ordered pair. One point of the triangle. x2, y2: an ordered pair. Another point of the triangle. x3, y3: another ordered pair, and the last point of the triangle c1: the color at (x1, y1). c2: the color at (x2, y2) c3: the color at (x3, y3)
Examplevar red=CreateColor(255, 0, 0);var green=CreateColor(0, 255, 0);var blue=CreateColor(0, 0, 255); GradientTriangle(15, 15, 60, 15, 35, 75, red, green, blue);FlipScreen();Delay(4000); /* the corner at (15, 15) is red, the corner at (60, 15) is green and the corner at (35, 75) is blue */



Rectangle(x, y, w, h, color)
Draws a rectangle with the upper-left corner at (x, y) with a width of w and a height of h. Said rectangle will be filled with the specified color.
Parameters x: the x coordinate of an ordered pair. y: the y coordinate of an ordered pair. width: the width of the rectangle height: the height of the rectanglecolor: the color of the rectangle.
Examplevar gray=CreateColor(127, 127, 127);Rectangle( 65, 30, 50, 50, gray);FlipScreen();Delay(3000);



GradientRectangle(x, y, w, h, c_ul, c_ur, c_lr, c_ll)
Draws a rectangle at (x, y) of width w and height h. The four corners each have their own color and said colors blend more and more the further away from the corners the pixel is.
Parameters x, y: an ordered pair. w: width of the rectangleh: height of the rectanglec_ul: color of the upper-left cornerc_ur: color of the upper-right cornerc_lr: color of the lower-right cornerc_ll: color of the lower-left corner.
Examplevar color1=CreateColor(30, 24, 100);var color2=CreateColor(0, 255, 255);var color3=CreateColor(255, 255, 255);var color4=CreateColor(0, 0, 90);GradientRectangle( 55, 20, 60, 45, color1, color2, color3, color4);FlipScreen();Delay(3000); /* the color of the upper-left corner is color1, the upper-right corner is color2, the lower-right corner is color3, and the lower-left corner is color4 */






Player Input






Sphere supports keyboard input, mouse input and will eventually support joysticks.



The arrow keys automatically move the input character when pressed. With the following functions, you can allow the player to use the mouse or keyboard keys for a variety of purposes.






Keyboard



Keys.txt has a list of the names of the keys on the keyboard. It is found in the docs directory of the Sphere folder.



AreKeysLeft()
Returns a Boolean true or false depending on whether there are keys left in the input queue. True if keys are left.
Parameters None.
Examplewhile(AreKeysLeft==true)
{var font=LoadFont("roman.rfn");var x=MapToScreenX(15);var y=MapToScreenY(25);font.drawText(x, y, "Stop pounding the keys!");}


GetKey()
Returns the first key in the input queue. If there are no keys in it, Sphere will wait until there are.
Parameters None
Exampleif(GetKey()!=5){ShowText(15, 15,"You guessed wrong. The answer was 5", 4000)}


IsKeyPressed(key)
Searches the input queue for "key". If the key has been pressed, it returns true. If not, it waits for the key to be pressed.
Parameters key: the name of a key. Refer to key.txt of the docs folder in your Sphere directory.
Example var font=GetSystemFont();
var done=false;
while(done==false)
{
font.drawText(15, 15, "Hello");
FlipScreen();

if(IsKeyPressed(KEY_ENTER))
{done=true}
}



GetKeyString(key, shift)
Returns a string based on the key that is passed. Shift is a Boolean that determines whether to use the upper/special case of the key.
Parameters key: the name of a key. Refer to keys.txt.shift: a Boolean true/false. False returns the normal case of the key, true returns upper/special case.
Examplevar character=GetKeyString(A, false);var font=GetSystemFontfont.drawText(65, 65, character);FlipScreen();Delay(2000);





Mouse



No mouse input is automatically supported by the engine. You must use the mouse functions to allow the player to use the mouse in the game.



The mouse cursor is represented by an image. You may use the system cursor with GetSystemArrow() or use your own graphics.




SetMousePosition(x, y)
Sets the position of the mouse cursor.
Parameters x: the x value of an ordered pairy: the y value of an ordered pair
ExampleSetMousePosition(15, 15);



GetMouseX()
Returns the x position of the mouse cursor if it is within the engine screen.
Parameters None
Examplevar x=GetMouseX();



GetMouseY()
Returns the y position of the mouse cursor if it is within the engine screen.
Parameters None
Examplevar y=GetMouseY();



IsMouseButtonPressed(button)
Returns true if the specified mouse button is pressed
Parameters button: MOUSE_LEFT, MOUSE_MIDDLE, or MOUSE_RIGHT.
Exampleif(GetMouseX=15 and GetMouseY=80 and IsMouseButtonPressed(MOUSE_LEFT)){switch=true} /* Pretend that there is a switch located at (15, 80). If the player clicks on it with the mouse, the switch has been set to true*/







Time




GetTime()
Returns the time, in milliseconds. The value that represents time steadily increases by one for each millisecond that passes.
Parameters None
Examplevar Start=GetTime();var End=Start+90000;if(Start==End){SomeFunction()}
/* The value of Start is increased by one every millisecond. Nine seconds after Start is declared, SomeFunction() is run. */







ByteArray Object


This object is primarily used for networking. In order to send information across the Internet the information must be in binary format. To send words or numbers across the Internet, each letter must be translated into binary. Each letter of the word is an element in the array, whose value is it's equivalent in binary language. For example, lowercase "e" in binary language is 101. So if we do var greeting=CreateByteArrayFromString("Hello"); then greeting[1] will equal 101.



So to send the word "Hello" to another computer you would have to do CreateByteArrayFromString("Hello"); and send the ByteArray to the other computer. Then that computer would "decode" it, so to speak, with CreateStringFromByteArray(array).






CreateByteArrayFromString(string)
Returns a ByteArray object based on the specified string.
Parameters string: any string
Examplevar charPortrait=CreateByteArrayFromString("Lynn.png"); /* this translates the string "Lynn.png" into data that can be sent across the Internet */




CreateStringFromByteArray(array)
Creates a string based on a byte_array object.
Parameters array: a ByteArray object.
Examplevar image=CreateStringFromByteArray(charPortrait); /* charPortrait is a previously made byte_array */


ByteArray_object is any object that returns a byte array.

ByteArray_object.length
Returns the length of the ByteArray object. Length is the number of elements in the array.
Examplevar byteArray=CreateByteArrayFromString("Hello");var byteLength=byteArray.length;







Networking



GetLocalName()
Returns the IP address of the computer on which the game is running.
Parameters None
Examplevar compName=GetLocalName();



GetLocalAdress()
Returns a string with the IP address of the computer on which the game is being run.
Parameters None
Examplevar address=GetLocalAddress();



OpenAddress(address, port)
Attempts to open a connection with the computer specified by "address" on "port". Returns a socket object if successful.
Parameters address: an IP addressport: A connection that you could use. Represented by a number.
ExampleOpenAddress(address, 231); // where address is the IP address of another computer. */



ListenOnPort(port)
Listens for connections on "port". Returns a socket object if successful.
Parameters port: a port that your computer may connect to. Must be a number.
Examplevar socket=ListenOnPort(3291);


Socket_object is any variable that returns a socket object.




Socket_object.isConnected()
Returns true if the socket is connected to a port
Parameters None
Examplevar theSocket=ListenOnPort(1102);if(theSocket.isConnected){ /* code to say hello to other person */}



Socket_object.getPendingReadSize()
Returns the size of the next byte_array to be read into the socket
Parameters None
Examplevar theSocket=ListenOnPort(1102);var info=theSocket.getPendingReadSize();



Socket_object.write(ByteArray)
Writes a ByteArray object into the socket
Parameters ByteArray: a byte_array object.
Examplevar theArray=CreateByteArrayFromString("Hello There!");var theSocket=ListenOnPort(1102);theSocket.write(theArray);



Socket_object.read(int_size)
Reads from the socket and returns a ByteArray object
Parametersint_size: the number of bytes to be read.
Examplevar theSocket=OpenPort(1234);var array=CreateByteArrayFromString("Hello")theSocket.write(array)theSocket.read(9); /* this reads 9 bytes from theSocket */







Color Object




CreateColor(R, G, B[, A])
Creates a new color object and returns it.
Parameters R: red value. Must be a number ranging from 0-255.
G: green value. Must be a number from 0-255. B: blue value. Must be a number from 0-255. A: alpha. If specified, must be from 0-255. If left blank, it is the default 255.
Examplevar Green=CreateColor(0, 255, 0); /* the alpha has been left blank, so Sphere reads it as though the alpha were written as 255 */
Notes: An alpha of 255 is opaque, and an alpha of 0 is transparent. With red, green and blue, the higher the numbers the brighter it is, and lower numbers make darker colors.



BlendColors(color1, color2)
Blends two colors and returns a new color object.
Parameters color1: an existing color object. color2: an existing color object.
Examplevar Purple=BlendColors(Blue, Red);



BlendColorsWeighted(color1, color2, c1_weight, c2_wieght)
Blends two colors based on the "weight" of each.
Parameters color1: an existing color object. color2: an existing color object. c1_weight: the weight of color1. Must be a number. c2_weight: the weight of color2. Must be a number.
Examplevar ReddishPurple=BlendColorsWeighted(blue, red, 1, 4 ); /* this blends the color objects blue and red, with 4 parts red to 1 part blue. */
Notes: the weighted part is like a ratio, where the denominator is c1_wieght + c2_weight. In the example blue is 1/5 of the new color, and red is 4/5.


Color_object is any variable that returns a color object.



Color_object.red
Returns the red component of the color object.
Examplevar Red=CreateColor(255, 0, 0); var myColor=Createcolor(255, 255, 0); Red.red; //returns 255
myColor.red; // returns 255.


Color_object.green
Returns the green component of the color object.
Examplevar Green=CreateColor(0, 200, 0); Green.green; //returns 200
var bgColor=CreateColor(50, 180, 95); bgColor.green; // returns 180



Color_object.blue
Returns the blue component of the color object.
Examplevar thatColor=CreateColor(45, 45, 0); thatColor.blue; //returns 0
var fontColor=CreateColor(255, 230, 255); fontColor.blue; // returns 255



Color_object.alpha
Returns the alpha of the color object.
Examplevar someColor=CreateColor(45, 45, 0, 150); someColor.alpha; //returns 150
var fontColor=CreateColor(255, 230, 120); fontColor.alpha // returns 255, the default value of alpha








Maps





Running Maps




MapEngine(map, fps)
Opens the specified map and runs the map engine at the specified frames per second.
Parameters map: the name of a map file.fps: frames per second.
ExampleMapEngine("World.rmp", 60);



ChangeMap(map)
Exits the current map and loads the specified map.
Parameters map: a map file.
ExampleChangeMap("Portside.rmp", 60);



GetCurrentMap()
Returns the file name of the current map.
Parameters None
Examplevar mapName=GetCurrentMap();
Notes: this function does not work in version .97, and may be omitted from future versions of Sphere.



ExitMapEngine()
Closes the map engine, but does not necessarily exit the Sphere engine.
Parameters None
ExampleExitMapEngine();


UpdateMapEngine()
Updates the map engine. Anything that is processed by the map engine is updated when this function is called
Parameters None
ExampleUpdateMapEngine();
Notes: The map engine handles the processing of color masks for spritesets and for the screen, spritesets, frames of animated tiles and changes to tiles and the camera. It automatically updates them with every frame that the map engine processes. If you do not want to wait for the next automatic update, or you want everything updated at once, use UpdateMapEngine().




Rendering Maps




GetNumLayers()
Returns the number of layers on the map.
Parameters None
Examplevar worldLayers=GetNumLayers();



GetLayerWidth(layer)
Returns the width of the layer, in tiles.
Parameters layer: the index value of the layer
Examplevar layerWidth=GetLayerWidth(2);



GetLayerHeight(layer)
Returns the height of the layer, in tiles.
Parameters layer: the index value of the layer
Examplevar height=GetLayerHeight(0);



GetNumTiles()
Returns the number of tiles in the maps rts file.
Parameters None
Examplevar tiles=GetNumTiles();



SetTile(x, y, layer, tile)
Changes the tile on the current map.
Parameters x, y: the x and y coordinates of the tile, where each tile is a square on the Cartesian plane. layer: the index value of the layer. tile:the index of the tile that replaces the old one.
ExampleSetTile(10, 23, 0, 6); /* the tile that is at (10, 23) on layer 0 is replaced with the seventh tile of the maps rts file. */



GetTile(x, y, layer)
Returns the index value of the tile.
Parameters x, y: the x and y coordinates of the tile. layer: the index of the layer.
Examplevar theTile=GetTile(28, 0, 2) /* this returns the index value of the tile that is located at (28, 0) on the third layer of the current map.


RenderMap()
Renders the map to the back buffer. This 'takes a picture' of the map as it is when this function is called, and puts that picture on the back-buffer.
Parameters None
Examplevar font=LoadFont("aerial.rfn");
for(var a=0; a< 10; a++)
{
font.drawText(15, 15, a);
FlipScreen();
RenderMap();
Delay(1500);
} /* this displays the numbers 0-9 on the screen. Without RenderMap(), the numbers 1-9 would be drawn on a blank screen, rather than on an image of the map */



SetColorMask(color, num_frames)
Places a color mask over the map.
Parameters color: a color objectnum_frames: the number of frames that are processed before the mask is visible.
Examplevar gray=CreateColor(100, 100, 100, 90);SetColorMask(gray, 300); /* for the next 300 frames, there will be a gray, partially translucent mask over the map.


SetDelayScript(num_frames, script)
The command or commands of script are executed after the designated number of frames has been processed.
Parameters script: scripting command(s)
ExampleSetDelayScript(600, MovieSequence()); /* after 600 frames have been processed, the engine runs the user-defined function called "MovieSequence() */







Input




BindKey(key, on_key_down, on_key_up)
Runs the "on_key_down" script when the designated key is pressed and the "on_key_up" script when the key is released.
Parameters key: the name of the key. Refer to keys.txt. on_key_down: the script that is run when the key is pressed.on_key_up: the script hat is run when the key is released.
ExampleBindKey(KEY_A, "power++", ""); /* power is simply a user-defined variable. Each time the key "A" is pressed, power increases by 1. Nothing happens when the key is released. */BindKey(KEY_S, "Scroll()", "ShowText(25, 25, 'What is so special about this spot?')"); /* This causes the camera to scroll across the screen while the player is pressing the key. When the key is released, the text is displayed on the screen. Scroll() and ShowText() are user-defined functions. */



UnbindKey(key)
Unbinds a key that was bound with BindKey().
Parameters key: a key from the keyboard. If the key is not bound, it is not affected.
ExampleUnbindKey(KEY_CTRL); /* Now the control key will not run any scripts when it is pressed. */



AttachInput(name)
Makes 'person' the input person. This fellow will respond to the following input; up arrow: move up. down arrow: move down. right arrow: move right. left arrow: move left. He or she also activates triggers and ON_ACTIVATE_TOUCH scripts.
Parameters person: the name of a person object.
ExampleAttachInput("Bobby"); /* the arrow keys now control the movements of the person named Bobby */
Notes: Only one person can have input attached. If you attach the input to one person, and later to another, the input will be automatically removed from the first person.



DetachInput()
Releases the input from the person that it is attached to. If no one is attached, it does nothing.
Parameters None
ExampleDetachInput(): /* Now the input is not attached to any person */



IsInputAttached()
Returns true if any person is attached to the input. Otherwise returns false.
Parameters None
Exampleif(IsInputAttached){var input="on";}else{var input="off";} /* sets the variable called input to on or off depending on the value returned by IsInputAttached() */


GetInputPerson()
Returns the name of the person to whom the input is attached
Parameters None
Examplevar inputPerson=GetInputPerson();


SetUpdateScript(script)
script is called each time the map engine processes a frame.
Parameters script: the command or commands to execute
ExampleSetUpdateScript("var a++"); /* the variable is increased by one each time a frame is processed. */
Notes: if you have more than one UpdateScript() per map, only one of them will be run.


SetRenderScript(script)
Script is called each time the screen is rendered.
Parameters script: the command(s) to be executed
ExampleSetRenderScript("Sequence()"); /* where Sequence() is a function that makes the townspeople on the map move about in a movie sequence. */
Notes: if you have more than one SetRenderScript() per map, only one of them will be run.


SetLayerRenderer(layer, script)
Runs the script each time the layer is rendered.
Parameters layer: the index value of the layerscript: the script to be executed.
ExampleSetLayerRenderer(2, "DisplayImage(15, 15, 'epic.png', 3000)"); /* after the third layer