DaVince scripting tutorial/More on variables
From Spheriki
Contents |
More on variables
There's a few types of values available in Sphere, each one of them is intended for different things. This means that you can put different types of content in variables. In this chapter you'll learn about most of these types of values.
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 know this one already, too, if you have been paying close attention to the last chapter. You can use regular sentences, words, letters and characters with this type of content. You call this a string. Strings are used to store and use text in your program. Strings are recognizable by the fact that they have double quotes put around them (like "this"). This is done to clearly define to the system that it is a text string, not a number or anything else. You can also use single quotes if it's more convenient at the time, but take care with single quotes if you have "regular" text: words like it's use a single quote too, so they would end the string. Strings are also typically useful to define file and directory names.
var hi = "Hello!"; var project_file = "game.sgm";
There is a way to "connect" seperate strings together, in fact, it doesn't even have to be a string to be able to connect it to a string. Connecting (or combining) two strings (or compatible types) is what you would call concatenating. There is a very simple way to concatenate: use the plus sign as if you were "adding" two values.
Run the following code in Sphere:
var string = "I am a string" + " with a second string concatenated"; string = string + " and a third string concatenated"; string += " and even a fourth one!" + " And a fifth one on the next line, because the plus character allows this."; Abort(string);
Sphere will show something like this:
I am a string with a second string concatenated and a third string concatenated and even a fourth one! And a fifth one on the next line, because the plus character allows this.
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.
- If you used a single quote ' to formulate your string in stead of a double quote, you can use a regular " inside this single-quote string, but you will then have to define "textual" single quotes like this: \'
Try running the following code to see how you can use these:
Abort("Hi.\nI'm on a new line.\nMe too.\n\tI'm on a new line with a tab in front.\nC:\\path\\to\\something.txt\nAnd \"I\" am in \"quotes\".");
The result will be something like this:
Hi. I'm on a new line. Me too. I'm on a new line with a tab in front. C:\path\to\something.txt And "I" am in "quotes".
3. Sphere functions
Sphere has a few built-in functions that can return values, meaning they give you values back when calling them. For example, GetPersonX(name) gives you a numerical value of the X position of a person on the map, GetScreenWidth() gives you the screen width, stuff like that. When you use such a function as a value in a variable, Sphere will put the resulting returned value in the variable.
var blah = GetScreenWidth();
In this case, you're not really putting the function in a variable. You're putting whatever value it gives back to you in it instead. For example, GetScreenWidth() could return the number 320 to you, so var blah would then contain the number 320 as a value.
You can actually store the actual function inside a variable, if you wish. This will create what you would call a reference to this function: you're basically creating a new identifying name to call the function. To re-reference a function, just remove the parentheses () at the end:
var GetSW = GetScreenWidth; var blah = GetSW(); //GetSW() actually calls the same code as GetScreenWidth() would now.
There are a lot of functions in Sphere that return a value to whatever called it. Below are a few that you might want to study and practice using.
- GetPersonX(person_name) - Returns the x position (as a number) of person_name on the map.
- GetPersonY(person_name) - Same, but returns the y position.
- GetScreenWidth() - Returns the width of the game screen (as a number).
- 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 (as a string).
4. Sphere's special internal objects
You can put objects in variables. Objects are a kind of function too, but they can do much more internally, like store and retreive sub-values and even sub-functions inside. They also can have "changing" states: two objects can be the same on the outside, but store very different things. For example, you can have two instances of an Image object, one containing a small icon and the other a big cloud graphic. Objects are complex, so I'll leave the explanation at that for now and go more in-depth later in the tutorial.
Anyway! Sphere has a bunch of internal objects that can load images, music, basically all basic file resources. These objects can be made (instantiated) and stored inside variables by calling their appropiate LoadWhatever() functions, like LoadImage(file) or LoadFont(file). These then offer some internal "sub"-functions (or subvalues) to get or change further information, like image.width and image.height, or Font.getHeight().
var blah = LoadFont("fontfile.rfn"); var fontheight = blah.getFontHeight(); blah.drawText(10, fontheight, "Hahaha!"); //y position of this text depends on the height of the largest character in the font you loaded.
blah contains an instance of Sphere's internal Font object, which has methods (subfunctions, indicated with a separating dot) to further do things with this object, like draw it on the screen.
The following is a list of functions that returns an instance of any special Sphere object, like images and fonts.
- 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.
- LoadAnimation(file) - Makes and prepares an animation object and returns it.
- LoadSpriteset(file) - Makes and prepares a spriteset object and returns it.
- LoadSurface(file) - Makes and prepares a surface object and returns it.
- LoadWindowStyle(file) - Makes and prepares a windowstyle object and returns it.
- OpenFile(file) - Makes and prepares a file object (for saving game data or settings) and returns it.
---
- 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. Better suited for manipulating the image, or drawing it in a special way (like warping it all over the screen).
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 (these are methods), and the Image object has a .blit() function (or method), etcetera. You can create your own objects too.
5. New functions
You can also put NEW functions in variables, like this:
var blah = function(parameters) { //Code comes here. }
This is basically a different way to declare a function. It's functionally equivalent to this:
function blah(parameters) { //Code comes here. }
This might seem useless, it has several uses:
- Objects use it to create methods (subfunctions, example is the getHeight() method in Font.getHeight()), because the syntax to make these is a bit different.
- You can make anonymous functions. These are normal functions that do not have a name. An example of doing this is when you pass a function as an argument:
function CallMe(argument) { argument(); //I'm sure that the argument actually contains a function! Let's call it. } //... CallMe(function() { Abort("something happens in here."); });
That's a lot of braces and parentheses! But all we do on the last line is create a function on the spot, on a single line, and not assign any identifiable name to it. I could also have done the following for the last line, but then you wouldn't call it an anonymous function anymore:
var somefunction = function() { Abort("something happens in here."); } CallMe(somefunction);
Still, it does the same thing; pass a function to another function, showing that functions can be allowed as "values" to pass to other things just as well as a number or a string.
6. true and false
true and false are keywords in JavaScript that are used when you only need to know two "states" about something. Some examples:
- Has an event happened? (you could call it a flag when used like this, you toggle the flag as you finish the event.)
var talked_to_old_man = false;
- Should my textbox draw a window?
var draw_a_window = true; //And in a textbox function somewhere: if (draw_a_window) //The condition evaluates to "true" because draw_a_window is true... { windowstyle.drawWindow(x, y, w, h); }
- Do I want to debug my game and show extra values on the screen?
var DEBUG = true; //Anywhere else in code: if (DEBUG) { /* Do something related to testing your game */ }
- Do I want to check if something finished in order to end a loop?
var finished = true; while (finished == false) { //Do whatever until I set finished to true somewhere in this loop. }
An alternative way of checking for false is by putting an exclamation mark in front of the condition (or variables in the condition), like this:
while (!finished)
- Do I want to check if something simply is true or false, or do I want to make it true or false?
if (!sound.isPlaying()) //Check if sound is not playing (sound.Playing == false). { sound.play(true); //The true here is an argument to sound.play, which answers Sphere's question: should the music loop? }
As you can see, it has many small but important uses. You'll encounter these two values a lot.
Last thing, remember that false is (sort of) equivalent to 0, and true is (sort of) equivalent to almost any other value. This means that a condition like (value == false) could be true when value equals 0! This can come in handy in places like loops.
7. undefined
undefined is a keyword in Sphere (or rather, JavaScript) that lets you enter nothing as a value! For example, some function's argument could be optional, and use some other default value if it's not set, so in this case you could pass the undefined value as an argument.
Or maybe you wish to erase a variable's previous value.
var blah = 4; blah = undefined; //Woops, setting 4 was a mistake.
Or maybe you wish to declare a variable, but not set a value yet... But then again, in that case you could just not set a value: JS will automatically enter undefined as the default value for a variable not given a value.
var blah; Abort(blah); //Sphere will quit, printing out "undefined".
8. Arrays
Arrays are somewhat different from the other variables mentioned so far. The big difference lies in that you can put multiple values in it, and these values can be of various types (even more arrays)!
Declaring the array
To make an array, you can type one of the following:
var blah = new Array();
- OR -
var blah = [];
I recommend using [] because it's shorter to type, though it doesn't really make a difference. The first way is a nice example of instantiating an object, though, so you might want to come back here later when you're learning about objects.
Storing values in the array
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 right when you declare the array.
var blah = new Array(1, 6, 4, "Theo", "etcetera", new Array("subarray!"), 88);
- OR -
var blah = [1, 6, 4, "Theo", "etcetera", ["subarray!"], 88];
This is how you declare the array and immediately put some values in it. An array is like a list of items where you can store a value, each seperated with a comma. All items in this list also have a number, starting from 0, which can be used to identify the seperate items, or places in the array.
- In the above array:
- The number 1 is stored in spot 0 of the array.
- The number 4 is stored in spot 2 of the array.
- The string "etcetera" is stored in spot 4 of the array.
- Another array (containing the string "subarray!" on spot 0) is stored in spot 5 of its parent (or containing) array.
Did I confuse ya? Read over it again, then continue. The second way to put values in an array will make things a bit clearer. :)
The second way to store values in an array is by already having declared the array, and then assigning values to spots in the array:
var array = []; //or new Array(); array[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!"; //Spot 0 contained the value 1 before, now it contains "new value!". blah[1] = 7; //And this used to be 6 blah[4] = "Pete"; //And this used to be "etcetera" blah[7] = "new value"; //Spot 7 comes after the last spot (spot 6, which contains 88), so basically we created a new spot to store a value in. blah[9] = [1, 2, 3]; //Another subarray with three items is added to the blah array. Spot 8 will contain an undefined value.
This way you can change the values (or make new values) on different places of your array. The old values (if there are any) are replaced, 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", ["subarray!"], 88, "new value", undefined, [1, 2, 3]]
Now how do we use these values? Well, that's pretty simple, actually. Just refer to your array and add straight brackets right after it containing the number of the spot you want to reach. For example:
var nn = blah[3]; //nn now contains the value "Theo". TextBox(blah[4]); //TextBox will print out the text "Pete". Abort(blah[9]); //Sphere will quit, showing the text "[1, 2, 3]" (the array gets interpreted as a string, showing its internal values).
So what are arrays useful for? Well, for example, they can be useful for an inventory:
var inventory = ["Potion", "Antidote", "Empty bottle"];
But most importantly, they can be used to store similar data together and perform mass actions on them. Like making of all characters in your game (or just the party) and then generating a person on the map for each one of them:
var people = ["DaVince", "Petey Pirate", "Aegis", "Flikky", "Nidoran"]; //Create persons using their above name for both the identifying name and the spriteset file to load (like DaVince.rss or Nidoran.rss). CreatePerson(people[0], people[0] + ".rss", true); CreatePerson(people[1], people[1] + ".rss", true); CreatePerson(people[2], people[2] + ".rss", true); CreatePerson(people[3], people[3] + ".rss", true); CreatePerson(people[4], people[4] + ".rss", true);
The above code can be made much simpler and quicker using loops, explained in the next chapter.
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! ;)