Scripting:Basic course

From STNE Wiki

(Difference between revisions)
Jump to: navigation, search
(Parameters)
(Alternative to ShipManager: Ship.Action)
Line 384: Line 384:
kommt noch
kommt noch
-
===Alternative zum Schiffsmanager: Schiffsaktion===
+
=== An alternative to using the Ship Manager: Ship Action ===
-
Für Objekte des Typ's CMyFlotte und CMyShip kann über die Eigenschaft Aktion direkt auf die Funktionen des Schiffsmanagers zugegriffen werden.
+
The objects CMyShip (not CShip) And CMyFleet can access methods of the Ship Manager directly via the Action method of the object.
-
<pre><nowiki>VAR Schiff AS CMyShip = new CMyShip( 4711 )
+
<pre><nowiki>VAR Ship AS CMyShip = new CMyShip( 1 );
-
Schiff.Aktion.Abdocken()</nowiki></pre>
+
Ship.Action.Undock();</nowiki></pre>
-
<pre><nowiki>VAR Flotte AS CMyFlotte = new CMyFlotte( 4711 )
+
<pre><nowiki>VAR Fleet AS CMyFleet = new CMyFleet( 1 );
-
Flotte.Aktion.Abdocken()</nowiki></pre>
+
Fleet.Action.Undock();</nowiki></pre>
==Enumeration ist Alles==
==Enumeration ist Alles==

Revision as of 04:55, 12 November 2011

This page needs translation. You can help to complete the translation.



Main | Syntax | Operators | Interfaces | FAQ | Contents | API Reference | Index

This is a beginners course for the STNE engine script. It is not complete and probably not 100% correct. I have basically taught myself to use the STNE engine through trail and error, bad translation, good examples, and the benevolence of others. My spelling sucks. I'm sorry. If you see a mistake please fix it.

Contents

Vorwort

Much like the German version this course is aimed primarily at those who have never programmed and would like to start scripting in STNE. Please realize it is not easy and it will take a little while before you realize results. Be patient and keep at it! Like all good things it takes effort but it should be worth the time you put into it. I wish you the best of luck.

Chapter 1 - Strings

In programming a String is a series of characters. The chapter title would be a String as would this text. The famous line "Hello World!" is also a String and it is this String you will be working with.

"Hello World!"

We don't really know where it started but when first embarking on learning a programming language the first program you tend to write will be "Hello World!" In the STNE engine this is very easy. First launch the script editor under: Database -> Script Editor -> Create a new script -> Custom script without input wizard Then you will click "Edit source code". In the text field provided type:

WriteLine('Hello World!');

Now click Save&Run. Did it work? If not double check your input. Are the capital letters capital? Are there opening and closing quote marks and parentheses? Does it end with a semicolon? When it works you should see the line:

Hello World!
Congratulations you are now programming. Try making a program that says:
Hello World!
Live long and prosper!

Your code should look like this:

WriteLine('Hello World!');
WriteLine('Live long and prosper!');

Note every line of code ends with a semicolon. But what if you want to write everything on one line:

Hello World! Live long and prosper!

This is done by use of the & symbol:

WriteLine('Hello World!'&' Live long and prosper!');

The & symbol allows you to combine two Strings. It literately sticks them right next to each other which is why ' Live long and prosper!' has the preceding space. See what happens when you remove it!

"But wait!" You say. "I could simple code:
WriteLine('Hello World! Live long and prosper!');
and never have to deal with the & symbol!"

True, and as a programmer you will have many choices of different ways to do things. But the '&' is important as you will find out in the next chapter.

Summary: Strings

  • A String is a sequence of several characters.
  • A String is output, or printed, using the command WriteLine();.
  • You may use the character & to combine one String with another within the parameters, or parentheses, of WriteLine();.

Chapter 2 - Variables

Basic types

Think of a variable as a reference that you can use again and again and again. They can be a word, a number, or true/false. These are all called Data Types and, of course, each has a special name:

  • String - a series of characters
  • Integer - a whole number
  • Boolean - decision (True/False)

Variables

Imagine you have a gigantic project with hundreds of lines of code. Dozens upon dozens of times your code will output the lines:

Captains log Stardate:

You could code:

