Hackscript Tutorial

From Hack Wars Wiki

Jump to: navigation, search

Contents

[edit] Introduction

HackWars encourages players to program to increase their skills and standing within the game. Although you don't need to program to play HackWars (because you can buy applications from Stores), you can fine-tune exactly what your computer does in any situation by creating your own scripts in Hackscript, the HackWars scripting language. Scripts are also the main source of trade revenue as players will pay greatly for scripts with overwhelming power. When you compile scripts, they're called applications or programs.

Here you will find everything you need to know to get started programming in Hackscript.

[edit] Script Editor

To create a new program in Hack Wars, the first step is to find the Script Editor under Applications. The Script Editor allows you to choose which type of script you’d like to create (Banking, Attack, etc.). Each type of script has various components, e.g., a Banking script has Deposit, Withdrawal, and Transfer components. These correspond with actual events that happen while playing the game. For instance, any code you write into the Deposit component will be run when a player attempts to perform a Deposit transaction with their Bank.

Hack Wars programming is event-driven. There are limitations as to what functions can be run at any given time, depending on the type of program you are making and the ‘event’: functions called in the ‘Finalize’ portion of an Attack script must be functions that can be called when finalizing an attack.

[edit] Types of Scripts

[edit] Banking Scripts

A banking script has three ‘events’:

  • Deposit: called when a player attempts to make a deposit to his or her bank.
  • Withdrawal: called when a player attempts to withdraw from his or her bank. Restriction: If you are writing a malicious withdraw script, you can only steal as much money as the player has requested to withdraw. This ensures that your bank is secure despite malicious scripts.
  • Transfer: called when a player attempts to make a transfer to another player.

[edit] Attack

An attack script has three ‘events’:

  • Initialize: called before the attack actually begins. This allows you to preemptively cancel an attack based on certain parameters. This is also where malicious zombie codes are placed.
  • Continue: called each time the attack is about to deal damage. Restriction: you can also place berserk in continue to deal extra damage. This can be called only once per continue.
  • Finalize: called when an attack has been completed, and the opponent’s port is in a weakened state. To perform a malicious operation, one of the ‘finalize’ methods listed in the Attack API can be called here. Restriction: Only one finalize method may be called in an attack.

[edit] Redirect

Although redirect scripts are similar to attack scripts they do not share the functions of the attack API. Thats why Continue and Finalize are often left unchanged.

A redirect script has three ‘events’:

  • Initialize: called before the attack actually begins. Here you set what to redirect.
  • Continue: called each time the attack is about to deal damage. Usually unchanged.
  • Finalize: called when an attack has been completed, and the opponent’s port is in a weakened state. Usually unchanged.

[edit] FTP Scripts

  • Put: called when a player attempts to place a file from their home directory into either the Store or Public FTP directory.
  • Get: called when a player attempts to retrieve a file from their Store or Public FTP directory and replace it on their home computer.

[edit] Watch

  • Fire: called when one of the various events that can cause a Watch to fire has taken place, such as an attack, scan, or change in amount of Petty Cash.

[edit] HTTP Scripts

  • Enter: Called when a player first visits your website.
  • Submit: Called when a player submits a form on your website.
  • Exit: Called when a player leaves your website.

A full list of functions that can be called is given in the Hackscript API section, listed by type of script.


[edit] Compiling and Decompiling Programs

[edit] Compiling scripts

Compiling a script requires that a player has attained the level required to call the functions, as listed in the API, and also that the player pays the appropriate amount of money, determined by the functions called within the program and the number of occurrences.

A program is compiled by clicking the appropriate button Image:Compile.png in the Script Editor. Prior to compiling, it is advisable to Test Compile: this gives the player the compiling cost and tests the code’s validity. If the test compile finds invalid code, the event containing the faulty code is identified. The player’s name is attached to the program upon compiling.

Compiled programs can be installed on a player’s ports in Port Management (see below, section on Installing Programs), sold in stores to other players or installed on an opponent’s port after a successful attack.

While compiling code is restricted based on level, a player of a lower level may still install a program he or she has bought or traded.

[edit] De-compiling programs

