Suggestions about XS Scripting

I’d just like to make a few suggestions that I think are important! What’s missing are event listeners, especially in technologies for track status progress. Furthermore, working with arrays could be a bit simpler, similar to the JavaScript programming language. Function names are just examples. I’m not very good at english.

Suggestion about event listeners:

int xsEvent(string eventName, void function, bool once); // once is optional parameter
bool xsRemoveEvent(int eventId);

suggested events: technologyinprogress = in progress, technologyresearched = research completed, technologyqueued = in queue/pending, technologyresearchstopped, playerdefeated, playerresigned

Example for tech listener:

// Create listener. retuns a unique id
int aEvent = xsEvent("technologyresearch", (int playerId, int technologyId) {

});

// Or
void MyCustomFunction(int playerId, int technologyId) {

};

int aEvent = xsEvent("technologyresearch", MyCustomFunction);

// Remove event
bool isAEventRemoved = xsRemoveEvent(aEvent);

or just all-in one for technologies:

void MyCustomFunction(int playerId, int technologyId, string technologyState) {

};

int aEvent = xsEvent("technologystate", MyCustomFunction);

Extra: If you want to disable civilization bonuses or create a custom technology tree /bonuses before starting the game. Currently, bonuses are activated before main function runs.

void MyCustomFunction() {

for(i = 0; < xsGetNumPlayers()) {
int getCivId = xsGetPlayerCivilization(i);
  if(getCivId == cBulgarians) {
     xsEnableTech(i, 45, true); // Enable faith
     xsResearchTech(i, 505, true); // Research Recurve Bow. No matter is civ specific tech or not when "force" parameter are true

  }
}



};

int aEvent = xsEvent("ready", MyCustomFunction, true); // or beforeready / beforestart etc... run once

Simplified array creation, and objects

I don’t really need to go into too much detail. The example explains it:

array randomItems = [10024, 1020, 301401, 502402, {"hey" : "hooo"}, 815135, "string", 1.222, true];
array scores = [2,3232,42424,25525];

array players = [
  ["Hun player", "Barbar"],
  ["Byzantine Player", "Defensive"]
];

object aObj = {
 "name" : "Blah",
 "age" : 10,
 "aura" : 1.5
};

array aTable = [{
 "name" : "Hera",
 "civilization" : "Byzantines",
 "civId" : 7,
 "isAlive" : true
}, {
 "name" : "Red Phosphorus",
 "civilization" : "Goths",
 "civId" : 3,
 "isAlive" : true
}];

xsChatData(aObj.name); // prints Blah

object getHera = aTable[0];
string getBlahName = aObj.name;

// print scores
for(i = 0; <= xsTotalArrayItems(scores)) { // or xsTotal(array arr) / xsCount(array arr)
 xsChatData(scores[i]);
}

As well we need a basic array functions, like: filter, sort, find, push, pop, split, includes, copy etc…

Perhaps Map and Set-like functions:

Set - JavaScript | MDN … and … Map() constructor - JavaScript | MDN

Additional Suggested Functions / Simplified existing features … or maybe it would be possible to add them into a single function (extending xsEffect function) …although it may be less “user friendly”

For techs and units

array[object] xsGetTechResources(int techId); // or xsGetUnitResources

bool xsSetTechResourceCost(int techId, int resourceIndex, int resourceId, int value); // Or xsSetUnitResourceCost

bool xsRemoveTechResourceCost(int techId, int resourceIndex); // or xsRemoveUnitResourceCost

int xsGetTechResourceStoreMode(int techId, int resourceIndex);// or xsGetUnitResourceStoreMode

bool xsSetTechResourceStoreMode(int techId, int resourceIndex, int storeMode); // or xsSetUnitResourceStoreMode