WriteLine('Captains log Stardate:');

every single time and maybe misspell it. Or you could use a variable. Before a variable can be used, or called, it must be created. You do this with the word "Var" followed by the name followed by "As" followed by the type of variable it is followed by "=" followed by the data to be stored.

Sound complicated? Bear with us.

In keeping with the above example let us declare a String variable that contains the line: 'Captains log Stardate:'

Var CL As String = 'Captains Log Stardate:';

the name can be anything you choose it to be. In this example we used the letters CL because they are an acronym for Captains Log but you could as easily use LC or X or foo. Choose something that makes sense to you because you will use it through your code. No two variables can have the same name though.

Lets create a number, or integer, variable:

Var SD As Integer = 234121;

Notice that because this is a number the type is Integer and because this is not a String we DO NOT put quotes around the assignment (what follows the equal sign). When you run this program, though, it doesn't seem to do much. That is because everything is happening behind the curtain and trust us you don't want to look back there! But if we add an output statement:

WriteLine(CL & SD);

Things start to happen. Cool huh? Just in case your having trouble your code should look like this:

Var CL As String = 'Captains Log Stardate:';
Var SD As Integer = 234121;
WriteLine(CL & SD);

Remember that variable assignments always have to come before variable calls. Your code is executed one line at a time and it needs to know what CL is before it can WriteLine CL. Also note the clever use of the & symbol. It stuck the integer and the string together! The output looks like:

Captains Log Stardate:234121

See if you can find a way to get a space between the colon and the number...

Captains Log Stardate: 234121

Converting One Data Type to Another

In many programming languages including an older version of the STNE engine you often need to convert variables from one type to another. For instance if you had a variable:

Var number As Integer = 12345;

You couldn't use it in certain functions like

WriteLine(number);

Because the parameters for WriteLine() would only accept Strings and the variable 'number' is an Integer.

In that case you would use another function CStr() to convert it to a String:

CStr(number)

You could even place that inside the parameters of WriteLine():

WriteLine(CStr(number));

Likewise you could covert a String to it's integer value with CInt();

But lucky for us the language is much smarter now and this has become a problem of such little significance that we can not even think up a satisfactory example.

Rules for Naming Variables

There are some rules for naming your variables

  • Do not duplicate names. Each script you make must only use a name once, and those names are case insensitive. This means that FOO and foo are actually the same.
  • Do not use spaces. Use capital letters to signify different words.
  • Do not use reserved names. Certain names are needed by the complier and by the STNE system and should be avoided. This names include dates, commands for system-defined functions, and features.
  • For clear coding consider starting your variable name with a three digits representing the variable type. For example:
intDeutNeeded
  • Remember always attempt to make your code as easy to understand as possible. Someday you will come back to it and try to understand what you were attempting.

Summary: Variables

  • A variable takes the place of "hard coded" data.
  • To create a variable use 'VAR Name AS Datentype;
  • To assign data to a variable you use Name = Inhalt;
  • To output a variable use WriteLine(Name); This can be very important when debugging.
  • The & symbol connects variables withing a function callWriteLine();

Chapter 3 - Control Structures

Now that you know how to create and use variables it is time to tackle Control Structures. These are the decision making lines that will make your scripts very powerful.

If - Else

This works exactly how it sounds. IF evaluates a statement and when it is true will execute the next few lines of code that are within curly braces "{" and "}". You can also include an ELSE statement that will execute when the IF evaluates to false. For example this code evaluates a variable and executes the code within the curly braces in response:

Var tribbles As Boolean = True;
If (tribbles){
  WriteLine('Oh no! The food!');
}
Else{
  WriteLine('The food is safe.');
}

When the code runs it will evaluate tribbles. See it is true and then run the code within the curly braces and ignore the code after the ELSE statement. Try it out.

You can also use an IF statement to compare amounts. In that case you would use the equal symbol:

Var EPSamount As Integer = 44;
If (EPSamount = 45){
  WriteLine('We have exactly ' & EPSamount & ' available');
}
Else{
  WriteLine('Im givin her all shes got, Cpatain!');
}

Since EPSamount does not equal 45 this the statement will evaluate to false. It then ignores the code after the IF statement and executes the code after the ELSE statement.