A player is allowed to de-compile his own programs by selecting the binary in the File Browser (System—Home) and clicking the De-compile button Image:Decompile.png at the top of the window. This will return 90% of the compile cost to the player; also, 90% of the experienced gained from compiling the program will be deducted. An uncompiled version of the script will appear on the player’s hard drive, which can now be edited. This can be useful to merchants who may have a large quantity of files to which they wish to make a change. Note that once a program has been installed, it cannot be removed, and therefore not de-compiled. Only the player who compiled the binary can decompile it again.

Please note that the money returned is 90% of the compile cost, and NOT the price set by the user.

[edit] Syntax

Programming in Hack Wars is close to a programming language called C. This is a very pervasive standard in computing. For those not familiar with this programming language, this section of the wiki will give a good overview. Even for experienced programmers, it is good to read through this section to see some of the limitations presented by the HackWars programming language.

[edit] Hello World

Create a new HTTP script and put in the following in Enter. Leave Submit and Leave unchanged.

int main(){
message(getVisitorIP(),"Hello World");
}

Compile and install that script as your default HTTP script. Now visit your own website via the website browser. Everytime you or anybody else visits your website "Hello World" will apear in the visitor's game messages. This code works in all script types and all sections of a script but it will show the Hello World message for other events then.

  • int main(){ is required in every script and marks the point the script will start to run.
  • message() is a function that will send a message
  • getVisitorIP() this will give your own ip, which is used by message() in this example
  • } in this example it marks the end of the main function

[edit] Data Types and Variables

These two topics are closely related: when you program, you have "variables" which store your information of a certain "data type". For example, if I wanted to store my age, I know that my age is always an integer value. I could create a variable called "age" of type "int":

int age = 28;


The other thing you'll notice here is that I assigned my age a value, in this case 28, using the '=' logical operator. After I've created a variable, I can then change its value:

int age = 28;
age = 234;


The last thing to note here is the semicolon (;) at the end of the statement. Almost all statements require semicolons at the end of them (with the exception of if statements and loops, which use curly braces {}).

You can use the following data types when declaring variables in Hackscript:

  • int
  • float
  • string
  • boolean

int is for integers (must not have a decimal place). float is for floating point numbers (can have decimal places). string is for text, and assigned using quotations marks (see example below). boolean stores either true or false.

Here’s an example of a script snippet using all four types:

int a = 10;
float b = 5.5;
string msg = "You are being sent a message.";
boolean myBool = true;
if(myBool && (b>5.0 || a<10)){
	message(getSourceIP(), msg);
}


First we declare our numerical variables (the int and the float). Then we create a string, and a boolean that is true. The we send a message only if the conditional statement is true: if myBool is true and either b > 5 OR a < 10. Since myBool is true and b >5, the message would be sent.

Note that when we created the boolean myBool, we assigned it the value true. Then in the if statement, we didn't need to explicitly say if (myBool == true && ...). That's because when checking boolean values in if statements, unless we explicitly check myBool== false then it's assumed that we mean myBool==true

If you placed this script, for instance, in the deposit entry point of a banking application, it would always send you the message “You are being sent a message.” when you attempt to deposit — the deposit would not happen, mind you, since it contains no code to perform this operation.

[edit] Assigning Values

Above, we assigned a variable a value using the '=' logical operator. You can also assign values using ‘++’,'--’,'*=’, etc. So, for instance, if you had a counter in a loop you could increment it using the following code:

int i=0;
while(i<10){
  i=i+1;
}


or

int i=0;
while(i<10){
  i++;
}


[edit] Logical Operators

Logical operators compare two different true or false values, and return a new true or false value.

Operator Name Usage
== Equal A == B is true when A and B are equal.
 != Not Equal A != B is true when A and B are not equal.
< Less Than A < B is true when A is less than B.
<= Less Than Or Equals A <= B is true when A is less than or equal to B.
> Greater Than A > B is true when A is greater than B.
>= Greater Than Or Equals A >= B is true when A is greater than or equal to B.
&& And A && B is true when both A and B are true.
|| Or A || B is true when either A or B is true.


[edit] Modulus

Many people get confused when the word modulus is mentioned. So what is it and how does it work? Well, it is like your old school long division except it returns the remainder of the division instead of the actual answer (how many times x goes into y, etc).