// Only for techs
bool xsEnableTech(int playerId, int techId, bool enableOrDisable);
bool xsResearchTech(int playerId, int techId, bool force);
string xsGetTechState(int playerId, int techId);
array[object] xsGetTechRequiredTechs(int techId);
int xsGetTechRequiredTech(int techId, int index);
bool xsRemoveTechRequiredTech(int techId, int index);
bool xsSetTechRequiredTech(int techId, int index, int requiredTechId);
int xsGetTechMinimumReqTechsCount(int techId);
bool xsSetTechMinimumReqTechsCount(int techId, int value);
int xsGetTechRepeatableCount(id techId);
bool xsSetTechRepeatableCount(id techId, int value);
int xsGetTechIcon(id techId);
bool xsSetTechIcon(id techId, int value);

// Exclusive techs
int xsCreateExclusiveTechBucket(string type, array[techIds], object options = {"instant" : false, "startingTech" : -1, "enabled" : false});
bool xsRemoveExclusiveTechBucket(int exclusiveBucketId);
bool xsRemoveExclusiveTech(int exclusiveBucketId, int index);
bool xsAddExclusiveTech(int exclusiveBucketId, int techId, int index); // Index is optional
bool xsSetExclusiveTechBucketType(string type);
string xsGetExclusiveTechBucketType(int exclusiveBucketId);
bool xsSetInstant(int exclusiveBucketId, bool instant);
bool xsSetStartingTechId(int exclusiveBucketId, int techId);
bool xsIsInstant(int exclusiveBucketId);
int xsGetActiveTech(int exclusiveBucketId);
bool xsSetActiveTech(int exclusiveBucketId, id techId); // false if the specified tech already active
bool xsSetExclusiveTechBucketState(bool enable);
int xsGetStartingTechId(int exclusiveBucketId);
array[object {"id" : int, "startingTech" : bool, "active" : bool}] xsGetExclusiveTechs(int exclusiveBucketId);

Examples:

array castleAgeCosts = xsGetTechResources(102);
bool isRemovedCost = xsRemoveTechResourceCost(102, 2); // removes 2nd resource

result for xsGetTechResources:

[
 {"type" : 0, "value" : 800, "storeMode" : 1}, // 0 = food
 {"type" : 1, "value" : 200, "storeMode" : 1} // 1 = gold
]

Example for making exclusive techs:

// Create an exclusive tech bucket
int bucket = xsCreateExclusiveTechBucket("Cycle", [1281, 1282, 1283], {"instant" : true, "startingTech" : 1281, "enabled" : true});

bool added = xsAddExclusiveTech(bucket, 1284); // Index is optional, so it places  at the end of the array, as the last element

xsChatData(xsGetExclusiveTechBucketType(bucket)) // Prints Cycle

bool isRemoved = xsRemoveExclusiveTech(bucket, 1282); // false if technology is starting tech. if removed, this tech are deactivated and next technology are activated (1283)


bool byebyeBucket = xsRemoveExclusiveTechBucket(bucket); // Removed and deactivated

Player/civilization related functions:

array[int] xsGetAllDisabledTechIds(int playerId);
array[int] xsGetAllEnabledTechIds(int playerId);
array[int] xsGetAllCivilizationSpecificTechIds(int civilizationId); // team Bonuses, unique unit upgrades, civ specific techs...
bool xsRevertTech(int playerId, int technologyId); // This is useful if you want to remove the civilization bonus later, returns true if success
bool xsApplyTech(int playerId, int technologyId); // This is useful if you want to apply or reactivate civilization bonus or civilization specific tech. Perhaps this could be resolved using the “xsEnableTech”

At least i couldn’t figure out how to disable the civilization bonus in the xs script before it was applied. If anyone knows the secret, please tell me but without full tech mode! It’s midnight here right now, so im going to sleep. If anything else comes to mind—for me or for you—don’t keep it to yourself!

Edit: + Maybe we need a module based system! (import/export)

1 Like

Developers and who work with xs scripts will (most likely) understand this.

Suggestion about collections!

It would work similarly to the Map object in JavaScript. Key must be unique and case sensitive

int xsCreateCollection();

bool xsCollectionHasItem(int collection, string key); // Check, if item is exists.