You can also use "<",">","<=",">=" for different types of comparisons. In that order and in English those are called "less then", "greater then", "less then or equal to", and "greater then or equal to". These can be a little confusing at first so remember the bigger side of the symbol is toward the larger number. "a<b" says that a is less then b. b is greater. You can also you the words "AND" and "OR" to write more complex IF statements with multiple tests but each test will need to be inside it's own parentheses which can get very confusing very fast:

If ((dilth>5)AND(deut>10)AND(ANTIM>10)){
  WriteLine('Ready for deep space exploration');
}
Else{
  WriteLine('Are you crazy? We wont make it past pluto!');
}

Remember the more clear your code is the easier it is for someone in the future, probably you, to understand it so you might re-write the above statement using more variables:

Var dilth AS Boolean = (dilthAmount>5);
Var deut AS Boolean = (deutAmount>10);
Var antiM As Boolean = (antiMAmount>10);
If ((dilth)AND(deut)AND(antiM)){
  WriteLine('Ready for deep space exploration');
}
Else{
  WriteLine('Are you crazy? We wont make it past pluto!');
}

It is completely up to you!

Loops

The next important control structure to learn are loops. A loop works like an if statement, that is executing the lines of code within curly braces "{" "}" but a loop will not exit until the conditions that started become false.

While

Consider the following code:

Var ore As integer= 0;
WriteLine('Do you need ore?');
while ((ore < 12)){
  WriteLine('We have ' & ore &' ore. We need more ore!');
  ore = ore + 2;
}
WriteLine('Thanks. We can start making Duranium.');

When executing the WHILE repeats until ore reaches twelve and then it moves on. This type of code can cause problems though when you write a statement that will never evaluate false:

Var isKilingon As Boolean = True;
while (isKilingon){
  WriteLine('Today is a good day to die!');
}
WriteLine('Enough battle!');

If run this code would print the line 'Today is a good day to die!' forever and never print the line 'Enough battle'. Luckily when this happens the STNE engine steps in and kills the script.

Do

DO loops work just like WHILE loops except that regardless the evaluation a DO will execute at least once.

VAR friendlyShip AS Boolean = False;
WriteLine('Ship on Federation sensors');
Do(friendlyShip){
  WriteLine('Hale them.');
}
WriteLine('No response. Open fire!');

When this script is run, regardless of the fact that the statement evaluated false it will run once. If something happened inside the statement that made it become true though it would run again.

For

A FOR loop works just like a WHILE loop except it has a built in integer variable which it increments after every loop. This makes it very good for incrementing. Consider our earlier example:

Var ore As integer= 0;
WriteLine('Do you need ore?');
while ((ore < 12)){
  WriteLine('We have ' & ore &' ore. We need more ore!');
  ore = ore + 2;
}
WriteLine('Thanks. We can start making Duranium.');

This could also be written using a FOR loop:

Var ore As integer;
WriteLine('Do you need ore?');
for(ore=0 To 12 Step 2){
  WriteLine('We have ' & ore &' ore. We need more ore!');
}
WriteLine('Thanks. We can start making Duranium.');

See how the incrementation is taken care of in the parameters, or between the parentheses? It takes the integer variable ore from 0 to 12 by sets of 2.

If you do not specify a step it will assume the step is 1.

Chapter 4 - Functions

Introduction

The last object to learn about are functions. A function is a series of lines of code that can be called from main to run again and again. Consider that we have the following code.

WriteLine('Get them out of there!');
WriteLine('Attempting to beam up away-team');

But you want to run that ten times. You could write those two lines ten times or you could make a function. In that way a function can act similar to variables though as you will see they are much more powerful. To create a function you use the following formula 'Function' followed by the name you give it, followed by the symbols "(){}" Here is an example using the code above:

Function BeamUp(){
  WriteLine('Get them out of there!');
  WriteLine('Attempting to beam up away-team');
}

Now every time BeamUp() is called it looks through the entire script for the Function BeamUp() and will run those two lines of code. For example:

WriteLine('We are at the Borg ship.');
BeamUp();
WriteLine('We are at the Klingon colony.');
BeamUp();
Function BeamUp(){
  WriteLine('Get them out of there!');
  WriteLine('Attempting to beam up away-team!');
}
WriteLine('We are at the Syndicate station');
BeamUp();

