-
Notifications
You must be signed in to change notification settings - Fork 0
/
acsg-dist.js
14328 lines (12452 loc) · 391 KB
/
acsg-dist.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.acsg = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
/* eslint no-console: off */
/* eslint-env node,browser */
var fs = require('fs');
var grid = require('./pixels');
var position = require('mouse-position');
var Mousetrap = require('mousetrap');
var gaussian = require('gaussian');
var Rands = require('rands');
var seedrandom = require('seedrandom');
var uuidv4 = require('uuid/v4');
var GREEN = [0.51, 0.95, 0.61];
var BLUE = [0.50, 0.86, 1.00];
var YELLOW = [1.00, 0.86, 0.50];
var BLACK = [0, 0, 0];
var GRAY = [0.1, 0.1, 0.1];
var teamColors = [BLUE, YELLOW];
function arraysEqual(arr1, arr2) {
for (var i = arr1.length; i--;) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
function distance(x, y, xx, yy) {
return Math.sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y));
}
function extend(obj, src) {
for (var key in src) {
if (src.hasOwnProperty(key)) obj[key] = src[key];
}
return obj;
}
function filenameFrom(data) {
var experimentID = data.id;
return experimentID + '-decompressed.json';
}
function sum(vector) {
return vector.reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
}
function softmax(vector) {
var temperature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
/* The softmax activation function. */
var new_vector = vector.map(function (x) {
return Math.pow(x, temperature);
});
if (sum(new_vector)) {
return new_vector.map(function (x) {
return x / sum(new_vector);
});
} else {
return new_vector.map(function () {
return vector.length;
});
}
}
var acsg = {}; // Module namespace
acsg.Browser = function () {
var Browser = function Browser(game, opts) {
if (!(this instanceof Browser)) {
return new Browser(game, opts);
}
this.game = game; // Seed background animation RNG.
var backgroundRngFunc = seedrandom(this.now());
this.rBackground = new Rands(backgroundRngFunc);
this.scoreboard = document.getElementById('score');
this.bonus = document.getElementById('dollars');
this.clock = document.getElementById('clock');
this.data = [];
this.background = [];
this.opts = opts;
for (var i = 0; i < opts.ROWS; i++) {
for (var j = 0; j < opts.COLUMNS; j++) {
this.data.push(BLACK);
this.background.push(BLACK);
}
}
this.pixels = grid(this.data, {
root: document.body,
rows: opts.ROWS,
columns: opts.COLUMNS,
size: opts.BLOCK_SIZE,
padding: opts.BLOCK_PADDING,
background: GRAY,
formatted: true
});
if (this.opts.INCLUDE_HUMAN) {
this._bindKeys();
}
};
Browser.prototype.now = function () {
return performance.now();
};
Browser.prototype.updateScoreboard = function (ego) {
if (this.scoreboard !== null) {
this.scoreboard.innerHTML = ego.score;
}
if (this.bonus !== null) {
this.bonus.innerHTML = ego.payoff.toFixed(2);
}
};
Browser.prototype.updateClock = function (t) {
if (this.clock !== null) {
this.clock.innerHTML = t > 0 ? t.toFixed(1) : '0.0';
}
};
Browser.prototype.draw = function (position, color) {
// Covert x, y to linear index
var index = position[0] * this.opts.COLUMNS + position[1];
this.data[index] = color;
};
/**
* If in real-time mode, for every screen refresh update,
* call the callback function with the actual current timestamp.
*
* If we're not in real-time mode, return a timestamp that's later than
* the end of the experiment being replayed, so it executes all actions
* as fast as possible.
*
* See:
* https://github.com/regl-project/regl/blob/gh-pages/API.md#per-frame-callbacks
*/
Browser.prototype.eventStream = function (callback) {
var self = this;
if (!this.opts.REAL_TIME) {
// Jump to the end of the game, so we process all events immediately
var afterGameOver = (this.now() + this.opts.DURATION + 1) * 1000;
this.pixels.frame(function () {
callback(afterGameOver);
});
} else {
self = this;
this.pixels.frame(function () {
callback(self.now());
});
}
};
Browser.prototype.updateMask = function (ego) {
var g = gaussian(0, Math.pow(this.opts.VISIBILITY, 2));
var rescaling = 1 / g.pdf(0);
var x = ego.position[0];
var y = ego.position[1];
var dimness, idx;
for (var i = 0; i < this.opts.COLUMNS; i++) {
for (var j = 0; j < this.opts.ROWS; j++) {
dimness = g.pdf(distance(x, y, i, j)) * rescaling;
idx = i * this.opts.COLUMNS + j;
this.data[idx] = [this.data[idx][0] * dimness, this.data[idx][1] * dimness, this.data[idx][2] * dimness];
}
}
};
Browser.prototype.updateGrid = function (world) {
this._updateBackground();
world.drawTo(this);
this.pixels.update(this.data);
};
Browser.prototype.exportFile = function (data, filename) {
var blob = new Blob([JSON.stringify(data)], {
type: 'application/json'
});
var url = URL.createObjectURL(blob);
var el = document.createElement('a');
el.style.display = 'none';
el.id = 'downloadAnchorElem';
el.href = url;
el.download = filename;
el.textContent = 'Download';
document.body.appendChild(el);
el.click();
};
Browser.prototype._updateBackground = function () {
var rand;
for (var i = 0; i < this.data.length; i++) {
rand = this.rBackground.uniform() * 0.02;
this.background[i] = [this.background[i][0] * 0.95 + rand, this.background[i][1] * 0.95 + rand, this.background[i][2] * 0.95 + rand];
}
this.data = this.background;
};
Browser.prototype._bindKeys = function () {
var self = this;
var directions = ['up', 'down', 'left', 'right'];
var lock = false;
directions.forEach(function (direction) {
Mousetrap.bind(direction, function () {
if (!lock) {
self.game.playerMoved(direction);
}
lock = true;
return false;
});
Mousetrap.bind(direction, function () {
lock = false;
return false;
}, 'keyup');
});
};
return Browser;
}();
acsg.CLI = function () {
var CLI = function CLI(opts) {
if (!(this instanceof CLI)) {
return new CLI(opts);
}
this.opts = opts;
this._performance = require('perf_hooks');
};
CLI.prototype.now = function () {
return this._performance.performance.now();
};
CLI.prototype.draw = function () {// Noop
};
CLI.prototype.updateClock = function () {// Noop
};
CLI.prototype.updateGrid = function () {// Noop
};
CLI.prototype.updateMask = function () {// Noop
};
CLI.prototype.updateScoreboard = function () {// Noop
};
CLI.prototype.eventStream = function (callback) {
var afterGameOver = (this.now() + this.opts.DURATION + 1) * 1000;
callback(afterGameOver);
};
CLI.prototype.exportFile = function (data, filename) {
var content = JSON.stringify(data);
fs.writeFileSync('data/' + filename, content, function (err) {
if (err) throw err;
});
};
return CLI;
}();
acsg.World = function () {
var World = function World(settings) {
if (!(this instanceof World)) {
return new World(settings);
}
this.rows = settings.ROWS;
this.columns = settings.COLUMNS;
this.botStrategy = settings.BOT_STRATEGY;
this.food = [];
this.players = [];
this.states = [];
};
World.prototype.drawTo = function (ui) {
// Draw the players and food
this.players.forEach(function (p) {
ui.draw(p.position, p.color);
});
this.food.forEach(function (f) {
ui.draw(f.position, f.color);
});
ui.updateMask(this.ego());
};
World.prototype.randomPosition = function () {
var empty = false;
while (!empty) {
position = [Math.floor(Math.random() * this.rows), Math.floor(Math.random() * this.columns)];
empty = this.isEmpty(position);
}
return position;
};
World.prototype.hasPlayer = function (position) {
var numPlayers = this.players.length;
for (var i = 0; i < numPlayers; i++) {
if (arraysEqual(this.players[i].position, position)) {
return true;
}
}
return false;
};
World.prototype.hasFood = function (position) {
var numFood = this.food.length;
for (var i = 0; i < numFood; i++) {
if (this.food[i].position === position) {
return true;
}
}
return false;
};
World.prototype.isEmpty = function (position) {
return !this.hasPlayer(position) && !this.hasFood(position);
};
World.prototype.spawnFood = function () {
this.food.push(new acsg.Food({
'world': this
}));
};
World.prototype.spawnPlayer = function () {
this.players.push(new acsg.Player({
'world': this
}));
};
World.prototype.spawnBot = function () {
this.players.push(new acsg.Bot({
'world': this
}));
};
World.prototype.ego = function () {
return this.players[0];
};
World.prototype.recordStateAt = function (timestamp) {
this.states.push(this.state(timestamp));
};
World.prototype.state = function (t) {
var s = {
'timestamp': t,
'players': this.players,
'food': this.food
};
return acsg.State(s);
};
World.prototype.serialize = function () {
var players = [],
food = [],
states = [],
i;
for (i = 0; i < this.players.length; i++) {
players.push(this.players[i].serialize());
}
for (i = 0; i < this.food.length; i++) {
food.push(this.food[i].serialize());
}
for (i = 0; i < this.states.length; i++) {
states.push(this.states[i].serialize());
}
return {
players: players,
food: food,
states: states
};
};
return World;
}();
acsg.State = function () {
var State = function State(config) {
if (!(this instanceof State)) {
return new State(config);
}
this.timestamp = config.timestamp; // XXX Could we just store the serialized versions here?
this.players = config.players;
this.food = config.food;
};
State.prototype.serialize = function () {
var players = [],
food = [],
i;
for (i = 0; i < this.players.length; i++) {
players.push(this.players[i].serialize());
}
for (i = 0; i < this.food.length; i++) {
food.push(this.food[i].serialize());
}
return {
timestamp: this.timestamp,
players: players,
food: food
};
};
return State;
}();
acsg.Player = function () {
var Player = function Player(config) {
if (!(this instanceof Player)) {
return new Player(config);
}
this.world = config.world;
this.id = this.world.players.length;
this.position = this.world.randomPosition();
this.teamIdx = Math.floor(Math.random() * teamColors.length);
this.color = config.color || teamColors[this.teamIdx];
this.score = config.score || 0;
this.payoff = 0;
return this;
};
Player.prototype.move = function (direction) {
var newPosition = this.position.slice();
switch (direction) {
case 'up':
if (this.position[0] > 0) {
newPosition[0] -= 1;
}
break;
case 'down':
if (this.position[0] < this.world.rows - 1) {
newPosition[0] += 1;
}
break;
case 'left':
if (this.position[1] > 0) {
newPosition[1] -= 1;
}
break;
case 'right':
if (this.position[1] < this.world.columns - 1) {
newPosition[1] += 1;
}
break;
default:
console.log('Direction not recognized.');
}
if (!this.world.hasPlayer(newPosition)) {
this.position = newPosition;
}
return direction;
};
Player.prototype.consume = function () {
for (var i = 0; i < this.world.food.length; i++) {
if (arraysEqual(this.position, this.world.food[i].position)) {
this.world.food.splice(i, 1);
this.world.spawnFood();
this.score++;
break;
}
}
return this.score;
};
Player.prototype.serialize = function () {
return {
id: this.id,
position: this.position,
teamIdx: this.teamIdx,
color: this.color,
score: this.score,
bot: false
};
};
return Player;
}();
acsg.Bot = function () {
var Bot = function Bot(config) {
if (!(this instanceof Bot)) {
return new Bot(config);
}
acsg.Player.call(this, config);
this.strategyName = this.world.botStrategy;
};
Bot.prototype = Object.create(acsg.Player.prototype);
Bot.prototype.move = function () {
var direction = this.strategy[this.strategyName]();
acsg.Player.prototype.move.call(this, direction);
return direction;
};
Bot.prototype.strategy = {};
Bot.prototype.strategy.random = function () {
var dirs = ['up', 'down', 'left', 'right'];
return dirs[Math.floor(Math.random() * dirs.length)];
};
Bot.prototype.serialize = function () {
var data = acsg.Player.prototype.serialize.call(this);
data.bot = true;
return data;
};
return Bot;
}();
acsg.Food = function () {
var Food = function Food(config) {
if (!(this instanceof Food)) {
return new Food(config);
}
this.world = config.world;
this.position = config.position || this.world.randomPosition();
this.color = config.color || GREEN;
return this;
};
Food.prototype.serialize = function () {
return {
position: this.position,
color: this.color
};
};
return Food;
}();
acsg.Game = function () {
var Game = function Game(g) {
var opts, i;
if (!(this instanceof Game)) return new Game(g); // Check if this is a new game or a replay.
if (g.id) {
// A replay.
this.UUID = g.id;
this.humanActions = g.data.actions;
this.humanActionTimestamps = g.data.timestamps;
this.opts = g.config;
this.replay = true;
this.opts.REAL_TIME = g.config.REAL_TIME || false;
} else {
// A new game.
this.opts = opts = g.config || {};
this.opts.REAL_TIME = true;
this.opts.NUM_PLAYERS = opts.NUM_PLAYERS || 10;
this.opts.INCLUDE_HUMAN = opts.INCLUDE_HUMAN || false;
this.opts.DURATION = opts.DURATION || 120;
this.opts.ROWS = opts.ROWS || 25;
this.opts.COLUMNS = opts.COLUMNS || 25;
this.opts.NUM_FOOD = opts.NUM_FOOD || 5;
this.opts.VISIBILITY = opts.VISIBILITY || 500;
this.opts.BOT_MOTION_RATE = opts.BOT_MOTION_RATE || 8;
this.opts.BLOCK_SIZE = opts.BLOCK_SIZE || 15;
this.opts.BLOCK_PADDING = opts.BLOCK_PADDING || 1;
this.opts.BOT_STRATEGY = opts.BOT_STRATEGY || 'random';
this.opts.INTERGROUP_COMPETITION = opts.INTERGROUP_COMPETITION || 1;
this.opts.INTRAGROUP_COMPETITION = opts.INTRAGROUP_COMPETITION || 1;
this.opts.DOLLARS_PER_POINT = opts.DOLLARS_PER_POINT || 0.02;
this.UUID = uuidv4();
this.replay = false;
this.humanActions = [];
this.humanActionTimestamps = [];
}
if (this.opts.IS_CLI) {
this.ui = acsg.CLI(this.opts);
} else {
this.ui = acsg.Browser(this, this.opts);
}
if (this.opts.INCLUDE_HUMAN) {
this.numBots = this.opts.NUM_PLAYERS - 1;
} else {
this.numBots = this.opts.NUM_PLAYERS;
}
this.opts.SEED = this.opts.SEED || this.ui.now(); // Seed event RNG.
Math.seedrandom(this.opts.SEED);
this.eventRandomizer = new Rands();
this.gameOver = false;
this.world = acsg.World(this.opts); // Create the human.
if (this.opts.INCLUDE_HUMAN) {
this.world.spawnPlayer();
} // Create the bots.
for (i = 0; i < this.numBots; i++) {
this.world.spawnBot();
}
for (i = 0; i < this.opts.NUM_FOOD; i++) {
this.world.spawnFood();
}
};
Game.prototype.playerMoved = function (direction) {
if (!this.gameOver) {
this.humanActions.push(direction);
}
};
Game.prototype.serializeActions = function () {
var data = {
'id': this.UUID,
'data': {
'actions': this.humanActions,
'timestamps': this.humanActionTimestamps
},
'config': this.opts
};
if (this.opts.INCLUDE_HUMAN && this.world.players && this.world.players[0]) {
data.data.score = this.world.players[0].score;
data.data.payoff = this.world.players[0].payoff.toFixed(2);
}
return JSON.stringify(data);
};
Game.prototype.serializeFullState = function () {
var data = {
'id': this.UUID,
'data': {
'actions': this.humanActions,
'timestamps': this.humanActionTimestamps
},
'config': this.opts
};
data = extend(data, this.world.serialize());
return data;
};
Game.prototype.pregenerateBotMotion = function () {
// Pregenerate bot motion timings, sans direction. Since the timing and
// direction of all bot movement is deterministic based on the seed
// to the random number generator, we can pregenerate a sequence of
// time+bot pairs to execute later.
var motion = {
timestamps: [],
botIds: []
},
humanOffset = this.opts.INCLUDE_HUMAN ? 1 : 0,
t = 0,
waitTime,
idx; // eslint-disable-next-line no-constant-condition
while (true) {
waitTime = this.eventRandomizer.exponential(this.opts.BOT_MOTION_RATE * this.numBots);
if (t + waitTime > this.opts.DURATION) {
break;
}
t += waitTime;
motion.timestamps.push(t);
idx = Math.floor(Math.random() * this.numBots) + humanOffset;
motion.botIds.push(idx);
}
return motion;
};
Game.prototype.unbufferHumanMoves = function (timestamp) {
// If original game w/ human player, register any human moves
// added to the actions list with the current tick's timestamp
// so they can be processed on the next update.
var newActionCount;
if (this.opts.INCLUDE_HUMAN && !this.replay) {
newActionCount = this.humanActions.length - this.humanActionTimestamps.length;
for (var i = 0; i < newActionCount; i++) {
this.humanActionTimestamps.push(timestamp);
}
}
};
Game.prototype.computePayoffs = function () {
/* Compute payoffs from scores.
A player's payoff in the game can be expressed as the product of four
factors: the grand total number of points earned by all players, the
(softmax) proportion of the total points earned by the player's group,
the (softmax) proportion of the group's points earned by the player,
and the number of dollars per point.
Softmaxing the two proportions implements intragroup and intergroup
competition. When the parameters are 1, payoff is proportional to what
was scored and so there is no extrinsic competition. Increasing the
temperature introduces competition. For example, at 2, a pair of groups
that score in a 2:1 ratio will get payoff in a 4:1 ratio, and therefore
it pays to be in the highest-scoring group. The same logic applies to
intragroup competition: when the temperature is 2, a pair of players
within a group that score in a 2:1 ratio will get payoff in a 4:1
ratio, and therefore it pays to be a group's highest-scoring member. */
var group_info, group_scores, ingroup_scores, intra_proportions, inter_proportions, p, i;
var player_groups = {};
var total_payoff = 0;
var player = this.world.players[0];
for (i = 0; i < this.world.players.length; i++) {
p = this.world.players[i];
group_info = player_groups[p.teamIdx];
if (group_info === undefined) {
player_groups[p.teamIdx] = group_info = {
players: [],
scores: [],
total: 0
};
}
group_info.players.push(p);
group_info.scores.push(p.score);
group_info.total += p.score;
total_payoff += p.score;
}
group_scores = Object.values(player_groups).map(function (g) {
return g.total;
});
group_info = player_groups[player.teamIdx];
ingroup_scores = group_info.scores;
intra_proportions = softmax(ingroup_scores, this.opts.INTRAGROUP_COMPETITION);
player.payoff = total_payoff * intra_proportions[0];
inter_proportions = softmax(group_scores, this.opts.INTERGROUP_COMPETITION);
player.payoff *= inter_proportions[player.teamIdx];
player.payoff *= this.opts.DOLLARS_PER_POINT;
};
Game.prototype.run = function (callback) {
var self = this;
callback = callback || function () {
console.log('Game finished.');
};
var start = this.ui.now();
var botActions = [];
var lastBotActionIdx = -1;
var lastHumanActionIdx = -1;
var players = self.world.players;
var ego = self.world.ego();
var botMotion = this.pregenerateBotMotion();
this.world.recordStateAt(0);
this.ui.eventStream(function (now) {
var nextBotT, nextHumanT, elapsedTime, currentBot;
elapsedTime = (now - start) / 1000;
self.unbufferHumanMoves(elapsedTime); // Execute all unexecuted actions up to elapsedTime.
// eslint-disable-next-line no-constant-condition
while (true) {
nextBotT = botMotion.timestamps[lastBotActionIdx + 1] || Infinity;
nextHumanT = self.humanActionTimestamps[lastHumanActionIdx + 1] || Infinity;
if (nextBotT > elapsedTime && nextHumanT > elapsedTime) {
break;
}
if (nextBotT <= nextHumanT) {
// Break ties in favor of bots.
// Carry out bot action.
lastBotActionIdx += 1;
currentBot = players[botMotion.botIds[lastBotActionIdx]];
botActions.push(currentBot.move());
currentBot.consume();
self.world.recordStateAt(nextBotT);
} else {
// Carry out human action.
lastHumanActionIdx += 1;
ego.move(self.humanActions[lastHumanActionIdx]);
ego.consume();
self.ui.updateScoreboard(ego);
self.world.recordStateAt(nextHumanT);
}
self.computePayoffs();
}
self.ui.updateGrid(self.world);
self.ui.updateClock(self.opts.DURATION - elapsedTime);
self.computePayoffs();
if (lastBotActionIdx >= botMotion.botIds.length - 1) {
if (!self.gameOver) {
self.gameOver = true;
callback();
}
}
});
}; // Download the serialized game as a JSON file.
Game.prototype.exportFullGameData = function () {
var data = this.serializeFullState(),
filename = filenameFrom(data);
this.ui.exportFile(data, filename);
return filename;
};
return Game;
}();
module.exports = acsg;
},{"./pixels":64,"fs":3,"gaussian":6,"mouse-position":12,"mousetrap":13,"perf_hooks":3,"rands":19,"seedrandom":53,"uuid/v4":63}],2:[function(require,module,exports){
},{}],3:[function(require,module,exports){
arguments[4][2][0].apply(exports,arguments)
},{"dup":2}],4:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;