bool xsCollectionAddItem(int collection, string key, any value); // Add item, return true if success

void xsCollectionRemoveItem(int collection, string key); // Remove item by key.

any xsCollectionGetItem(int collection, string key); // Get value of item, fail if item does not exists

int xsCollectionGetSize(int collection); // Get collection size

void xsCollectionClear(int collection);

Example:

int collection = xsCreateCollection(); // This an empty collection

// We need add some items. Returns true if success

xsCollectionAddItem(collection, "Total Players", 3);
xsCollectionAddItem(collection,"Player 1", xsCreateCollection());
xsCollectionAddItem(collection,"Player 2", xsCreateCollection());
xsCollectionAddItem(collection,"Player 3", xsCreateCollection());

// We need add some techs to Player 1
int getPlayer1 = xsCollectionGetItem(collection,"Player 1");
xsCollectionAddItem(getPlayer1, "Faith", 45);
xsCollectionAddItem(getPlayer1, "Block Printing", 230);
xsCollectionAddItem(getPlayer1, "Sample tech 1", 200);
xsCollectionAddItem(getPlayer1, "Sample tech 2", 202);

if(xsCollectionHasItem(getPlayer1, "Faith")) {
    xsChatData("Player 1 has Faith");
}

xsChatData("Total available techs: " + xsCollectionGetSize(getPlayer1)); // prints 4

xsCollectionRemoveItem(getPlayer1, "Block Printing");
xsChatData("Total available techs: " + xsCollectionGetSize(getPlayer1)); // prints 3 because "Block Printing" is removed!


if(xsCollectionHasItem(getPlayer1, "Block Printing")) {
  // Does not execute, because "Block Printing" is removed from collection
  xsChatData("I have Block Printing");
}

// Get items from players with "for", then check, player x has Faith technology
for(i = 1; i <= xsCollectionGetSize(collection)) {
   if(xsCollectionHasItem(collection, "Player" + i)) {
      int getCurrentPlayer = xsCollectionGetItem(collection, "Player" + i);
      if(xsCollectionHasItem(getCurrentPlayer, "Faith")) {
           xsChatData("Player " + i + " has Faith"); // Prints if selected player has Faith
      }
   }
}

1 Like

These seem like good suggestions to me!

Event listeners would be useful for technologies, and the ability to toggle technologies before the effects are activated. Furthermore, collections are much simpler and easier to understand than working with array.

What else would be needed are additional features for editing technologies: ad/remove required techs, set required tech count, better resource manipulation, civilization specific techs…

1 Like

Javscript arrays are a mess.
Javascript is a mess, I hate undeclared abstract coding, but it’s a personnal bias.

Many of your suggestion exists are trigger, so just let time do the job and they will make some XS equivalent, which is how they tend to do. First a dataset version, and later trigger, and finally xs if xs isn’t added in the same time as the trigger.

for RMS it’s possible to affect the game before the main() is loaded. For example there is a RMS script where one of the gaia church from the desert turns into a Wololo tournament building, with some redbull wololo flags.
Such scripts are loaded before triggers, and before team bonuses so you should try to see on the Random-Map-Script part of the XS possibilities.

Arrays are easy to create, and instead of objects just make multiple arrays for each column of your object instead. I recommand you check this documentation: xsArrays community made documentation

I don’t get the point of exclusive techs, except if you’re thinking of the chronicle style double Unique Techs. You can artificially make them via techs that disable other techs without need of a special XS addition.

All xs files are loaded by the game, so you don’t have to import any file, if that’s what you’re thinking about.

The problem with arrays is that you can only assign string, integer, float, and boolean values to them. It is not possible to create an array that can contain values of array, it does not exists yet.

If they were to introduce a Map-like feature, tt would be easier to store, delete, and add different values, store technology states. It would also be helpful to have to less use the Scenario Trigger features as possible,we shouldn’t have to manually create conditions for each players. If I want to create a campaign about a civilization that doesn’t exist in the game, i can use triggers or the “rule” function to check the status of technologies in real time per player. In the former case, the triggers list will be very long, in the latter case, it will become less pretty. If the following functions were exists, it would look a bit better, prettier:

