Last change
on this file since 19270 was 19270, checked in by elexis, 7 years ago |
Unify random integer and float helper functions of GUI, Simulation and AI.
Patch By: bb
Differential Revision: D121
Refs: #4326
Removes the Random.js simulation helper and randomFloat function of the random map scripts library.
Adds randomIntInclusive and randomIntExclusive to make the calls more readable and fix and prevent off-by-one mistakes.
Adds randBool and use it in an AI occurance. It will be used in many places by the random map scripts.
Use the pickRandom function introduced in r19109 in more applicable occurances.
Replace remaining occurances of Math.random() with the new functions to easily test completeness.
Cleanup of the random map script functions will come in a separate commit.
|
-
Property svn:eol-style
set to
native
|
File size:
1.0 KB
|
Line | |
---|
1 | var WeightedList = function()
|
---|
2 | {
|
---|
3 | this.elements = [ ];
|
---|
4 | this.totalWeight = 0;
|
---|
5 | };
|
---|
6 |
|
---|
7 | WeightedList.prototype.length = function()
|
---|
8 | {
|
---|
9 | return this.elements.length;
|
---|
10 | };
|
---|
11 |
|
---|
12 | WeightedList.prototype.push = function(item, weight)
|
---|
13 | {
|
---|
14 | if (weight === undefined)
|
---|
15 | weight = 1;
|
---|
16 | this.totalWeight += weight;
|
---|
17 | this.elements.push({ "item": item, "weight": weight });
|
---|
18 | };
|
---|
19 |
|
---|
20 | WeightedList.prototype.removeAt = function(index)
|
---|
21 | {
|
---|
22 | var element = this.elements.splice(index, 1)[0];
|
---|
23 | if (element)
|
---|
24 | this.totalWeight -= element.weight;
|
---|
25 | };
|
---|
26 |
|
---|
27 | WeightedList.prototype.itemAt = function(index)
|
---|
28 | {
|
---|
29 | var element = this.elements[index];
|
---|
30 | return element ? element.item : null;
|
---|
31 | };
|
---|
32 |
|
---|
33 | WeightedList.prototype.randomIndex = function() {
|
---|
34 | var element;
|
---|
35 | var targetWeight = randFloat(0, this.totalWeight);
|
---|
36 | var cumulativeWeight = 0;
|
---|
37 | for (var index = 0; index < this.elements.length; index++)
|
---|
38 | {
|
---|
39 | element = this.elements[index];
|
---|
40 | cumulativeWeight += element.weight;
|
---|
41 | if (cumulativeWeight >= targetWeight)
|
---|
42 | return index;
|
---|
43 | }
|
---|
44 | return -1;
|
---|
45 | };
|
---|
46 |
|
---|
47 | Engine.RegisterGlobal("WeightedList", WeightedList);
|
---|
Note:
See
TracBrowser
for help on using the repository browser.