Scripting:Basic course

From STNE Wiki

(Difference between revisions)
Jump to: navigation, search
Line 298: Line 298:
-
Nachdem wir nun über ein paar Grundlagen verfügen, wollen wir uns den wirklich interessanten Dingen zuwenden, der Steuerung von Spielinhalten durch Scripte.
+
Now that we now have a few basics, let us turn to the really interesting things, the control of game content through scripts.
-
Um mit Schiffen zu interagieren gibt es eine Sammlung von Methoden, welche im Shipmanager zu finden sind.
+
To interact with ships there is a collection of methods, which can be found in the Ship managers  CShipManager. For this we must first assign a Ship manager to either a ship or a fleet.
-
Hierzu müssen wir dem Shipmanager als erstes Mitteilen, welches bzw. welche Flotte er verwenden soll.
+
-
Hierführ gibt es die Befehle:
+
To assign the safety officer, there are the commands:
-
<pre><nowiki>ShipManager.SelectShip(NCC-Nummer of Ship);</nowiki></pre>
+
<pre><nowiki>ShipManager.SelectShip(NCC-Number of Ship);</nowiki></pre>
or,
or,
<pre><nowiki>ShipManager.SelectFleet(ID of Fleet);</nowiki></pre>
<pre><nowiki>ShipManager.SelectFleet(ID of Fleet);</nowiki></pre>

Revision as of 17:19, 11 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 things, the control of game content through scripts.

To interact with ships there is a collection of methods, which can be found in the Ship managers CShipManager. For this we must first assign a Ship manager to either a ship or a fleet.

To assign the safety officer, there are the commands:

ShipManager.SelectShip(NCC-Number of Ship);

or,

ShipManager.SelectFleet(ID of Fleet);

Damit weiß der ShipManager schonmal welches Schiff, bzw. welche Flotte die Aktionen ausführen soll.

Mit dem Shipmanager können folgende Aktionen ausgeführt werden:

  • An- und Abdocken
  • Alarm Stufe ändern
  • Aus Flotten austreten
  • Aus Orbit einfliegen austreten
  • Benennen(Name As String)
  • Deuterium sammeln (Nur mit FP)
  • Erz sammeln (Nur mit FP)
  • Fliegen
  • Sensoren aktivieren / deaktivieren
  • Reparieren
  • Batterien entladen
  • Schilde aktivieren/deaktiviere/aufladen
  • Reservebatterie aufladen
  • Traktorstrahl ein- / ausschalten
  • Beamen
  • Verstecken
  • Replikator aktivieren/deaktivieren
  • Waren über Bord werfen
  • Warpkern aktiveren/deaktivieren
  • Wrackextraktoren

Eine vollständige Auflistung aller Funktionen findet sich im Objekt-Explorer.

Im folgenden wollen wir uns einige Funktionen genauer anschauen:

Beamen

Syntaxe:

ShipManager.TransferiereZuSchiff(Schiffid, Menge, EBeamRessource.Ware);

Hier musst du nun nurnoch den kursiven Text mit deinen Angaben ersetzten. Hier ein Beispiele:

ShipManager.BenutzteSchiff(1);
ShipManager.TransferiereZuSchiff(2, 20, EBeamRessource.Nahrung);

Natürlich kann man auch eine ganze Flotte beamen lassen, dazu ersetzt du ShipManager.BenutzteSchiff(1); durch ShipManager.BenutzteFlotte(1); Dann sieht das Script folgendermasen aus:

ShipManager.BenutzteFlotte(1);
ShipManager.TransferiereZuSchiff(2, 20, EBeamRessource.Nahrung);

Fliegen

Bei der Syntaxe gibt es 2 Möglichkeiten, die eine für Spieler unter Level 8 oder mit Feature-Pack, also mit Autopilot, und die andere für die Leute über Level 8 und ohne Feature-Pack, die Variante ohne Autopilot.

Fliegen mit dem Autopiloten

Nur für Spieler mit Feature-Pack oder unter Kolonisationslevel 8 möglich!

Der Befehl:

ShipManager.FliegeZu(xxx|yyy);

Auch hier Gilt es wieder das kursive durch die eigenen Angaben zu ersetzten. Wie in folgendem Beispiel:

ShipManager.BenutzteSchiff(1);
ShipManager.FliegeZu('123|465');

oder mit dem Flottenbefehl:

ShipManager.BenutzteFlotte(1);
ShipManager.FliegeZu('123|465');

Mit deisem Befehl fliegt das Schiff zu einer belibigen Position, NPC-Gebiete ausgenommen, und umgeht dabei wie der Autopilot Energie-intensive Hindernisse, sowie solche die das Schiff oder die Crew Gefährden.

Fliegen ohne Autopilot

Der Befehl hierzu sieht wie folgt aus:

ShipManager.Fliege(Strecke, EShipRichtung.Richtung);

Auch hier ersetzt du die kursiven Worte mit deinen Angaben, ein Beispiel folgt:

ShipManager.BenutzteSchiff(1);
ShipManager.Fliege(5, EShipRichtung.Hoch);
ShipManager.Fliege(8, EshipRichtung.Links);

oder wenn es eine ganze Flotte ist:

ShipManager.BenutzteFlotte(1);
ShipManager.Fliege(5, EShipRichtung.Hoch);
ShipManager.Fliege(8, EshipRichtung.Links);

Schiffsystem nutzen

kommt noch

Alternative zum Schiffsmanager: Schiffsaktion

Für Objekte des Typ's CMyFlotte und CMyShip kann über die Eigenschaft Aktion direkt auf die Funktionen des Schiffsmanagers zugegriffen werden.

VAR Schiff AS CMyShip = new CMyShip( 4711 )
Schiff.Aktion.Abdocken()
VAR Flotte AS CMyFlotte = new CMyFlotte( 4711 )
Flotte.Aktion.Abdocken()

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

Personal tools