Parameters

But it gets better. You can pass a function variables making it more versatile. To specify what types of variables a function can be passed you need to declare them between the parenthesis "()". These are called the Functions Parameters. You declare a function in the parameters the same way you do in regular code and you can declare as many variables of any type as you want so long as you separate them by comas. For example

Function BeamUp(number As Int32, crew As Boolean, teamName As String){
  If(crew){
    WriteLine('Beaming up ' & number & ' ' & teamName & '.');
    WriteLine('Attempting to beam up away-team!');
    Else{
      WriteLine('There is nobody there');
    }
  }
} 

For some reason when the compiler checks for errors it replaces the word Integer with Int32. Don't worry. It you write either one your code will still work. Now when you make the function call you need to pass it values that match it's parameters. In the above example you might call it this way:

BeamUp(5, True, Medics);
Function BeamUp(number As Int32, crew As Boolean, teamName As String){
  If(crew){
    WriteLine('Beaming up ' & number & ' ' & teamName & '.');
    WriteLine('Attempting to beam up away-team!');
    Else{
      WriteLine('There is nobody there');
    }
  }
}
WriteLine('We are at the Borg ship.');
BeamUp();
WriteLine('We are at the Klingon colony.');
BeamUp();
WriteLine('We are at the Syndicate station');
BeamUp();

Also for clarity consider keeping your Functions separate from your main code either all above or all bellow.

Now that we now have a few basics, let us turn to the really interesting parts, the control of the game content through scripts.

To interact with ships there is a collection of methods, which can be found in CShipManager. To use them, we must first assign a ShipManager to either a ship or a fleet. This is done via assignment of a new CShipManager variable

Var ShipManager As New CShipManager();

To assign the safety officer, there are the commands:

ShipManager.SelectShip(NCC-Number of Ship);

or,

ShipManager.SelectFleet(ID of Fleet);

This way the ShipManager knows which ship or fleet to interact with.

Syntax:

 CShipManager.TransferToShip(ToShipID, Amount, EBeamResource.Resource)

You just need to replace the parameters with the respective values. Here's an example:

 ShipManager.SelectShip (1);
 ShipManager.TransferToShip (2, 20, EBeamRessource.Food);

Of course, you can also beam from an entire fleet, if your replace ShipManager.SelectShip(1) by ShipManager.SelectFleet(1), Then the script transfers the amount from every ship in a fleet:

 ShipManager.BenutzteFlotte (1);
 ShipManager.TransferToShip (2, 20, EBeamRessource.Food);

With the Ship Managers, you can do the following:

  • Docking and undocking
  • Alert level change
  • Escape from fleets
  • Enter or leave orbit
  • Rename (name As String)
  • Collect deuterium (only with FP)
  • Gather ore (only with FP)
  • Fly (FlyTo() AutoPilot, only with FP)
  • Fly (Using the Fly() method)
  • Tractor beam on / off
  • Beaming
  • Hide
  • Enable / Disable the Replicators
  • Jettison Goods
  • Enable / Disable the Warp Core
  • Wreck extraction
  • And more

For a complete list of the CShipManager features, see Object Explorer.

Next, we will look at some specific features:

Beaming

Syntax:

 CShipManager.TransferToShip(ToShipID, Amount, EBeamResource.Resource)

You just need to replace the parameters with the respective values. Here's an example:

 ShipManager.SelectShip (1);
 ShipManager.TransferToShip (2, 20, EBeamRessource.Food);

Of course, you can also beam from an entire fleet, if your replace ShipManager.SelectShip(1) by ShipManager.SelectFleet(1), Then the script transfers the amount from every ship in a fleet:

 ShipManager.SelectFleet (1);
 ShipManager.TransferToShip (2, 20, EBeamRessource.Food);

Flying

There are two versions of flying, CShipManager.FlyTo() (For players with the Feature-Pack), and CShipManager.Fly() (Works for everyone). FlyTo() is an auto pilot, like the helm control with FP, while Fly() moves you a number of sectors in a straight line.

Flying with the Autopilot

Only for players with the feature pack!