Here is an example in HackScript:

int myVariable = 10%3;


That above line doesn't look like much, except for the fact that 'myVariable' is actually set to 1. It does this by testing 10, to see how many times 3 fits into 10 (i.e. three 3s are equal to 9), then subtracts the total value of those 3s from 10. So, 10 - 9 = 1 and thats your modulus result. It will always return a whole (integer) number with no decimal places after it.

Just to make sure you understand, here is another example:

int myVariable = 22%5;


The above line will set myVariable to 2. This could also be done in your head by subtracting 5 from 22 each time until the remaining number is less than 5. So, subtract 5 from 22 leaves 17, subtract 5 from 17 leaves 12, subtract another 5 leaves 7, and subtracting another 5 will leave you with 2. Since subtracting 5 from 2 will produce a negative number, you cannot go any further and must stop at 2 which leaves you with your modulus answer. That is basically how modulus( % in hackscript) works.

[edit] Program Flow

There are two main ways to direct the logical flow of a program you are creating: conditional statements (aka "if" statements) and loops.

[edit] If Statements

Using an if statement allows you to execute code if a statement evaluates to true, using else allows you to specify code that runs otherwise:

if(5>6){
  message(getSourceIP(),"This should never happen!");
}else{
  message(getSourceIP(),"This should always happen.");
}


You can also use 'else if' to extend your normal if statements so that they can have more than 2 outcomes:

if(5>6){
  message(getSourceIP(),"This should never happen!");
}else if(getSourceIP() == "123.456.7.890"){
  message(getSourceIP(),"This should only happen if getSourceIP() returns 123.456.7.890");
}else{
  message(getsourceIP(),"This should happen if getSourceIP() is not equal to 123.456.7.890 and 5 is not greater 6");
}


[edit] While Loops

Using a while statement allows you to specify a block of code (everything between the curly braces) that will always execute until a condition evaluates to false:

int i=0;
while(i<3){
  message(getSourceIP(),printf("T Minus %s",(3-i)));
  i=i+1;
}
message(getSourceIP(),"Liftoff!");


[edit] For Loops

For loops allow you to specify a block of code that will execute as long as the conditions are true:

int i;
for (i = 0; i < 3; i++) {
  message(getSourceIP(),printf("T Minus %s",(3-i)));
}


First we declared an integer variable i. Then in the for loop, we said "i starts at 0 (i = 0), and as long as i is less than 3 (i < 3), run this code, and after each time the code is run, increment i (i++)."

[edit] Functions

For creating complex programs, such as complicated HTTP programs, one can use functions. Functions are used to store code at one place to call it from other places in your script. Function can be used to organise long code into short and easy to understand sections.

A function consists of the header and a body.

float areaOfSquare(float a) // function header
{
    return a*a; // return the result as the return value of area()
}


This function when called will give the size of the area of a Square with the length a. The function header has the following syntax:

returntype functionname(vartype varname, vartype varname, ...)
  • returntype: the type the return value will be. Possible types are all variables types (int, float, string, boolean) and void. void means that the function will not return any value.
  • functionname: name of the function
  • vartype: the type of the parameter
  • varname: name of the parameter

Parameters are seperated with a comma.

The keyword return will jump back to the place from where the function was called, provide the return value and continue with the script.

int countOccurence(string longString, string shortString)
{
    int count = 0; //counts how often shortString is in longString
    int lastFound = 0; //remembers the position of the last find of shortString in longString
    while( true ) //endless loop
    {
        lastFound = indexOf( longString,shortString,lastFound );
        if (lastFound == -1 ) return count; // done. stop function (and escape the "endless loop" ) and return count
        count++; //if lastFound is not -1 then we found another one so the count is increased by one
        lastFound++; //lastFound is increased to avoid finding the same occurence again - which would result in a real endless loop
    }
}


You can then use these functions in other parts of your code, when you need to do whatever each function does. You use functions all the time when you're programming. There are some really common functions that all Hackscript programmers need, so we have provided them by default and are defined in the different Hackscript APIs (application programmer's interface).

[edit] Global Variables

