Ticket #4326: t4323_random_merge+pickRandom.diff

File t4323_random_merge+pickRandom.diff, 18.3 KB (added by bb, 7 years ago)

Rabse form #3102, I would be glad to split the nuked function from the pickRandom(), but as the calls to pickRandom are mainly old calls to GetRandom and that last function got nuked, it seems better to merge it. So we don't change lines twice and the patch isn't *that* big. Also didn't add a messy "-1" in UnitAI because adding 1 ms to the random feed/walk time doesn't seem to matter.

  • binaries/data/mods/public/globalscripts/random.js

     
     1/*
     2 * Return a random floating point number using Math.random library
     3 *
     4 * If no parameter given, the returned float is in the interval [0, 1)
     5 * If one parameter given, it's maxval, and the returned float is in the interval [0, maxval)
     6 * If two parameters are given, they are minval and maxval, and the returned float is in the interval [minval, maxval)
     7 */
     8function randFloat()
     9{
     10    if (!arguments.length)
     11        return Math.random();
     12    else if (arguments.length == 1)
     13        return randFloat() * arguments[0];
     14    else if (arguments.length == 2)
     15        return arguments[0] + randFloat() * (arguments[1] - arguments[0]);
     16    else
     17    {
     18        error("randFloat: invalid number of arguments: "+arguments.length);
     19        return undefined;
     20    }
     21}
     22
     23/*
     24 * Return a random integer using Math.random library
     25 *
     26 * If no parameter given, the returned integer is in the interval [0 .. 1]
     27 * If one parameter given, it's maxval, and the returned integer is in the interval [0 .. maxval-1]
     28 * If two parameters are given, they are minval and maxval, and the returned integer is in the interval [minval .. maxval]
     29 */
     30function randInt()
     31{
     32    if (!arguments.length)
     33        return Math.round(randFloat());
     34    else if (arguments.length == 1)
     35        return Math.floor(randFloat(arguments[0]));
     36    else if (arguments.length == 2)
     37        return Math.floor(randFloat(arguments[0], arguments[1] + 1));
     38    else
     39    {
     40        error("randInt: invalid number of arguments: "+arguments.length);
     41        return undefined;
     42    }
     43}
  • binaries/data/mods/public/globalscripts/utility.js

     
    2828    let result = [source[0]];
    2929    for (let i = 1; i < source.length; ++i)
    3030    {
    31         let j = Math.floor(Math.random() * (i+1));
     31        let j = randInt(i+1);
    3232        result[i] = result[j];
    3333        result[j] = source[i];
    3434    }
    3535    return result;
    3636}
     37
     38function pickRandom(source)
     39{
     40    return source.length ? source[randInt(source.length)] : undefined;
     41}
  • binaries/data/mods/public/gui/common/functions_utility.js

     
    33 */
    44var g_LastNickNotification = -1;
    55
    6 function getRandom(randomMin, randomMax)
    7 {
    8     // Returns a random whole number in a min..max range.
    9     // NOTE: There should probably be an engine function for this,
    10     // since we'd need to keep track of random seeds for replays.
    11 
    12     var randomNum = randomMin + (randomMax-randomMin)*Math.random();  // num is random, from A to B
    13     return Math.round(randomNum);
    14 }
    15 
    166// Get list of XML files in pathname with recursion, excepting those starting with _
    177function getXMLFileList(pathname)
    188{
  • binaries/data/mods/public/gui/common/music.js

     
    132132
    133133Music.prototype.getRandomTrack = function(tracks)
    134134{
    135     return tracks[getRandom(0, tracks.length-1)];
     135    return pickRandom(tracks);
    136136};
    137137
    138138Music.prototype.startPlayList = function(tracks, fadeInPeriod, isLooping)
  • binaries/data/mods/public/gui/gamesetup/gamesetup.js

     
    12571257    {
    12581258        let victoryScriptsSelected = g_GameAttributes.settings.VictoryScripts;
    12591259        let gameTypeSelected = g_GameAttributes.settings.GameType;
    1260         selectMap(Engine.GetGUIObjectByName("mapSelection").list_data[Math.floor(Math.random() *
    1261             (Engine.GetGUIObjectByName("mapSelection").list.length - 1)) + 1]);
     1260        selectMap(pickRandom(Engine.GetGUIObjectByName("mapSelection").list_data));
    12621261        g_GameAttributes.settings.VictoryScripts = victoryScriptsSelected;
    12631262        g_GameAttributes.settings.GameType = gameTypeSelected;
    12641263    }
     
    12811280        let chosenCiv = g_GameAttributes.settings.PlayerData[i].Civ || "random";
    12821281        if (chosenCiv == "random")
    12831282        {
    1284             let culture = cultures[Math.floor(Math.random() * cultures.length)];
     1283            let culture = pickRandom(cultures);
    12851284            let civs = Object.keys(g_CivData).filter(civ => g_CivData[civ].Culture == culture);
    1286             chosenCiv = civs[Math.floor(Math.random() * civs.length)];
     1285            chosenCiv = pickRandom(civs);
    12871286        }
    12881287        g_GameAttributes.settings.PlayerData[i].Civ = chosenCiv;
    12891288
     
    12911290        if (g_GameAttributes.mapType === "scenario" || !g_GameAttributes.settings.PlayerData[i].AI)
    12921291            continue;
    12931292
    1294         let chosenName = g_CivData[chosenCiv].AINames[Math.floor(Math.random() * g_CivData[chosenCiv].AINames.length)];
     1293        let chosenName = pickRandom(g_CivData[chosenCiv].AINames);
    12951294
    12961295        if (!g_IsNetworked)
    12971296            chosenName = translate(chosenName);
  • binaries/data/mods/public/gui/loading/loading.js

     
    1414    if (tipTextLoadingArray.length > 0)
    1515    {
    1616        // Set tip text
    17         let tipTextFilePath = tipTextLoadingArray[getRandom(0, tipTextLoadingArray.length-1)];
     17        let tipTextFilePath = pickRandom(tipTextLoadingArray);
    1818        let tipText = Engine.TranslateLines(Engine.ReadFile(tipTextFilePath));
    1919
    2020        if (tipText)
     
    6363
    6464    // Pick a random quote of the day (each line is a separate tip).
    6565    let quoteArray = Engine.ReadFileLines("gui/text/quotes.txt");
    66     Engine.GetGUIObjectByName("quoteText").caption = translate(quoteArray[getRandom(0, quoteArray.length-1)]);
     66    Engine.GetGUIObjectByName("quoteText").caption = translate(pickRandom(quoteArray));
    6767}
    6868
    6969function displayProgress()
  • binaries/data/mods/public/maps/random/flood.js

     
    432432    planetm * scaleByMapSize(13, 200)
    433433);
    434434
    435 setSkySet(shuffleArray(["cloudless", "cumulus", "overcast"])[0]);
     435setSkySet(pickRandom(["cloudless", "cumulus", "overcast"]));
    436436setWaterMurkiness(0.4);
    437437
    438438ExportMap();
  • binaries/data/mods/public/maps/random/island_stronghold.js

     
    564564paintTerrainBasedOnHeight(1, 2, 0, tShore);
    565565paintTerrainBasedOnHeight(getMapBaseHeight(), 1, 3, tWater);
    566566
    567 setSkySet(shuffleArray(["cloudless", "cumulus", "overcast"])[0]);
     567setSkySet(pickRandom(["cloudless", "cumulus", "overcast"]));
    568568
    569569setSunRotation(randFloat(0, TWO_PI));
    570570setSunElevation(randFloat(PI/5, PI/3));
  • binaries/data/mods/public/maps/random/rmgen/random.js

     
    1 // TODO: rename/change these functions, so the bounds are more clear
    2 
    3 /*
    4  * Return a random floating point number using Math.random library
    5  *
    6  * If no parameter given, the returned float is in the interval [0, 1)
    7  * If two parameters are given, they are minval and maxval, and the returned float is in the interval [minval, maxval)
    8  */
    9 function randFloat()
    10 {
    11     if (arguments.length == 0)
    12     {
    13         return Math.random();
    14     }
    15     else if (arguments.length == 2)
    16     {
    17         var minVal = arguments[0];
    18         var maxVal = arguments[1];
    19 
    20         return minVal + randFloat() * (maxVal - minVal);
    21     }
    22     else
    23     {
    24         error("randFloat: invalid number of arguments: "+arguments.length);
    25         return undefined;
    26     }
    27 }
    28 
    29 /*
    30  * Return a random integer using Math.random library
    31  *
    32  * If one parameter given, it's maxval, and the returned integer is in the interval [0, maxval)
    33  * If two parameters are given, they are minval and maxval, and the returned integer is in the interval [minval, maxval]
    34  */
    35 function randInt()
    36 {
    37     if (arguments.length == 1)
    38     {
    39         var maxVal = arguments[0];
    40         return Math.floor(Math.random() * maxVal);
    41     }
    42     else if (arguments.length == 2)
    43     {
    44         var minVal = arguments[0];
    45         var maxVal = arguments[1];
    46 
    47         return minVal + randInt(maxVal - minVal + 1);
    48     }
    49     else
    50     {
    51         error("randInt: invalid number of arguments: "+arguments.length);
    52         return undefined;
    53     }
    54 }
  • binaries/data/mods/public/simulation/ai/common-api/utils.js

    Property changes on: binaries/data/mods/public/maps/random/rmgen/random.js
    ___________________________________________________________________
    Deleted: svn:eol-style
    ## -1 +0,0 ##
    -native
    \ No newline at end of property
     
    5454    return endArray;
    5555};
    5656
    57 /** Picks a random element from an array */
    58 m.PickRandom = function(list)
    59 {
    60     return list.length ? list[Math.floor(Math.random()*list.length)] : undefined;
    61 };
    62 
    63 
    6457/** Utility functions for conversions of maps of different sizes */
    6558
    6659/**
  • binaries/data/mods/public/simulation/ai/petra/chatHelper.js

     
    33
    44m.chatLaunchAttack = function(gameState, player, type)
    55{
    6     let message;
    7     let proba = Math.random();
    8     if (type === "HugeAttack" && proba > 0.25 && proba < 0.75)
    9         message = markForTranslation("I am starting a massive military campaign against %(_player_)s, come and join me.");
    10     else if (proba < 0.5)
    11         message = markForTranslation("I am launching an attack against %(_player_)s.");
    12     else
    13         message = markForTranslation("I have just sent an army against %(_player_)s.");
    14 
    156    Engine.PostCommand(PlayerID, {
    167        "type": "aichat",
    17         "message": "/allies "+ message,
     8        "message": "/allies " + (type === "HugeAttack" && Math.random() < 0.5 ?
     9            markForTranslation("I am starting a massive military campaign against %(_player_)s, come and join me.") :
     10            pickRandom([
     11                markForTranslation("I am launching an attack against %(_player_)s."),
     12                markForTranslation("I have just sent an army against %(_player_)s.")
     13            ])),
    1814        "translateMessage": true,
    1915        "translateParameters": ["_player_"],
    20         "parameters": {"_player_": player}
     16        "parameters": { "_player_": player }
    2117    });
    2218};
    2319
    2420m.chatAnswerRequestAttack = function(gameState, player, answer, other)
    2521{
    26     let message;
    27     if (answer)
    28     {
    29         let proba = Math.random();
    30         if (proba < 0.5)
    31             message = markForTranslation("Let me regroup my army and I am with you against %(_player_)s.");
    32         else
    33             message = markForTranslation("I am doing the final preparation and I will attack %(_player_)s.");
    34     }
    35     else
    36     {
    37         if (other !== undefined)
    38             message = markForTranslation("I cannot help you against %(_player_)s for the time being, as I have another attack foreseen against %(_player_2)s.");
    39         else
    40             message =  markForTranslation("Sorry, I do not have enough soldiers currently, but my next attack will target %(_player_)s.");
    41     }
    42 
    43     let chat = {
     22    Engine.PostCommand(PlayerID, {
    4423        "type": "aichat",
    45         "message": "/allies " + message,
     24        "message": "/allies " + (answer ?
     25            pickRandom([
     26                markForTranslation("Let me regroup my army and I am with you against %(_player_)s."),
     27                markForTranslation("I am doing the final preparation and I will attack %(_player_)s.")
     28            ]) :
     29            (other ?
     30                markForTranslation("I cannot help you against %(_player_)s for the time being, as I have another attack foreseen against %(_player_2)s.") :
     31                markForTranslation("Sorry, I do not have enough soldiers currently, but my next attack will target %(_player_)s."))),
    4632        "translateMessage": true,
    47         "translateParameters": ["_player_"],
    48         "parameters": {"_player_": player}
    49     };
    50     if (other !== undefined)
    51     {
    52         chat.translateParameters.push("_player_2");
    53         chat.parameters._player_2 = other;
    54     }
    55     Engine.PostCommand(PlayerID, chat);
     33        "translateParameters": other ? ["_player_", "_player_2"] : ["_player_"],
     34        "parameters": other ? { "_player_": player, "_player2_": other } : { "_player_": player }
     35    });
    5636};
    5737
    5838m.chatSentTribute = function(gameState, player)
    5939{
    60     let message;
    61     let proba = Math.random();
    62     if (proba < 0.33)
    63         message = markForTranslation("Here is a gift for %(_player_)s, make a good use of it.");
    64     else if (proba < 0.66)
    65         message = markForTranslation("I see you are in a bad situation %(_player_)s, I hope this will help.");
    66     else
    67         message = markForTranslation("I can help you this time %(_player_)s, but try to assemble more resources in the future.");
    68 
    6940    Engine.PostCommand(PlayerID, {
    7041        "type": "aichat",
    71         "message": "/allies " + message,
     42        "message": "/allies " + pickRandom([
     43            markForTranslation("Here is a gift for %(_player_)s, make a good use of it."),
     44            markForTranslation("I see you are in a bad situation %(_player_)s, I hope this will help."),
     45            markForTranslation("I can help you this time %(_player_)s, but try to assemble more resources in the future.")
     46        ]),
    7247        "translateMessage": true,
    7348        "translateParameters": ["_player_"],
    74         "parameters": {"_player_": player}
     49        "parameters": { "_player_": player }
    7550    });
    7651};
    7752
    7853m.chatRequestTribute = function(gameState, resource)
    7954{
    80     let message;
    81     let proba = Math.random();
    82     if (proba < 0.33)
    83         message = markForTranslation("I am in need of %(resource)s, can you help? I will make it up to you.");
    84     else if (proba < 0.66)
    85         message = markForTranslation("I would participate more efficiently in our common war effort if you could provide me some %(resource)s.");
    86     else
    87         message = markForTranslation("If you have some %(resource)s excess, that would help me strengthen my army.");
    88 
    8955    Engine.PostCommand(PlayerID, {
    9056        "type": "aichat",
    91         "message": "/allies " + message,
     57        "message": "/allies " + pickRandom([
     58            markForTranslation("I am in need of %(resource)s, can you help? I will make it up to you."),
     59            markForTranslation("I would participate more efficiently in our common war effort if you could provide me some %(resource)s."),
     60            markForTranslation("If you have some %(resource)s excess, that would help me strengthen my army.")
     61        ]),
    9262        "translateMessage": true,
    93         "translateParameters": {"resource": "withinSentence"},
    94         "parameters": {"resource": gameState.sharedScript.resourceNames[resource]}
     63        "translateParameters": { "resource": "withinSentence" },
     64        "parameters": { "resource": gameState.sharedScript.resourceNames[resource] }
    9565    });
    9666};
    9767
    9868m.chatNewTradeRoute = function(gameState, player)
    9969{
    100     let message;
    101     let proba = Math.random();
    102     if (proba < 0.5)
    103         message = markForTranslation("I have set up a new route with %(_player_)s. Trading will be profitable for all of us.");
    104     else
    105         message = markForTranslation("A new trade route is set up with %(_player_)s. Take your share of the profits.");
    106 
    10770    Engine.PostCommand(PlayerID, {
    10871        "type": "aichat",
    109         "message": "/allies " + message,
     72        "message": "/allies " + pickRandom([
     73            markForTranslation("I have set up a new route with %(_player_)s. Trading will be profitable for all of us."),
     74            markForTranslation("A new trade route is set up with %(_player_)s. Take your share of the profits")
     75        ]),
    11076        "translateMessage": true,
    11177        "translateParameters": ["_player_"],
    112         "parameters": {"_player_": player}
     78        "parameters": { "_player_": player }
    11379    });
    11480};
    11581
    11682m.chatNewPhase = function(gameState, phase, started)
    11783{
    118     let message;
    119     if (started)
    120         message = markForTranslation("I am advancing to the %(phase)s.");
    121     else
    122         message = markForTranslation("I have reached the %(phase)s.");
    123 
    12484    Engine.PostCommand(PlayerID, {
    12585        "type": "aichat",
    126         "message": "/allies " + message,
     86        "message": "/allies " + (started ?
     87            markForTranslation("I am advancing to the %(phase)s.") :
     88            markForTranslation("I have reached the %(phase)s.")),
    12789        "translateMessage": true,
    12890        "translateParameters": ["phase"],
    12991        "parameters": { "phase": phase }
  • binaries/data/mods/public/simulation/components/UnitAI.js

     
    32303230                this.SelectAnimation("walk", false, this.GetWalkSpeed());
    32313231                this.MoveRandomly(+this.template.RoamDistance);
    32323232                // Set a random timer to switch to feeding state
    3233                 this.StartTimer(RandomInt(+this.template.RoamTimeMin, +this.template.RoamTimeMax));
     3233                this.StartTimer(randInt(+this.template.RoamTimeMin, +this.template.RoamTimeMax));
    32343234                this.SetFacePointAfterMove(false);
    32353235            },
    32363236
     
    32753275                // Stop and eat for a while
    32763276                this.SelectAnimation("feeding");
    32773277                this.StopMoving();
    3278                 this.StartTimer(RandomInt(+this.template.FeedTimeMin, +this.template.FeedTimeMax));
     3278                this.StartTimer(randInt(+this.template.FeedTimeMin, +this.template.FeedTimeMax));
    32793279            },
    32803280
    32813281            "leave": function() {
  • binaries/data/mods/public/simulation/helpers/Random.js

     
    1 /**
    2  * Returns a random integer from min (inclusive) to max (exclusive)
    3  */
    4 function RandomInt(min, max)
    5 {
    6     return Math.floor(min + Math.random() * (max-min));
    7 }
    8 
    9 Engine.RegisterGlobal("RandomInt", RandomInt);