The command:

 ShipManager.FlyTo ('xxx | yyy');

Again, it you need to replace the italicized parameter 'xxx | yyy' with something appropriate. Here is an example:

ShipManager.SelectShip(1);
ShipManager.FlyTo('123|465');

Or, with a fleet:

ShipManager.SelectFleet(1);
ShipManager.FlyTo('123|465');

With this command, the ship or fleet flew through space to the destination, using the auto pilot to bypass NPC Areas, energy-intensive obstacles, and those which endanger the ship or the crew

Flying without the Autopilot

The command for this is as follows:

 ShipManager.Fly (distance,EShipDirection.Direction);

Here is an example:

 ShipManager.SelectShip (1);
 ShipManager.Fly (5, EShipDirection.Up);
 ShipManager.Fly (8, EShipDirection.Left);

or if you wanted to move an entire fleet:

 ShipManager.SelectFleet (1);
 ShipManager.Fly (5, EShipDirection.Up);
 ShipManager.Fly (8, EShipDirection.Left);

Please note, Fly() will NOT avoid dangerous areas, it will fly in a straight line though Nebulas etc.

Schiffsystem nutzen

kommt noch

An alternative to using the Ship Manager: Ship Action

The objects CMyShip (not CShip) And CMyFleet can access methods of the Ship Manager directly via the Action method of the object.

VAR Ship AS CMyShip = new CMyShip( 1 );
Ship.Action.Undock();
VAR Fleet AS CMyFleet = new CMyFleet( 1 );
Fleet.Action.Undock();

Enumeration ist Alles

kommt noch

Methoden

Öfters wiederkehrende Aufgaben können in Methoden zusammengefasst werden:

Function ShowKoords(x As Integer, y As Integer)
{
  WriteLine(CStr(x) + '|' + CStr(y));
}

Die Methode ShowKoords kann dann im Script folgendermaßen aufgerufen werden:

ShowKoords(3, 4);
ShowKoords(ship.MapPosition.X,ship.MapPosition.Y);

Wenn berechnete Werte von der Methode zurückgegeben werden sollen:

Function Distanz(x1 As Integer, y1 As Integer, x2 As Integer, y2 As Integer) As Integer
{
  Var distanz As Integer;
  
  distanz = Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
  Return distanz ;
}

WriteLine(Distanz(1, 1, 5, 5));

Einfache Typen werden immer 'ByVal' übergeben, d.h. die Werte werden als Kopie an die Methode übergeben und die entsprechenden Variablen im Script nicht verändert. 'ByRef' ist zwar in der Scriptengine vorgesehen und kann angegeben werden, ist aber derzeit ohne Funktion. Objekte werden immer ByRef übergeben.

Klassen

In Klassen können Daten und Methoden in einem Objekt gekapselt werden:

Class CKoords
{
  Var x As Integer;
  Var y As Integer;
  
  Function New(x As Integer, y As Integer)
  {
    This.x = x;
    This.y = y;
  }
  
  Function ToString() As String
  {
    Return (CStr(x) + '|' + CStr(y);
  }
  
  Function Distanz(koord As CKoords) As Integer
  {
    Return Math.Abs(x - koord.x) + Math.Abs(y - koord.y);
  }
}

Var ko1 As New CKoords(3, 5);
Var ko2 As CKoords;


ko2 = New CKoords(8, 9);
WriteLine('Distanz von ' + ko1.ToString() + ' nach ' + ko2.ToString() + ': ' + CStr(ko1.Distanz(ko2)));

Wichtig: Klassen brauchen immer eine Methode New(), sonst kann kein neues Objekt der Klasse generiert werden!

Autoren

(hier dürfen sich diejenigen verewigen die hier min. ein Kapitel geschrieben haben [sonst kommt noch einer daher nur weil er nen Rechtschreibfehler verbessert hat ;)])

Nickname IG-id Kapitel
WiZz4Rd 16475 Kapitel 1, Kapitel 2, Kapitel 4
Stryke 28885 Vorwort, Kapitel 3, Kapitel 4
Xenon 10127 Korrektur & Überarbeitung Kapitel 1
Fling 54865 Kapitel 7, Kapitel 8


Anfängerkurs