Differences

This shows you the differences between the selected revision and the current
version of the page.


wmebook:ch2 2007/12/06 10:50 wmebook:ch2 2008/07/21 19:47 current
Line 1: Line 1:
====== 2. Survivor's guide to WME scripting ====== ====== 2. Survivor's guide to WME scripting ======
-So we’ve managed to get over the first couple of WME tests, we’ve mastered the developers environment and now you’re surely eager to know how to advance! As you’ve probably guessed, the core of all WME operations lies in the scripts. But what IS the script?+We’ve already managed to get over the first couple of WME tests, we’ve mastered the developers environment and now you’re surely eager to know how to advance! As you’ve probably guessed, the core of all WME operations lies in the scripts. But what IS the script?
Let’s start from the very beginning. Every software is in its core “action / reaction” based. This means that something happens and the program somehow responds to it. The action can be anything ranging from player’s mouse clicks and ending with, for example, time which passes. So back to my question – what is a script? **It’s a program, which defines what actions to take care of and how to respond to them.** Let’s start from the very beginning. Every software is in its core “action / reaction” based. This means that something happens and the program somehow responds to it. The action can be anything ranging from player’s mouse clicks and ending with, for example, time which passes. So back to my question – what is a script? **It’s a program, which defines what actions to take care of and how to respond to them.**
-Now your typical WME game will be constructed from many scripts. Let’s say that you click with your mouse on a door. You’d need a script which would make your game avatar say “The door is locked.” I hope you get my point here.  As we dive deeper into this chapter, you see a lot of WME magic, but let’s start right at the beginning.+Now your typical WME game will be constructed from many scripts. Let’s say that you click with your mouse on a door. You’d need a script which would make your game avatar say “The door is locked.” I hope you get my point here.  As we dive deeper into this chapter, you see a lot of WME magic, but we're going to start right at the beginning.
The core of the WME programming lies in commands. Command tells WME to perform an action. We can have plenty of different commands ranging from simple mathematic operation (addition , substraction , etc) to complex commands like for example The core of the WME programming lies in commands. Command tells WME to perform an action. We can have plenty of different commands ranging from simple mathematic operation (addition , substraction , etc) to complex commands like for example
Line 11: Line 11:
<code script>Game.ChangeScene("some_scene.scene");</code> <code script>Game.ChangeScene("some_scene.scene");</code>
-which makes WME to change actual scene. But let’s look at the very basics of scripting. We’d start with something which is called variable. What is a variable? It’s a container in which you can store information. In WME (unlike for example in C++) you can store any type of information into your variable (string, object, number). +which makes WME to change actual scene. But let’s look at the very basics of scripting. We’re going to start with something which is called **variable**. What is a variable? It’s a container in which you can store information. In WME (unlike for example in C++) you can store any type of information into your variable (string, object, number).
Let’s look at an example: Let’s look at an example:
Line 17: Line 17:
<code script>var myvar = "Hello World";</code> <code script>var myvar = "Hello World";</code>
-The keyword var declares a local variable called myvar which has been filled by the text Hello World. Later on we can reference the text in the variable for example with:+The keyword var declares a local variable called myvar which has been filled with the text //Hello World//. Later on we can reference the text in the variable for example with:
<code script>Game.Msg(myvar);</code> <code script>Game.Msg(myvar);</code>
Line 25: Line 25:
//**Syntax rule no.1** //**Syntax rule no.1**
As you can see, every command ends up with a semicolon ; As you can see, every command ends up with a semicolon ;
-Also WME is case sensitive! hello is not equal to Hello. Keep this in mind!//+Also WME is case sensitive! myvar is not equal to MyVar. Keep this in mind!//
-Very important rule is that in each script we declare variable only **once**. Then we reference it without keyword //var//. +Very important rule is that in each script we declare variable only **once**. Then we reference it without the keyword //var//.
-Now let’s have a look at some basic work with variables:+Let’s have a look at some basic work with variables:
<code script> <code script>
Line 63: Line 63:
</code> </code>
-TIP: Always name your variable in an intelligent way so you find out later what is being stored inside. It’s of course funny to name a variable littleRedDwarf but if you look into your code 5 months later, you’ll be desperately trying to figure out why is your funny variable in there. Another common praxis is using lowerCamelCase or UpperCamelCase which is just a way how you capitalize letters in your variable name. So for example variable which should hold number of ingredients added to a kettle can be called for example kettleIngredients.+TIP: Always name your variable in an intelligent way so you can find out later what is being stored inside. It’s of course funny to name a variable littleRedDwarf but if you look into your code 5 months later, you’ll be desperately trying to figure out why is your funny variable in there. Another common praxis is using lowerCamelCase or UpperCamelCase which is just a way how you capitalize letters in your variable name. So for example variable which should hold number of ingredients added to a kettle can be called for example kettleIngredients.
-As you read, we’ve been speaking about something called **local variable**. The local means, that the variable is valid only in the script it's declared in. So imagine that we have two scripts which gets executed as test1.script followed by test2.script:+As you may noticed, we’ve been speaking about something called **local variable**. The //local// means, that the variable is valid only in the script it's declared in. So imagine that we have two scripts which gets executed as test1.script followed by test2.script:
**file test1.script** **file test1.script**
Line 103: Line 103:
</code> </code>
-**file test1.script**+**file test2.script**
<code script> <code script>
  global a = a + 1;   global a = a + 1;