int store = xsCollectionCreate();

void aEventListener(int playerId, int techId) {
  if(xsGetPlayerCivilization(playerId) == cHuns) {
  int getPlayerTechs = xsCollectionGetItem(store, "Player " + playerId);
    if(xsCollectionHasItem(getPlayerTechs, "Castle UT") && xsCollectionGetItem(getPlayerTechs, "Castle UT") == techId) {
      // Execute if exists, apply effect: Faith costs -50%
       xsEffectAmount(cModifyTech, 45, cAttrMulAllCosts, 0.5, playerId);
    }
  }

}

void main() {
  // SetUp players
  for(i = 1; < xsGetNumPlayers()) {
    string itemId = "Player "+i;
    xsCollectionAddItem(store, itemId, xsCollectionCreate());
    int getStorage = xsCollectionGetItem(store, itemId);
    xsCollectionAddItem(getStorage, "Castle UT", 1340); // I know, this is a Custom Castle Age Tech. This is a placeholder tech ID
    xsCollectionAddItem(getStorage, "Imperial UT", 1341); // I know, this is a Custom Imperial Age Tech This is a placeholder tech ID
  }

  int listener = xsEvent("technologyresearched", aEventListener);
}

You do not need to use trigger effects per player, you do not need to use rule syntax, it looks a bit prettier.

I don’t get the point of exclusive techs, except if you’re thinking of the chronicle style double Unique Techs. You can artificially make them via techs that disable other techs without need of a special XS addition.

I’m thinking of a custom feature that would work like “linkedTechs.json”. It would be much simpler if there were a dedicated function to create it.

I quickly threw a script related to the collections. There’s a technology that, once researched, will give the cavalry more hp! Currently the state of the technology can be checked in real time with rules! Since theres no event listener, we need have to write more code! First, i created a collection for each player to hold the technologies are haven’t researched yet. If a selected player has researched the specified technology, the effect will be activated, and the technology will be removed from the selected player collection to prevent it from being activated again. Collections can only store string values, so numbers and boolean values must be converted before check! Unfortunately, you can’t mix data types within arrays and expect it to work without conversion or more complex operations. Currently “any” type is not exists yet. Keys are case sensitive, so BlankTechnology and blanktechnology are different key!

Here is the “Main.xs” file of a scenario ,just a example:

include "Collections.xs";

int playersDb = 0;
int totalPlayers = 0;

// Check technology state per player
rule uniqTech
    inactive
    highFrequency
    priority 1
{
    for(i = 1; < totalPlayers) {
        int playerDb = xsArrayGetInt(playersDb, i - 1);
        int blankTech1 = strToInt(rsCollectionGet(playerDb, "BlankTech1")); 
        if(blankTech1 != -1 && xsGetTechState(blankTech1, i) == cTechStateDone) {
            xsEffectAmount(cMulAttribute, cCavalryClass, cHitpoints, 2.5, i);
            rsCollectionDelete(playerDb, "BlankTech1");
        }
    }
}

void main() {
    totalPlayers = xsGetNumPlayers();
    playersDb = xsArrayCreateInt(totalPlayers);

    for(i = 0; < xsArrayGetSize(playersDb)) {
        int collection = rsCollectionCreate();
        rsCollectionSet(collection, "BlankTech1", "1181");
        rsCollectionSet(collection, "BlankTech2", "1182");
        rsCollectionSet(collection, "BlankTech3", "1183");

        xsArraySetInt(playersDb, i, collection);
    }

    xsEnableRule("uniqTech");
}

And here is the Collection.xs file: I use “rs” prefix instead of “xs” to avoid future name conflicts.

int rsCollectionCreate() {
    int databases = xsArrayCreateInt(0);
    return (databases);
}