In all your scripts you can set and maintain global variables, using the functions: setGlobal(int index,variable data), and getGlobal(int index). Where data can be a string, int, float, or boolean. There are twenty globals available to you (0-19).

Here's an example of a poll created with Globals for your Hack Wars website:

First I made a watch script for reseting the variables, I just installed it as a petty-cash watch and fire it when I want to reset the poll:

setGlobal(0,0);
setGlobal(1,0);
setGlobal(2,0);
setGlobal(3,0);
message("192.168.2.002","Poll Reset: "+getGlobal(0)+" "+getGlobal(1)+" "+getGlobal(2)+" "+getGlobal(3));


Next there is the actual HTTP script I made for allowing players to vote using my global variables, this is placed in the 'submit' event.:

string a=getParameter("a");
if(equal(a,"0")){
	int i=getGlobal(0);
	i=i+1;
	setGlobal(0,i);
}else if(equal(a,"1")){
	int i=getGlobal(1);
	i=i+1;
	setGlobal(1,i);
}else if(equal(a,"2")){
	int i=getGlobal(2);
	i=i+1;
	setGlobal(2,i);
}else if(equal(a,"3")){
	int i=getGlobal(3);
	i=i+1;
	setGlobal(3,i);
}
 
float a=getGlobal(0)*1.0;
float b=getGlobal(1)*1.0;
float c=getGlobal(2)*1.0;
float d=getGlobal(3)*1.0;
float total=a+b+c+d;
string message="<h1>Results</h1><p>Who is the sexiest developer of Hack Wars?</p>";
message=message+"Johnny Heart: "+(a/total*100.0)+"%<br />";
message=message+"Sixteen Faces: "+(b/total*100.0)+"%<br />";
message=message+"Mecha Cephalon: "+(c/total*100.0)+"%<br />";
message=message+"Geckotoss: "+(d/total*100.0)+"%<br />";
popUp(message);


And, finally, we have the actual HTML I throw up on my page on Hack Wars. These together give my site a working poll:

<form>
<p> Who is the sexiest developer of Hack Wars? </p> 
<input type="radio" name="a" value="0" />Johnny Heart<br/>
<input type="radio" name="a" value="1" />Sixteen Faces<br/>
<input type="radio" name="a" value="2" />Mecha Cephalon<br/>
<input type="radio" name="a" value="3" />Geckotoss<br/>
<input type="submit" value="Vote" />
</form>

[edit] Arrays

An array is variable that is capable of storing several values seperately, while using the same variable name. Arrays can also be thought of as tables where each record or position in the array holds data or some form of information.

Declaring an array variable is done almost the same way as normal hackscript variables, except that you must have [] after the variable name. Here is an example of declaring a string array:

string myvariable[];


To read/write to that array you need to tell it what position/record to use. This is done by using [arrayposition] after the variable name of a array. Here is an example of declaring, writing/reading with an array then messeging you the results:

string myvariable[];
 
 myvariable[1] = "Hello";
 myvariable[2] = "World!";
 myvariable[3] = "You just used an array!";
 
 message("YOUR IP HERE",myvariable[1]+" "+myvariable[2]+" "+myvariable[3]);


You may notice the array above only stored strings. Arrays can only store one type of data. You cannot store a mixture of different data types in one array. If you need an array for numbers you can declare an array with int instead of string. Same goes for any other datatype.

[edit] Syntax Errors

Syntax errors occur when the compiler doesn't understand your script. It means that you made a mistake when you were coding, and did something that Hackscript doesn't understand. There are common problems that cause syntax errors:

  • you forgot to add a ; when declaring variables
  • you forgot to add a ; when calling a function
  • you forgot to add a ; when doing things other than logic, starting a code block ({ ... }), or commenting.
  • you have missed a bracket somewhere (either a (, ), { or })
  • you have incorrectly declared a variable (for example,
    float hi = "Hello";
    will not work - you declared a float and then assigned a string to it)
  • you forgot to put a string in quotes (string x = "hello";)
  • you forgot to put a decimal value when declaring a float, even if it's a 0 (float x = 10.0;)
  • you forgot to declare a variable type before you use it (ie/ you haven't declared i but say i=0;)
  • you used = instead of == as a comparator (ie/ you wrote if(a=1) )
Personal tools