Line 111: Line 111:
As the Real life example let's say that you have a button in some scene and if you press this button, you want some door in completely different scene to open. You simply declare a global variable and set it to true if the button was pressed. In the scene, where you find the door, you simply test this global variable and if it's set to true, you open the door. Just to clarify the term "true", there are two special values which you can set to variable - **true** and **false**. More about those in the conditions. As the Real life example let's say that you have a button in some scene and if you press this button, you want some door in completely different scene to open. You simply declare a global variable and set it to true if the button was pressed. In the scene, where you find the door, you simply test this global variable and if it's set to true, you open the door. Just to clarify the term "true", there are two special values which you can set to variable - **true** and **false**. More about those in the conditions.
-As we see, we’ve successfully uncovered variables, but wait - there’s much more to them. We’re just at the beginning.+We’ve successfully uncovered variables, but wait - there’s much more to them. We’re just at the beginning. 
====== 2.1 Magical Arrays ====== ====== 2.1 Magical Arrays ======
Line 165: Line 166:
<code script> <code script>
-var doorCode = “5”;+var doorCode = "5";
-doorCode = doorCode + “2”+doorCode = doorCode + "2"
-doorCode = doorCode + “3”+doorCode = doorCode + "3"
-doorCode = doorCode + “7”; // the result being 5237 in one variable.+doorCode = doorCode + "7"; // the result being 5237 in one variable.
</code> </code>
Well, we could, but then – what if you have more complex door code and wanted to change for example 3rd number when all 4 were set? It would make things much more complicated and also - we’re now demonstrating arrays so get over it. Well, we could, but then – what if you have more complex door code and wanted to change for example 3rd number when all 4 were set? It would make things much more complicated and also - we’re now demonstrating arrays so get over it.
-As you will get used to scripting, you’ll find a lot of use for arrays. The critical strength of arrays lies in the index. You can access the index value programmatically and that’s why we’ll look now in another real life example.+As you will get used to scripting, you’ll find a lot of use for arrays. The critical strength of arrays lies in the indexing. You can access the index value programmatically and that’s why we’ll look now in another real life example.
-You surely saw how better designed games use more different responses for one action so it won’t be boring. Let’s see how it can be done and let’s use an array for it. We’ll also incorporate a new command called **Random**.+You surely saw how better designed games use more different responses for one action so it won’t get too boring. Let’s see how it can be done and let’s use an array for it. We’ll also incorporate a new command called **Random**.
Random is a //function// which returns a random number in specified range. We’ll speak about functions and how they work later, so for now take it as something which works and don’t wonder why. Random is a //function// which returns a random number in specified range. We’ll speak about functions and how they work later, so for now take it as something which works and don’t wonder why.
Line 192: Line 193:
I think you’re getting a bit tired of this //variable// talk so we’ll focus now on different things and return to the big strength called **objects** a tad bit later on. I think you’re getting a bit tired of this //variable// talk so we’ll focus now on different things and return to the big strength called **objects** a tad bit later on.
- 
- 
- 
- 
- 
- 
- 
- 
====== 2.2 Conditions ====== ====== 2.2 Conditions ======
-Usually we need to know what’s going on. If we spoke before about the example with a door and a button, we spoke about testing if the button was pressed. But how do we actually do this test? We have a condition command called if which does the work for us. Again let’s start with some code:+Usually we need to know what’s going on. If we spoke before about the example with a door and a button, we spoke about testing if the button was pressed. But how do we actually do this test? We have a condition command called **if** which does the work for us. Again let’s start with some code:
<code script> <code script>
var a = 1; var a = 1;
-if (a == 1) Game.Msg(“A equals to one”); // this line can be read as: if a equals to 1 execute the following command +if (a == 1) Game.Msg("A equals to one"); // this line can be read as: if a equals to 1 execute the following command
</code> </code>
Line 235: Line 228:
</code> </code>
-But the fun doesn’t certainly end here! We can make much more complicated tests but to understand that, we have to look at another thing. +But the fun doesn’t certainly end here! We can make much more complicated tests but to understand them, we have to look at another thing. 
-Let’s get back to the beginning:+Back to the beginning:
Let's take our "if (a == 1)" and if we set variable //a// to 1 beforehand, we can read the command also as if 1 equals to 1. This statement is **true**. Let's take our "if (a == 1)" and if we set variable //a// to 1 beforehand, we can read the command also as if 1 equals to 1. This statement is **true**.
Line 268: Line 261:
**if ( (a>1 && a<10) || (b =="John") )** is one of the more complicated tests. It will execute the following command if the variable //a// is bigger than 1 AND smaller than 10 OR if variable //b// contains the word John. **if ( (a>1 && a<10) || (b =="John") )** is one of the more complicated tests. It will execute the following command if the variable //a// is bigger than 1 AND smaller than 10 OR if variable //b// contains the word John.
-//**Syntax rule no.4**+//**Syntax rule no.5**
If you want to execute multiple commands in the condition, you use **curly** brackets to enclose the commands which will then take place. If you want to execute multiple commands in the condition, you use **curly** brackets to enclose the commands which will then take place.
Example:// Example://
Line 277: Line 270:
}</code>//Both commands will be executed if variable a equals to 2// }</code>//Both commands will be executed if variable a equals to 2//
 +I think that you’ve already wondered if you want to test for some condition but also want to do the //false// statement some treatment. Here’s when the command **else** comes to play.
 +
 +<code script>
 +var a = 1;
 +
 +if (a == 1)
 +{
 + Game.Msg("It is true yet again.");
 + a = 10;
 +}
 +else
 + Game.Msg("Liars all over the code.");
 +
 +</code>
 +You can of course branch the else with more if’s ad absurdum.
 +
 +If is obviously practical, but there’s one example where you can solve the situation in more elegant manner. This elegant manner’s name is **switch**.
 +
 +What **switch** does is to branch the program into different paths according to a variable.
 +Let me show you an example:
 +<code script>
 +var a = Random(0,3); //we know this already!
 +var b = "";
 +
 +switch(a)
 +{
 + case 0:
 + Game.Msg("Branch 0");
 + b = "Hello";
 + break;
 + case 1:
 + Game.Msg("Branch 1");
 + b = "Good Bye";
 + break;
 + default:
 + Game.Msg("All other branches");
 + b = "What to do?";
 +}
 +</code>
 +
 +Okay. Here’s quite a lot of things going on. First we branch the code according to the variable //a//. This variable can be any number ranging from 0 to 3 (because of Random function). If a equals to 0  then we go through the first branch until we reach the command **break;** If this command wasn’t there, WME would go through all branches until it finds one! So if you want to terminate the branch use **break;**
 +
 +Each branch is defined by the keyword **case**. The specific syntax of **case** is that you define what should variable in the switch contain if you want to take this route. And after this value is a colon ( **:** ).
 +
 +We can also test for strings with for example *case "Sword":*
 +
 +And again – we enclose the whole nesting in the curly brackets. We’ll see a lot of curly brackets later on.
 +
 +BUG: Don’t use loops inside of the case branches. They don’t work. If you need, write a //function// (explained later) which will contain the loop. This workaround works.
 +
 +
 +====== 2.3. Loops ======
 +
 +There are many times when we want to use repeating actions. WME provides a couple of ways how can we accomplish that.
 +
 +We’ll start with the first way how to cycle – with the command **for**. This command is usable if we know the exact number of repetitions. Let’s say that we want to 10 times print the word //Hell//.
 +
 +<code script>
 +for (var a=0; a<10; a = a+1)
 +{
 +  Game.Msg("Hell");
 +}
 +</code>
 +
 +Let’s see what’s going on in here. The **for** command consists of 3 parts separated by semicolons. First part is where to start. In our case we start with a variable //a// set to 0. The second part is when to end. This is a bit tricky – **for** command ends when the second part, which is a condition, turns false! This means that it will loop until a<10. As soon as a turns 10, it will end. The last part is how to change the variable. We can use addition, substraction, multiplication, division, you name it... So in our case with each pass of the cycle, the variable a is increased by 1. Also note, that I’ve used curly brackets here even if it’s only one command in. Sometimes it’s more readable, but I’ll leave it to your preference.
 +
 +Important: The cycle runs 10 times. We’re starting with 0. Get used to 0 based start logic. It’s the source of many coding problems.
 +
 +Hmm. Printing ten times Hell isn’t THAT useful for game creating. Is it? Let’s see what more we can do. And this time we’re going to use Arrays for that.
 +
 +<code script>
 +var myArray;
 +myArray[0] = "Hi!";
 +myArray[1] = "How’s it goin’!";
 +myArray[2] = "Bye!";
 +
 +for (var a=0; a<3; a = a+1)
 +{
 +  Game.Msg(myArray[a]);
 +}
 +</code>
 +
 +As you can see, we’ve easily printed all array elements on the screen. I hope you’re starting to get the right impression of the usage.
 +
 +Another type of loop is so called **while** loop. This loop is used when we don’t know exactly how many times it should loop, but we know when it should stop.
 +
 +<code script>
 +var a = 0;
 +while (a != 5)
 +{
 +  a =  Random(0,5);
 +  Sleep(1);
 +}
 +</code>
 +
 +This probably useless example again evaluates the expression in while and if it’s true, it executes the block. So in other words, while a is not equal to 5, set another random number to it.
 +
 +**Important:**
 +Now you’re probably wondering what is going on with that Sleep(1); command. This is a bit more advanced issue, but if you tried the loop without the Sleep, your game would freeze and sometimes even your computer too. Why? Because the while loop would loop and loop and loop eating a lot of processor power. And the rest of the engine, which takes care of the timer and other things would never get the priority! So the whole WME would just loop. And if you’re unlucky and Random won’t be on your side returning all other numbers than 5, your computer will have serious problems. Function Sleep() which takes time in milliseconds doesn’t do anything  obvious. Waiting one millisecond can hardly be noticed, but it returns control from this script to other processes! So your game will never get stuck
 +
 +There’s also one more use for the **while** loop – so called //infinite loop//.
 +
 +it can be defined by this for example:
 +<code script>
 +while (1)
 +{
 +  //do something here;//
 +  Sleep(1);
 +}
 +</code>
 +
 +Those loops are very nice for some background processes you need to carry on for the whole game. For example you can check if the background music is playing and if it stops, you can play another song from the play list or in the demo project those processes handle caption displaying.
 +
 +
 +
 +====== 2.4. Functions ======
 +
 +As you already saw in the case of Sleep() or Random(), there’s something called a function. Function is a big time saver because it can take care of many lines of code. Imagine this example: you want to print ten times the word hell. But you want to print it in more than one parts of your code. Without function you’d do this:
 +
 +<code script>
 +for (var a=0; a<10;a=a+1) Game.Msg("Hell");
 +Game.Msg("1");
 +for (a=0; a<10;a=a+1) Game.Msg("Hell"); // note that I had to put the var away as it was already declared before.
 +Game.Msg("2");
 +for (a=0; a<10;a=a+1) Game.Msg("Hell"); // note that I had to put the var away as it was already declared before.
 +Game.Msg("3");
 +</code>
 +
 +Mess, isn’t it? So we’ll simplify our task using a **function**. Function is a piece of reusable code. It is defined by the keyword **function**, name of your preference and parentheses in which you can optionally put some parameters. The exit from the function is defined by a keyword **return;** Note that return forces function to leave immediately so you can use it with some logic code branching. So the basic declaration could look like this:
 +
 +<code script>
 +function Hell()
 +{
 +  for (a=0; a<10;a=a+1)
 +  Game.Msg("Hell");
 +  return;
 +}
 +
 +Hell();
 +Game.Msg(1);
 +Hell();
 +Game.Msg(2);
 +Hell();
 +Game.Msg(3);
 +</code>
 +
 +See, it’s much more readable. But it’s just a start. Imagine that with each pass you want to write 10 times different word. That’s when the functions really start to kick in. We’ll redefine our function with adding two parameters and rename it to for example writeText.
 +
 +<code script>
 +function writeText(what,count)
 +{
 +  for (a=0; a<count;a=a+1)
 +  Game.Msg(what);
 +  return;
 +}
 +
 +writeText("Hell",10);
 +writeText("on",2);
 +writeText("Earth",5);
 +</code>
 +
 +In the function the parameter works as a local variable which is valid only in the scope of the function. So our function has two parameters. First defines what to write and the second how many times it should be written. Our program would write 10 times //Hell//, 2 times //on// and 5 times //Earth//. As you can see, this function already simplified our task even more.
 +
 +So we know how to pass some data to the function but functions can also return data for us. Typical example of such function is Random. As we saw earlier, Random expects 2 parameters and returns a result. We can do the same through the keyword **return**. Let's write a simple function:
 +
 +<code script>
 +function isBigger(number1, number2)
 +{
 +    if (number1 > number2) return true;
 +    return false;
 +}
 +
 +if (isBigger(1,7)) Game.Msg("Number is higher");
 +else
 +  Game.Msg("Number is smaller");
 +</code>
 +
 +//**Syntax rule no. 6**
 +function name must contain only alphanumeric characters and there shouldn't be any whitespace characters.//
 +
 +Everything should be very clear at this point. If it’s not, please review the previous chapters before you can understand what’s going on. The only important thing is that we passed to **if** command, instead of our good old direct comparison, a //function//, which returns true or false. **if** command evaluates the function (which in this case returns //false//) and then executes the //else// block.
 +
 +
 +====== 2.5. Includes ======
 +
 +As we’ve seen the functions can be really useful but there’s a catch. There’s no way, how to define a global function. There are two workarounds though – through includes and through objects. Let’s speak about includes.
 +
 +If you looked a bit around the WME demo projects, you’ve seen, that every script starts with the line
 +
 +<code script>#include "scripts\base.inc"</code>
 +
 +This line prepends the contents of the file scripts\base.inc to this file. What’s it good for? Well, for example if you don’t want to declare your global variables every time you need them in a new script, simply put them into some inc file and include them. If you put them into your base.inc file, you’ll have this line included automatically because of the scene template. Useful isn’t it? But that’s not all. You can also put your commonly used functions into some include file and include those as well so you don’t need to copy/paste them to all scripts where you need them. Note that there's no semicolon at the end of the include line!
 +
 +**Important:**
 +Never initialize your variables in the include files. They will get reinitialized with every inclusion of your script.
 +
 +
 +====== 2.6. Objects ======
 +
 +Last chapter is dedicated to the very cool part of WME scripting language – objects.
 +
 +We’ll start slowly with the following thought. Imagine that you have some real world object. Let’s say a table. Now the term table is pretty abstract - It can be made out of plastic, wood, metal or whatever, it can have many colors, it can be expensive or cheap. Wouldn’t it be nice to have all information about such a table together?
 +
 +<code script>
 +var table;
 +
 +table.Material = "wood";
 +table.Color = "black";
 +table.Price = 100;
 +
 +Game.Msg(table.Price);
 +</code>
 +
 +What we’ve done here is that we’ve defined a variable, but instead of accessing this variable directly, we set a couple of //Attributes// to this variable. We no longer use the variable as a simple container. It became an object for us.
 +
 +Now you’re surely thinking “It’s all nice and everything, but what if we have 10 tables. Do we need 10 variables and declare them like this? It would be messy again”.
 +
 +Well, the magic of the objects is not only in //Attributes//, but also in **methods**. Method is normal function, which belongs to the object. All the time you’re using Game.Msg and now you've just discovered, that this is method of the object Game. The shocking revelation is, that almost everything you’ll be accessing from the WME side is object oriented and thus you’ll meet your fair share of objects for sure.
 +
 +But let’s get back to our task at hand – how do we actually define an object to be more versatile then only a couple of Attributes?
 +
 +First we’ll create an object definition file. Let’s call it table.script.
 +
 +<code script>
 +#include "scripts\base.inc"
 +
 +method initialize(material, color, price)
 +{
 +  this.Material = material;
 +  this.Color = color;
 +  this.Price = price;
 +}
 +</code>
 +
 +//**Syntax rule no. 5**
 +If we want to access attribute or method of an object, we use dot as seen in the previous example.//
 +
 +As we see here, we’re inside of the object so we can no longer use table.Material etc. because we don’t know how the variable holding our table will be called. That’s why we have a special identificator called **this** which points to the object itself. This way it will always set the attribute to the correct variable.
 +
 +In the script we want to create such an object, we have to first create it:
 +
 +<code script>
 +var table = new Object("table.script");
 +</code>
 +
 +and then we can setup object's properties through
 +
 +<code script>
 +table.initialize("wood","black",100);
 +</code>
 +
 +This already looks much more flexible, but we can go one more step further. Let’s say we’re going to create a game about a table seller who will have 10 different tables. Why not use an array for them?
 +
 +<code script>
 +for (var a=0;a<10;a=a+1)
 +{
 +  tables[a] = new Object("table.script");
 +}
 +</code>
 +
 +But here’s a pitfall! You can’t do something like: **tables[a].initialize();** because WME doesn’t support dot notation for arrays or nested objects. Also you can’t make something like **Game.Scene.SomeAttribute** because WME supports only one dot nesting. But there’s a workaround through temporary variable.
 +
 +The first case would be rewritten as:
 +<code script>
 +var tmp = tables[a];
 +tmp.initialize("wood","black",100);
 +</code>
 +
 +and the other like:
 +
 +<code script>
 +var tmp = Game.Scene;
 +tmp.SomeAttribute = 1;
 +</code>
 +
 +I think that this should be enough to get you started with scripting. The rest is just an application of what you have just learned. I’m sure that you’ll have no problems understanding what’s going on now.
 
wmebook/ch2.1196934623.txt.gz · Last modified: 2007/12/06 10:50 by metamorphium
Recent changes RSS feed Creative Commons License Driven by DokuWiki