int rsCollectionGetSize(int collection = 0) {
    return(xsArrayGetSize(collection) / 2);
}

void rsCollectionClear(int collection = 0) {
    xsArrayResizeInt(collection, 0);
}

string rsCollectionGet(int collection = 0, string key = "") {
    string returnValue = "";
    int size = xsArrayGetSize(collection);
    key = strTrim(key);
    if(key == "" || size < 2)
        return (returnValue);

    for(i = 0; < size) {
        if((i % 2) == 1) {
            int getKey = xsArrayGetInt(collection, (i - 1));
            string getKeyName = xsArrayGetString(getKey, 0);
            if(getKeyName == key) {
                int getValue = xsArrayGetInt(collection, i);
                returnValue = xsArrayGetString(getValue, 0);
                break;
            }
        }
    }
    return (returnValue);
}

bool rsCollectionHas(int collection = 0, string key = "") {
    return (rsCollectionGet(collection, key) != "");
}

int rsCollectionDelete(int collection = 0, string key = "") {
    int size = xsArrayGetSize(collection);
    key = strTrim(key);
    if(key == "" || rsCollectionHas(collection, key) == false || size < 2)
        return (collection);

    int newCollection = xsArrayCreateInt(0);
    int total = 2;
    for(i = 0; < size) {
        if((i % 2) == 1) {
            int getKey = xsArrayGetInt(collection, (i - 1));
            string getKeyName = xsArrayGetString(getKey, 0);
            if(getKeyName != key) {
                int minusSize = total - 1;
                xsArrayResizeInt(newCollection, total);
                int getValue = xsArrayGetInt(collection, i);
                string getValueString = xsArrayGetString(getValue, 0);

                int setKey = xsArrayCreateString(1); xsArraySetString(setKey, 0, getKeyName);
                int setVal = xsArrayCreateString(1); xsArraySetString(setVal, 0, getValueString);
                xsArraySetInt(newCollection, minusSize - 1, setKey);
                xsArraySetInt(newCollection, minusSize, setVal);
                total = total + 2;
            }
        }  
    }

    xsArrayResizeInt(collection, 0);
    for(r = 0; < xsArrayGetSize(newCollection)) {
        if((r % 2) == 1) {
            // Get data
            int getNewKey = xsArrayGetInt(newCollection, (r - 1));
            int getNewValue = xsArrayGetInt(newCollection, r);
            xsArrayResizeInt(collection, xsArrayGetSize(collection) + 2);
            xsArraySetInt(collection, r - 1, getNewKey);
            xsArraySetInt(collection, r, getNewValue);
        }
    }
    return(collection);
}

int rsCollectionSet(int collection = 0, string key = "", string value = "") {
    key = strTrim(key);
    if(key == "")
        return (collection);


    rsCollectionDelete(collection, key);

    int size = xsArrayGetSize(collection);
    int plusSize = size + 2;
    xsArrayResizeInt(collection, plusSize);

    int setKey = xsArrayCreateString(1); xsArraySetString(setKey, 0, key);
    int setVal = xsArrayCreateString(1); xsArraySetString(setVal, 0, value);

    xsArraySetInt(collection, plusSize - 2, setKey);
    xsArraySetInt(collection, plusSize - 1, setVal);
    return (collection);
}

int rsCollectionGetAllKeys(int collection = 0) {
    int strArr = xsArrayCreateString(0);
    int size = xsArrayGetSize(collection);
    int current = 1;
    for(i = 0; < size) {
        if((i % 2) == 0) {
            int getItem = xsArrayGetInt(collection, i);
            string getText = xsArrayGetString(getItem, 0);
            xsArrayResizeString(strArr, current);
            xsArraySetString(strArr, current - 1, getText);
            current++;
        }

    }
    return(strArr);
}

