DaVince scripting tutorial
From Spheriki
Notes
Tutorial being overhauled and continued as of July 3 2008.
The original Dutch version of this tutorial can be found here (outdated).
I made a scripting tutorial about Sphere in Dutch because some Dutch people didn't understand the English documentation very well. I received very positive comments about the tutorial, so I decided to translate it into English, and that's what you're seeing before you. It's pretty old by now and has been reworked/improved several times over the years so it can help you as well as is in my ability. :)
My tutorial teaches some of the basic JavaScript syntax (syntax = rules, "code grammar") and how you use the language in combination with Sphere. I have tried to make it so that beginners can easily step into the world of Sphere. There are also some tests available which you can use to practice the things you have learnt so far.
TO BEGIN: A very basic resource pack, for all beginners who just want to start scripting without having to look around for resources or make them. Resources include a map, sprite, font and sounds. Oh yeah, and sorry about the Dutch filenames in that archive. :)
Contents |
DaVince's Sphere scripting tutorial
Translated from the Dutch version
©Vincent Beers 2005 - 2008
About this tutorial
Ah, Sphere... An awesome and flexible RPG-creation program... Including a fully-fledged editor to make your own RPGs (or other kinds of games), and a pretty extensive scripting language! But how do you start learning and using this scripting language, and how does it work inside Sphere? This tutorial will help you on your way.
Some of the tutorial's chapters are based on other, older and sometimes well-known tutorials, but I tried to make sure that they are easier to understand for newbies. Also, examples were added to these chapters. Next to those chapters there are chapters (and tests) that I completely wrote myself.
Well, enjoy my tutorial and have a good Sphere experience! :)
Questions? Suggestions? Other feedback? My email address is VincentBeers@gmail[Dot]com. You can also of course contact me on the Spherical forums, or send me a message on the talk page of the Spheriki (this Wiki).
--DaVince
About Sphere
Sphere is a program designed to create RPGs in the style of early Final Fantasy games fairly easily. However, you'll be able to create almost any other kind of 2D game you can imagine if you're skilled enough. It uses a scripting language (JavaScript, which is NOT JAVA!) that "makes everything happen". This, of course, means that you will have to learn this scripting language in order to be able to create a game in Sphere. Scripting isn't always easy, especially for programming/scripting newbies, so I'll be trying to keep things simple.
Where can I find the latest version of Sphere?
Sphere and its editor can be downloaded from Sphere:Latest. The latest versions can always be found there.
The versions of Sphere used when this tutorial was first written are versions 1.10989, 1.11, and 1.13 (1.5 during the rewrite of this tutorial). If some things don't work (correctly), download the latest version of Sphere and these problems should disappear. If you already have the latest version, there's just something wrong with your code.
DO NOT use Sphere 1.1 of lower! They're horribly outdated and you'll be missing a lot of new goodness! It's a common mistake that people start out with Sphere 1.0 or 1.1, so I'm really pressing this matter. Go get the latest version!
Get used to the editor first!
If you want to be able to follow this scripting tutorial well, you will have to get used to the editor's interface a bit first and learn how to use it. If not, AT LEAST get used to the file formats and structure that Sphere games use. Tutorials on how to use the editor's interface can be found in Sphere's default docs, and there might be some on this Wiki too.
Chapter 1 - About Sphere's JavaScript
Sphere uses SpiderMonkey, a special "library" that makes JavaScript available in applications like Sphere. Sphere itself then adds lots of functions to SpiderMonkey so you can actually use it to create a game.
JavaScript is a browser scripting language in origin, specially designed for the use in webpages, but as Sphere proves it can be used for other things perfectly fine too. JavaScript consists of three parts: the Core, the Client and the Server. Sphere only uses the Core, the other two are actually parts that belong to Web JS.
Configuration and information on scripts
Every Sphere game must have a script where it can start out "reading" (actually interpreting) what to do. The start script to use can be defined in the Game Setings window (open this window by double-clicking the blue sphere in a project). Unless you don't have a script yet, of course.
The script doesn't need to have a specific name like main.js - you can give it any valid name you can think of, valid meaning only using all possible characters you can use in a filename. However, it's recommended to keep the name simple and preferably without any special characters (even spaces), so you can quickly and easily "fetch" a script in your code. The start script will be the first script that's read by Sphere's game engine when you start the game. If you want to let Sphere open other scripts next to this one, you can use specific functions in the main script to include these scripts (RequireScript(), more about that later).
You do not need to have more than one script, you could just as well put all of the game's code in the one single start script. But using multiple script files makes everything more clear and easier to find and use. Think about it: seperate scripts for battles, menus, text boxes... It also allows you to use specific scripts in multiple games, if you make sure to make everything in that script work independently from other scripts... Very nice if you devised a very nice menu or item system you don't want to create from scratch in a different game.
Sphere immediately looks for the function game() inside your startup script when the game is launched. This is the only automatically started (rather, "called") function and gives you a point to start with. All other functions will have to be called by hand.
You will get to know more about scripts later; I'll talk about where you can use scripts first now.
Places that scripts are used
You can use scripts in different places in Sphere. These are the maps, persons and files.
Maps can contain two types of "entities": triggers and persons. Triggers are attached to a specific tile and have a script that is launched when the player-controlled person walks over it. Persons are entities on the map that have a name, spriteset and scripts to control the actions of these spritesets.
Persons can have up to 5 personal scripts, each being startedduring a different situation:
- On Create, to run code when the person is created.
- On Destroy, to run code when the person's being destroyed.
- On Activate (Touch), to run code when the person's being touched by the person being controlled by the player.
- On Activate (Talk), to run code when the player-controlled person faces the person and presses the TALK button (default = space).
- On Generate Commands, to run code that is run each moment the map engine exists (specifically, every frame per second).
Maps also have a few personal scripts, which can be found in the Map Properties (Map > Properties). They are useful to have the game control what happens if the player-controlled character is entering or leaving the map (even in a specific way).
Files are the most common place for script code and can be created in every text editor. Sphere JavaScript files (and JavaScript files in general) use the file extension .js. More experienced Sphere users usually avoid non-file scripts as much as they can, and let it all be taken over by JS files (this for the sake of flexibility and being able to find everything, especially errors, more easily)! The files are the most important part as these are the main method to give instructions to Sphere, including where and what to start. The scripts in persons, triggers and maps are more of an extra place for a few instructions when that specific map starts or when you talk to a specific person.
To make a new script file, you go to file>>new>>script (or click the empty page icon) and you'll get a notepad-like editor. This is Sphere's built-in script editor, probably the best one for Sphere scripts.
Now that you know what scripts are all about, we can start the real work!
Chapter 2 - The basics of scripting
Comments
A comment is the most simple thing to do in Sphere.
With comments, you can give an explanation of something with NORMAL text in whatever language you like. Sphere plain skips over this text. It doesn't read comments as real code, so you can put anything in it. A comment is mainly intended to help the reader of the code: you can put comments above your real code in which you explain what the following code will do, for example.
A single comment line can be made by putting // in front of the line, a whole block (multiple lines) can be made by putting /* in front and */ after it.
//This is a comment. /* And this is a comment. */ /* This is also a comment. But, it stays comment on the next line, too. And it will keep on doing that until the blocks gets closed with the asterisk and the slash. */ This line is NOT a comment, because it doesn't have // in front and isn't in a /* */ block! // Note: above line is a comment from ^^ this spot onward, though!
A comment can be done on the same line as a line of code, too. This is useful for explaining just this line:
Code(); //Comment!
If you're a beginner it's useful if you put comments before or after every line of code that you think you might forget what it does, so you can look back on it later to see what a certain piece of code did again...
Closing a line of code
This is the next simplest thing and VERY IMPORTANT. You can't just close down a line of code like that. In real life, you have to add a dot at the end of every sentence, and in Sphere it isn't any different. Well, it's slightly different, as you have to type a ; instead.
Code;
Watch this! If your script doesn't work correctly it could be because you forgot a ;. If you DON'T put the ; in there, Sphere will often try to 'glue' the code together, which, of course, causes errors.
CodeCode would be bad code, while Code; Code; seperates it so Sphere can understand it. It's like the dot after a sentence.
Chapter 3 - Basic scripting tutorial
Part 3.1: functions
This is, as the name implies, a basic scripting tutorial intended for the people who just started off using Sphere or scripts. This tutorial will make sure that you can make your own game in Sphere. A simple, but working game.
The structure of a function
As you should know by now, every Sphere game must have a main script, containing the main function called game. If you don't know or remember, please read chapter 1 again.
- A function always starts with the word function so both Sphere and the reader of the script knows we're going to make a function. - After the word function comes the name of the function. When giving it a name, keep in mind only letters, numbers and the underscore _ are allowed. It is also not possible to start the name with a number. - After the name come two parenthesis: an opening parenthesis and a closing parenthesis (). - Then, on a new line, you put the brace { which indicates that the code coming after the brace will belong to your function. - After the bracket, on another new line, you put the code that should be run when the function is run. - When you're done with your code, you close down the functions with the closing brace }.
Example:
function game()
{
//code comes here.
}
So that's what a function looks like. game() is, as mentioned before, the starting function for Sphere.
Still, if you try to run this code, nothing will happen. That's because we didn't put any code in it yet. Let's add one very simple command:
function game()
{
//This function will open the map Map.rmp.
MapEngine("map.rmp", 60);
}
This pice of code WILL do something, namely it will open the map engine with the file map.rmp, with a framerate of 60 frames per second. Still, if you want this code to not give an error but just run, remember that the file map.rmp must actually exist!
The most used Sphere commands
Okay, now we will do a bit more difficult stuff. We're gonna insert and explain a few of the most used commands in Sphere. Every line of code will be explained.
function game()
{
CreatePerson ("my_name", "character.rss", false);
//Creates a new person. give him the name my_name and use the spriteset file character.rss for his looks.
AttachCamera ("my_name");
//Makes sure that the camera is always pointed at the person called my_name.
AttachInput ("my_name");
//Pass the input to the person my_name. This means that when you press an arrow key, he'll move, and stuff like that.
MapEngine("map.rmp", 60);
//We'll open map.rmp with a framerate of 60 frames per second (fps).
}
A list of often used commands
There are a lot more common Sphere commands, another bunch explained below. You can look up all the other Sphere commands in the doc_functions.txt file, delivered with Sphere in the docs directory.
NOTICE BEFORE YOU USE THESE COMMANDS: Some commands have a dot . inside them. You will have to replace the word that's before the dot with the command that loads the file that has to be used in combination with the command after the dot.
FlipScreen() - Puts everything you have blitted/drawn on the screen. When using a draw or blit function or anything like that, it doesn't get drawn on the screen but on the backbuffer. Things drawn on the backbuffer will show up on the screen when using FlipScreen(). After that the backbuffer is made empty again. ALWAYS PUT THIS AFTER ALL DRAWN STUFF!
LoadFont("font_file") - Loads a font file. Only the Sphere font format .rfn is supported, so make a Sphere font first.
font.drawText(x, y, text) - Draw the text on the screen with the assigned font and on the assigned x/y coordinates (in pixels). Don't forget to replace 'font' with the font file you wish to use, like this:
LoadFont("font_file.rfn").drawText(10, 10, "Good day, world!");
font.drawTextBox(x, y, width, height, offset, text) - Draw the text on the screen with the assigned font and on the assigned x/y coordinates. This is a bit different from font.drawText: it has borders you can assign with the width and height. When the maximum width is reached, the text continues blitting on the next line until the maximum height is reached too (in pixels). I'm not too sure what the offset is, I think the offset of pixels before drawing the text. I always set it to 0.
LoadWindowStyle("windowstyle_file") - Loads a windowstyle file in memory. Make sure you have a windowstyle file first, of course.
WindowStyle.drawWindow(x, y, width, height) - Draw the windowstyle on coordinates x,y with the assigned width and height.
LoadImage("image_file") - Load an image file (bmp, png, gif, jpg, pcx, tga are valid formats, png is recommended for its size/quality ratio).
image.blit(x, y) - Draws the image on the assignes x,y coordinates. Blit is an old English word for draw.
image.zoomBlit(x, y, zoom) - Draws the image on the assigned x,y coordinates, but resized according to the zoom parameter. Zooming is 1:1, so when inserting a value like 1.5 the image will be drawn 1.5 its original size.
LoadSound("sound_file") - Load a sound file into memory. wav, mp3, MIDI, modules, ogg are valid sound formats, for music I would recommend modules/mp3.
sound.play(repeat true/false) - Play the loaded sound. The parameter is tru or false, depending on if you want the sound to repeat. true = repeat, false = do not repeat.
sound.stop() - Stop the sound. This function has no parameters.
RenderMap() - If you have the map engine open and you want to draw something on screen, the map will not be shown when you FlipScreen() it. This is done for flexibility purposes. With RenderMap() you tell Sphere to put an image of the map engine in the backbuffer, so all the stuff you draw after it will be displayed on an image of the map. Put this before all other draw stuff, because it will be drawn in front of the rest if you don't.
GetKey() - Pauses the script until you press on a key (ANY key). Useful for intros. can also be used in combination with an if condition. You can find more information about if in chapter 4.
ChangeMap("map_file") - If the map engine is open, you can switch maps with this function.
Exit() - Exits the game.
Chapter 3.2: Variables & more functions
Let's continue our second part of chapter 3.
Variables
If you inserted more texts or objects of the same type in your code, you'll find that it is pretty annoying to type LoadFont("file") etcetera over and over again. Luckily there is something like a variable, in which you can store these things (and values, text and a lot more)! Because of this you will only need to type the name of the variable to call what's inside it, which could be our LoadFont("file") or whatever!
var IgaveItAname;
With this you make an empty variable, containing NO value yet. We gave it the name "IgaveItAname", which means we can type IgaveItAname every time we need its contents. You can't do anything with this variable yet though, because it contains nothing. You only DECLARED this variable, which means that you made a piece of memory available for our variable. Also remember that the word 'var' only has to be put before the variable when it's the first time you declare it.
Now let's assign a value to a variable.
var Music;
Music = LoadSound("SomeFile.mp3");
With this you make a variable called Music, and then you put a value in it. The value we just put in is LoadSound("SomeFile.mp3"). Now you can use the variable Music as a 'shortcut' to what's inside it, which is LoadSound("SomeFile.mp3") in this case.
Music.play(true);
The Music part starts what is inside of the Music variable. So what you see is music.play(true), but Sphere reads it as LoadSound("SomeFile.mp3").play(true) because the word Music is a variable containing LoadSound("SomeFile.mp3")! This is not only easier to type, but it also saves a lot of memory because the variable Music is loaded into memory at start, while using LoadSound("SomeFile.mp3") all the time will have to load the file again every time.
There is another, faster way to create a variable and assign a value to it at once. You can do it like this:
var Music = LoadSound("SomeFile.mp3");
With this you declare the variable and immediately give it a value. Don't forget you don't need the var word anymore after you declare a variable for the first time.
var Haha = LoadFont("haha.rfn");
//Haha exists now in memory, so following commands changing the variable do not need var in front of them:
Haha = LoadFont("eh.rfn");
Haha = LoadSound("haha.mp3");
As you can see you can also change the value in the variable. That IS why it's called a variable, because its contents can be changed.
Variables: more than a storage place for functions
You can store more than only functions in a variable! You can also use them to save numbers or text so you can use these later. Example:
var Story = 1; var CurrentText = "What a nice string of text I am!";
This is useful for storylines, for example. If an event has happened: change the value of the Story variable so Sphere knows that the event was played. The if here is a condition, of which you will learn more in the next chapter.
Adding, subtracting and the like
How to add and subtract values from variables containing numbers? It isn't as hard as you'd expect...
- variable++ adds 1 to your variable.
- variable-- subtracts 1 from your variable.
- variable += value adds the value to your variable.
- variable -= value subtracts the value from your variable.
- variable = value changes your variable to the value.
Functions
As you probably know by now, Sphere reads the commands you insert. These commands are called functions... game(), for example, is a function too, so it could be started the same way as for example a FlipScreen(): by typing its name and the braces behind it, and the ; of course.
game();
So with this you'd start up whatever is in the function game(). This particular function doesn't need to be started btw, because game() is automatically started at the start of the game. But it's a good example on how to create your own functions.
Making your own function is pretty simple. Just look on how you made the function game()... You make your own function about the same way.
function game()
{
//Code comes here.
}
You can put code in functions, the code will be executed as soon as the function was started (called) somewhere. As an example we'll try to make a function that executes all commands necessary to make a box containing text.
//First we'll declare a few variables outside of the functions,
//so that they are GLOBAL which means they can be used in any function!
var window = GetSystemWindowStyle();
//Makes the var window and puts the standard Sphere window style in it.
var font = GetSystemFont();
//Opens the (ugly lol) standard Sphere system font and puts it in the variable font.
//We make our function named 'TextBox'.
function TextBox()
{
//We open it for code.
window.drawWindow(5,5,310,100);
font.drawText(5,5,"Some text.");
FlipScreen();
GetKey();
}
Now if you insert TextBox(); in your game function, everything in the TextBox() function will be run!
Parameters
There still is a problem with our textbox: if you add TextBox(); to your code, the result will always be the same: every time you call for TextBox() you will see the text "Some text." appear on screen. But what if we want "Hello", "Line 2" or "Status:" as a text? You can't make four different functions just for that, that would be a waste and not easy at all! So we need to change something!
Just examine the following code: function TextBox(text) {
window.drawWindow(5,5,310,100); font.drawText(5,5,text); FlipScreen(); GetKey();
}
Look at the spot where the function is created (function TextBox). Inbetween braces, there is something new now. This is NOT a function, NOT a variable, but a parameter. Parameters can make sure that newly created functions can have extra input delivered with them, resulting in the output varying of what you inserted externally.
Now we can put all our different text in the function and get different results:
TextBox("Hello");
TextBox("Line 2");
TextBox("Status:");
As you can see we put our text in-between double apostophes ", in-between the braces () of the function call. The " are there to show Sphere that it's a string of text.
The stuff that we insert in-between the braces is stored in our created parameter that we gave the name 'text'. Everywhere within the function is looked for this same word, text in this case (though a parameter cal be named anything), and all found text words are replaced by what was inserted in the call of the function. Pretty difficult to explain, but this is what Sphere does:
1. Save the text that was found at the function call and put it in our parameter 'text'. 2. Walk through the function and look for other places pointing towards the parameter. 3. Replace it with what we got through the function call.
The result is different every time because it's dependant on what you inserted! Just try it and you'll see what I mean!
More than one parameter
If you want to insert more than one parameter, you just have to seperate the parameter names with a comma:
function TextBox(x, y, text)
{
window.drawWindow(x,y,310,100);
font.drawText(x,y,tekst);
FlipScreen();
GetKey();
}
//Call the function:
TextBox(10,10,"hahaha!");
//This will make the text "haha" appear on x position 10 and y position 10.
Chapter 4 - Conditions and Loops
If, while and for
This chapter will become a bit more difficult and confusing because we'll have to break some of the Javascript syntax rules that you learned before. For instance, we won't add a semicolon after every line anymore, and sometimes we add multiple semicolons in one line! Luckily this only happens in a few special occasions, so once you know this exception from the rule it isn't too hard to stick with it.
The condition : if
I bet you have thought at least once about letting something happen in the game ONLY when something else had happened first. This is called a condition, as you set a condition of when you will let it happen.
Conditions can check if something is true or not. For example, it can check if the variable 'blah' contains value '4', and if it's true it will return 'true'. This can be done with the command if.
var story = 0;
1. if (story == 0) //Note that there's no semicolon ; at the end!
2. {
3. TextBox("Hi. Could you do something for me? Thanks!");
4. story = 1;
5. }
(The TextBox() function doesn't really exist by default in Sphere, you'll have to make a TextBox() function if you want the above to really run. It's just an example.)
Now what you did with this code is the following:
1. You check whether the story variable is equal to 0.
This line of code has TWO equals signs (=) in it, because a double equals sign tells Javascript/Sphere that this is a comparison: we're comparing the story variable and the value 0 with each other. == indicates that there will be checked if these are EQUAL to each other.
A single = does not run a comparison, but assigns a value to the variable. A good example of this is when you were making variables: you assigned a value to a variable by putting an = in-between. We shouldn't use this in a comparison, of course, because we're comparing two values, and not assigning one value to a variable!
2. An if condition uses braces {} too, to open it for code. So we add a { after the if. The following code will run when the condition returned true (so when story == 0). Else, it will simply skip it.
3. The code to run comes here. TextBox() from the previous example was used in this example.
4. Now the code's done, and we'll change the story variable to 1. This makes sure that the condition can not be run again (unless you set story to 0 again somewhere).
5. We're closing the condition now with a }.
As you can see, the structure of a condition is almost the same as creating a function. The big difference lies in when it's run: a function will run when it's called, but a condition will run when it's encountered and returns true.
There's more than only comparing if values are equal
The == operator (it's called that) is just one of the comparisons you can use in conditions. It compares whether one number is equal to the other. But more comparisons exist, and we'll put them in a row!
- a > b Compares whether value a is higher than value b.
- a < b Compares whether value a is lower than value b.
- a >= b Compares whether value a is higher or equal to value b.
- a <= b Compares whether value a is lower or equal to value b.
- a != b Compares whether value a is anything but value b (and thus, the other way around too, duh).
You fill all of these in in the same way:
if (a > b) if (a != b) if (a <= b) //etc.
The loop: while and for
Loops in Sphere! These are very useful for certain things. One advantage is that you don't have to make long rows of the same code over and over again. Example:
var value = 0; value++; TextBox(value); value++; TextBox(value); value++; TextBox(value); value++; TextBox(value); //etcetera etcetera....
This is very annoying and long if you want to add 1 to value and show a textbox with the value 100 times in a row. That's where you can use a loop. The loop makes you able to just enter the two lines (value++ and TextBox(value)) once, and run it a hundred times!
There are more kinds of loops. The while loop is the easiest one to start with, because it looks about the same as an if condition does.
var value = 0;
while (value < 100)
{
value++;
TextBox(value);
}
//Code that starts when the loop is done comes here.
This is what it means:
The loop basically is a condition: it checks whether the given condition returns true. The only difference is that it loops. In this case, the loop is: While the value of var value is lower than 100: add 1 to var value and run the function TextBox with the value as a parameter.
So when the loop starts, var value is 0, and the code in the loop is run until var value reaches a value of 100 (or higher). Then the loop is done, so Sphere will continue with whatever comes after this loop (and its code).
If we had NOT used a loop for this piece of code, we would have wasted around 200 lines of code: 100 for the value++ and 100 for the TextBox(value)! But with the power of loops we minimized this to 5 lines, where the two crucial lines loop themselves 100 times. So loops are really useful, as you can see!
Then there is a more difficult kind of loop. You can wait with using this one until you feel ready for it, or just try it from the start anyway. The more difficult kind of loop is the for loop.
A for loop looks a bit different. It's because you do multiple things at once, still in the loop. A for loop usually looks something like this:
for (var value = 0; value < 100; value++)
There are three things here, and ;'s inbetween them! Weird, huh? But, it isn't as shocking or difficult as you might think...
for (make a variable here; the condition comes here; the stuff that happens with the variable comes here)
In the first part of a for loop, you place your variable that will control the loop. This can be a new variable, or one that was created globally somewhere else. You also give it a starting value (if you don't, its value will be "undefined", which can be unhandy).
In the second part you place the condition, just like you would do in an if or a while loop. In the third part, you place the things that affect the variable you made/used in part 1 of the loop.
This is the best I can explain it. Best way to understand it after this is trying it out for yourself. ;)
The rest of a for loop looks just like an if or while:
for (var blah = 0; blah < 25; blah++)
{
TextBox("This loop started " + blah + " times so far...");
}
There also is a different kind of loop, but it's basically the same as a while loop and not many people use it. If you still want to know more about it, check | this page.
Okay, that's it for the loops/conditions chapter.
Chapter 5 - More on variables
You've got a few types of variables available in Sphere, each one of them is intended for different things. Or rather: you can put different types of content in variables. In this chapter you'll learn about most of these contents.
1. Numbers
You already knew this one. It is an often used type of value. You can put numbers in variables so you can refer to them, change them, or do maths with them.
var blah = 4;
2. Text
You also know this one already. You can put sentences, words, letters and characters in a variable. This is called a string. Strings are useful for manipulating the text or call it back later. Strings have double quotes put around them, to define we have a string here and not a number or something else. It's also used for file/directory names.
var blah = "Hello!";
Strings can also contain some special characters you can use for formatting the text when it's put on screen:
- \n makes a new line.
- \t adds a tab (or rather, 5 spaces).
- \\ is for adding a \ to the text. :P
- \" is used so you can safely add a double quote to your string without indicating to the engine that you finish the string.
3. Sphere functions
Sphere has a few built-in functions that can return values, for example where a person on the map is, getting the screen width, and lots of other things. When you use such a function as a value in a variable, Sphere will put the resulting value in the variable.
var blah = GetScreenWidth();
4. Objects
You can put objects in variables. Objects kind of are Sphere functions too, but they can do more than return the resulting value of the function. Instead, you can call the full object and get a lot of more values on this object. You can also run or get functions that are inside this object!
var blah = LoadFont("fontfile.rfn");
var Other = blah.getFontHeight();
blah.drawText(10, 10, "Hahaha!");
5. New Functions
You can also put NEW functions in variables, like this:
var blah = function(parameters)
{
//Code comes here.
}
This might seem useless, but can be pretty useful, especially if you're planning to make your own object with sub-functions. More about this in the next chapter!
6. Arrays
Arrays are somewhat different than the other variables mentioned so far. The big difference lies in that you can put multiple values in it, and they can be of different types even!
To make an array, you can type one of the following:
var blah = new Array();
- OR -
var blah = [];
I don't REALLY know the difference between the two, but I do know that you make an object of the type Array with the first, and you make a native array (no object needed) with the second. Both can do the same things, though. I recommend using [] because it's shorter to type and it's native, which probably means it takes up less memory (which means better game performance). ;)
Okay, so now you have an Array. You can store your values in it in two different ways.
- The first way to do it is by putting values in it when you declare the array.
var blah = new Array(1, 6, 4, "Theo", "etcetera");
- OR -
var blah = [1, 6, 4, "Theo", "etcetera"];
This is what you do: declare the array, and put some values in it. An array consists of spots where you can store your value, and each spot is seperated by a comma. All spots also have a number, starting from 0. So you put the value 1 on spot 0, 6 on spot 1, 4 on spot 2, "Theo" on spot 3 and "etcetera" on spot 4. These spot numbers will be useful for the second way to change/add values in arrays.
- The second way to do it is by already having declared the array, and then doing something like this:
array_variable[spot_number] = a_new_value;
For example, I'll now change some of the values in the array blah we made before:
blah[0] = "new value!"; //This was 1 before blah[1] = 7; //And this was 6 blah[4] = "Pete"; //And this was "etcetera"
This way you can change the values (or make new values) on different spots of your array. The old values are overwritten, just like in a normal variable.
Since we didn't touch spots 2 and 3, they'll keep their original values, which were 4 and "Theo". That means that our array now consists of the following values:
["new value!", 7, 4, "Theo", "Pete"]
Now how to get these values to use them? Well, that's pretty simple, actually. Just refer to your array and add the spot it should read to it, like this:
var nn = blah[3]; //Putting the value of spot 3 in blah into a new variable TextBox(blah[4]); //Passing the value of spot 4 in blah onto the function TextBox().
So what are arrays useful for? Well, for example, they can be useful for an inventory:
var inventory = ["Potion", "Antidote", "Empty bottle"];
Or maybe a list of all characters in your game (or just the party):
var people = ["DaVince", "Petey Pirate", "Aegis", "Flikky", "Nidoran"];
You'll find that arrays can have lots of uses. I use them a lot, and some native Sphere functions also use them, so you'd better get to know them! ;)
7. Other functions
Huh? Functions, again? Yes, but this time, we're not gonna talk about MAKING functions, but CALLING functions in a variable. Now, why would you want to do that? Well...
There are lots of functions in Sphere that return a value to whatever called it. What does this mean? It means that those functions will give you a value back to you once it's done running. This is useful because not only can you check if the function is done, but you can also make functions that give you information!
So, functions can return values to you. Here are some examples of Sphere functions that return simple values (numbers, strings, arrays):
- GetPersonX(person_name) - Returns the x position of person_name on the map.
- GetPersonY(person_name) - Same, but y position.
- GetScreenWidth() - Returns the width of the screen.
- GetScreenHeight() - Returns the screen height.
- GetPersonList() - returns an array filled with strings of the person names on this map.
- GetVersionString() - Returns the current Sphere version string.
Some functions also return more complicated values called objects. These can contain subfunctions and subvalues. Anyway, more about making/using objects in the next chapter.
Some examples of Sphere functions that return a value to you:
- LoadFont(file) - Makes and prepares a font object and returns it to whatever called it.
- LoadImage(file) - Makes and prepares an image object and returns it to whatever called it.
- LoadSound(file) - Makes and prepares a sound object and returns it to whatever called it.
- LoadAnimation(file) - Makes and prepares an animation object and returns it to whatever called it.
- LoadSpriteset(file) - Makes and prepares a spriteset object and returns it to whatever called it.
- LoadSurface(file) - Makes and prepares a surface object and returns it to whatever called it.
- LoadWindowStyle(file) - Makes and prepares a windowstyle object and returns it to whatever called it.
- OpenFile(file) - Makes and prepares a file object and returns it to whatever called it.
Now, all of the above functions actually make different kinds of objects, which have their own specialized functions for that type of file. For example, a Sound object has .play() and .stop() functions in it, and the Image object has a .blit() function, etcetera. You can make objects too, see next chapter.
You can put above functions into a variable. That variable will then contain an object that's ready to be used. Example:
var some_font = LoadFont("font.rfn");
some_font.drawText(0, 0, "text");
You've seen this before, and now you know how it works. ;)
Some more functions that return objects:
- CreateColor(red, green, blue, alpha) - Makes a color object with the values you gave it.
- GrabImage(x, y, width, height) - Returns an image object that contains the contents of whatever is on screen in the zone you specified.
- GrabSurface(x, y, width, height) - Same as GrabImage(), but it returns a surface object, which has different kinds of functions.
There are literally TONS of more Sphere functions that return all kinds of values. I'm not going to explain them all here, since most are documented both in the Wiki and in doc_functions.txt (in the Sphere/docs folder). Most of these functions start with Get...(), so they're usually called getters.
Alright, you should now know enough about variables and functions to make quite a decent game! In fact, you're ready to fully make your game already, but if you wanna do it good and efficiently, you'd better learn more about objects too!
Chapter 6 - Objects
I swear I'm gonna type this out some day. For now, check out the Simple OOP in JavaScript tutorial.