int rsCollectionGetAllValues(int collection = 0) {
    int strArr = xsArrayCreateString(0);
    int size = xsArrayGetSize(collection);
    int current = 1;
    for(i = 0; < size) {
        if((i % 2) == 1) {
            int getItem = xsArrayGetInt(collection, i);
            string getText = xsArrayGetString(getItem, 0);
            xsArrayResizeString(strArr, current);
            xsArraySetString(strArr, current - 1, getText);
            current++;
        }

    }
    return(strArr);
}

string rsCollectionGetKey(int collection = -1, int index = 0) {
    int keys = rsCollectionGetAllKeys(collection);
    return(xsArrayGetString(keys, index));
}

string rsCollectionGetValue(int collection = -1, int index = 0) {
    int keys = rsCollectionGetAllValues(collection);
    return(xsArrayGetString(keys, index));
}

I also uploaded it to GitHub

Usage in for loops

int collection = rsCollectionCreate();
    rsCollectionSet(collection, "Huns", "Barbars");
    rsCollectionSet(collection, "Vandals", "Barbars");
    rsCollectionSet(collection, "Suebians", "Barbars");

for(i = 0; < rsCollectionGetSize(collection)) {
    string key = rsCollectionGetKey(collection, i);
    string val = rsCollectionGetValue(collection, i);

    if(key == "Vandals") {
        xsChatData("The " + key + " are " + val); // Prints "The Vandals are Barbars"
    }
}

Array of arrays is a database, so yes that’s not the point of XS usage.

So I’d say if you want to use arrays of arrays then maybe you’re not using the right tool, as in maybe you need another game / environment to reach your goals. (it’s not a negative critic, it’s an encouragement for you to go beyond the limitations, go bigger, reach the moon, don’t limit yourself to the tree in the garden)

Hm, I see why you wand that, you can do some ersatz using rules infact. Rule as a looping process and then just apply your filters.

I still don’t get the point, I mean you’re talking about eventListener, for a runtime content, what you look for is a pre-runtime thing. Actually you’re looking for an API, which the XS isn’t really, it’s closer to minecraft commandblock rather than plugin/mods thing that could have listener changing the behavior of the entire runtime.

I mean I understand the point as a programmer, definitly, but as an Age of Empires 2 designer, there is no use for what you want. You’re definitly looking at a “modkit” level content if you see what I mean, which the games currently doesn’t provide.

Still, your vision of the concept is pretty cool, there is a lot of potential in your ideas, you’re writing your code in a pretty solid way, easy to read and undestand in term of code, so definitly push your ideas forward and go big.

Hm, I think I get it, it’s like you’d like to be able to have built-in tools to extend the possibilites further. Then why not trying to make some xs libs ? It seems you can try with some files includes in your scripts, so maybe you can like do that yourself ? There is even IO support with read and write, so maybe you can yourself build an entire lib package for arrays of arrays etc, with json and other stuff ? I mean bro, you got the ideas, you got the knowledge, what’s stopping you of trying ? I’m pretty sure that your ideas can be helpful for some designers, you just need to make them easy enought for anyone to use them ^^

Like for example I had an issue couple days agos about not beeing able to renameObjects in XS, like giving custom names in text to objects as we can do ingame with triggers via the name field on attribute modify. But I saw it was possible to change unitName. Unit is basically an object spawned with an unique ID, so I grab every second all units of my toRename objects, for each player, check if curName is similar to the custom name, if no, change it, if yes, skip.

However then here the “string.equals” doesn’t exist in xs, but the “string.contains” exist, so I just did an ersatz of equals using contains as my objects never contains the custom string content. That’s my point about your ideas here, if it doesn’t exist, either ignores it or make your own, don’t stop at “it doesn’t exist so I can’t do it”, push it further.

I’m no expert yet of xs IO system but I know it’s usable, so just get your hands dirty, play with it, try, fail, retry, refail, but never give up until you get something you want.

There is an entire discord server dedicated to the XS scripting thing, I’m not on it but someone told me it exist. @StepS7578 can provide you the link so you can share your ideas with others and reach crazy result all together.

And honnestly, there is potential in your ideas, don’t wait for anyone to make them for you, do them, you got the knowledge.