-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
2515 lines (2141 loc) · 83.3 KB
/
main.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
// ==========================================================
// Game configuration
// ==========================================================
var mapWidth = 30,
mapHeight = 20,
movesPerTurn = 3,
minimumAIThinkingTime = 1000,
maximumAIThinkingTime = 5000;
// ==========================================================
// Game data
// ==========================================================
// === possible move types
var MOVE_ARMY = 1, BUILD_ACTION = 2, END_TURN = 3;
// === Player properties
var PLAYER_TEMPLATES = [
{i:0, n: 'Amber', l: '#fd8', d:'#960', h: '#fd8', hd:'#a80'},
{i:1, n: 'Crimson', l: '#f88', d:'#722', h: '#faa', hd:'#944'},
{i:2, n: 'Lavender', l: '#d9d', d:'#537', h: '#faf', hd:'#759'},
{i:3, n: 'Emerald', l: '#9d9', d:'#262', h: '#bfb', hd:'#484'}
];
// === Possible castle upgrades
var UPGRADES = [
{n: "Extra soldier", d: "", c: map(range(0,100), function(n) { return 8 + n * 4; }), x: []},
{n: "X of Water", d: "Income: X% more each turn.",
c: [15, 25], x: [20, 40],
b: '#66f'},
{n: "X of Fire", d: "Attack: X invincible soldier(s).",
c: [20, 30], x: [1, 2],
b: '#f88'},
{n: "X of Air", d: "Move: X extra move(s) per turn.",
c: [25, 35], x: [1, 2],
b: '#ffa'},
{n: "X of Earth", d: "Defense: Always kill X invader(s).",
c: [30, 45], x: [1, 2],
b: '#696'},
{n: "Rebuild fort", d: "Switch to a different upgrade.",
c: [0], x: []}
],
LEVELS = ["Fort", "Fortress"],
SOLDIER = UPGRADES[0], WATER = UPGRADES[1], FIRE = UPGRADES[2], AIR = UPGRADES[3], EARTH = UPGRADES[4], RESPEC = UPGRADES[5];
// === Constants for setup screen
var PLAYER_OFF = 0, PLAYER_HUMAN = 1, PLAYER_AI = 2;
var AI_NICE = 0, AI_RUDE = 1, AI_MEAN = 2, AI_EVIL = 3;
var UNLIMITED_TURNS = 1000000, TURN_COUNTS = [9, 12, 15, UNLIMITED_TURNS];
// == Application "states"
var APP_SETUP_SCREEN = 0, APP_INGAME = 1;
// == Special "player" for signifying a draw game
var DRAW_GAME = {};
// == AI personalities - how eagerly it builds soldiers, and what upgrades it prefers
var AI_PERSONALITIES = [
{s: 1, u:[]},
{s: 0.2, u: [WATER, EARTH]},
{s: 0.25, u: [WATER, FIRE, FIRE]},
{s: 0.15, u: [WATER, WATER, EARTH, EARTH]},
{s: 0.4, u: [WATER]},
{s: 0.3, u: [WATER, WATER]},
{s: 0.25, u: [FIRE, FIRE]},
{s: 0.2, u: [EARTH, EARTH]}
];
// ==========================================================
// Helper functions used for brevity or convenience.
// ==========================================================
var sin = Math.sin,
cos = Math.cos,
floor = Math.floor,
ceil = Math.ceil,
wnd = window,
doc = document,
div = elem.bind(0,'div');
// Returns a random number between low (inclusive) and high (exclusive).
function rint(low,high) {
return floor(low+Math.random()*(high-low));
}
// Returns an array of integers from low (inclusive) to high (exclusive).
function range(low,high) {
var r = [];
for (var i = low; i < high; i++)
r.push(i);
return r;
}
// Identity function (useful as a default for callback accepting functions like min).
function identity(x) { return x; }
// Creates a deep copy of an object, handling nested objects and arrays. Depth controls how deep
// the copy goes - the number of nesting levels that should be replicated.
function deepCopy(obj, depth) {
if ((!depth) || (typeof obj != 'object')) return obj;
var copy = (obj.length !== undefined) ? [] : {};
forEachProperty(obj, function(value, key) {
copy[key] = deepCopy(value, depth-1);
});
return copy;
}
// Clamps a number - if it's lower than low or higher than high, it's brought into range.
function clamp(number, low, high) {
return (number < low) ? low : ((number > high) ? high : number);
}
// Returns the current timestamp.
function now() {
return Date.now();
}
// Treats a given text as a template, replacing 'X' with the second parameter.
function template(text, replacement) {
return text.replace(/X/g, replacement);
}
// ==========================================================
// Loop constructs
// ==========================================================
// Same as array.map, but can be called on non-arrays (and minifies better).
function map(seq,fn) {
return [].slice.call(seq).map(fn);
}
// Iterates over all properties of an object, and calls the callback with (value, propertyName).
function forEachProperty(obj,fn) {
for (var property in obj)
fn(obj[property], property);
}
// Iterates over a rectangle (x1,y1)-(x2,y2), and calls fn with (x,y) of each integer point.
function for2d(x1,y1,x2,y2,fn) {
map(range(x1,x2), function(x) {
map(range(y1,y2), fn.bind(0,x));
});
}
// ==========================================================
// Working with the DOM
// ==========================================================
// Returns the element bearing the given ID.
function $(id) {
return doc.querySelector('#' + id);
}
// Return HTML (string) for a new element with the given tag name, attributes, and inner HTML.
// Some attributes can be shorthanded (see map).
function elem(tag,attrs,contents) {
var shorthanded = {
c: 'class',
s: 'style',
i: 'id'
};
var html = '<' + tag + ' ';
for (var attributeName in attrs) {
html += (shorthanded[attributeName] || attributeName) + "='" + attrs[attributeName] + "'";
}
html += '>' + (contents || '') + '</' + tag + '>';
return html;
}
// Appends new HTML to a container with the designated ID, and returns the resulting DOM node.
function append(containerId, newHTML) {
var container = $(containerId);
container.insertAdjacentHTML('beforeend', newHTML);
return container.lastChild;
}
// Sets the 'transform' CSS property to a given value (also setting prefixed versions).
function setTransform(elem, value) {
elem.style.transform = value;
elem.style['-webkit-transform'] = value;
}
// Adds a handler that will be called when a DOM element is clicked or tapped (touch events).
function onClickOrTap(elem, fn) {
elem.onclick = fn;
elem.addEventListener('touchstart', function(event) {
event.preventDefault();
return fn(event);
});
}
// Shows or hides an element with the given ID, depending on the second parameter.
function showOrHide(elementId, visible) {
$(elementId).style.display = visible ? 'block' : 'none';
}
function hide(elementId) { showOrHide(elementId, 0); }
function show(elementId) { showOrHide(elementId, 1); }
function toggleClass(element, className, on) {
if (typeof element == 'string')
element = $(element);
element.classList[on ? 'add' : 'remove'](className);
}
// ==========================================================
// Working on sequences
// ==========================================================
// Takes a sequence, and returns the smallest element according to a given key function.
// If no key is given, the elements themselves are compared.
function min(seq, keyFn) {
keyFn = keyFn || identity;
var smallestValue = keyFn(seq[0]), smallestElement;
map(seq, function(e) {
if (keyFn(e) <= smallestValue) {
smallestElement = e;
smallestValue = keyFn(e);
}
});
return smallestElement;
}
// Returns the biggest element of a sequence, see 'min'.
function max(seq, keyFn) {
keyFn = keyFn || identity;
return min(seq, function(elem) { return -keyFn(elem); })
}
// Returns the sum of a sequences, optionally taking a function that maps elements to numbers.
function sum(seq, keyFn) {
var total = 0;
map(seq, function(elem){
total += keyFn(elem);
});
return total;
}
// Checks whether a sequence contains a given element.
function contains(seq, elem) {
return seq && (seq.indexOf(elem) >= 0);
}
// Takes an array, and returns another array containing the result of applying a function
// on all possible pairs of elements.
function pairwise(array, fn) {
var result = [];
map(array, function(elem1, index) {
map(array.slice(index+1), function(elem2) {
result.push(fn(elem1, elem2));
});
});
return result;
}
// Shuffles a sequence (in place) and returns it.
function shuffle(seq) {
map(seq, function(_, index) {
var otherIndex = rint(index, seq.length);
var t = seq[otherIndex];
seq[otherIndex] = seq[index];
seq[index] = t;
});
return seq;
}
// ==========================================================
// Procedural map generation
// ==========================================================
// Generates a new map for a given number of players.
function generateMap(playerCount) {
var maxRegionSize = 11 - playerCount;
var neededRegions = 13 + playerCount * 3;
var perturbConst = rint(100000,100000000);
var regionMap, regions, count, retries;
// Repeat until we get a workable map
do {
regionMap = range(0,mapWidth).map(function(){return []});
regions = []; count = 0; retries = 2500;
// The main loop is repeated only a limited number of times to
// handle cases where the map generator runs into a dead end.
while ((count < neededRegions) && (--retries > 0)) {
// create a random region
var bounds = {
l: rint(1, mapWidth - maxRegionSize + 1),
t: rint(1, mapHeight - maxRegionSize + 1),
w: rint(3, maxRegionSize), h: rint(3, maxRegionSize)
};
// it has to overlap one of the existing ones
if (count && !overlaps(bounds)) continue;
// we shrink it until it no longer overlaps - this guarantees
// that it will border at least one other region, making the map
// contiguous
while (!shrink(bounds)) {
if (!overlaps(bounds)) {
regions.push(makeRegionAt(count++, bounds));
break;
}
}
}
} while (!retries);
fillNeighbourLists();
return regions;
// Shrink the region given by 'bounds' in a random direction
function shrink(bounds) {
var r = rint(0,4);
if (r % 2) bounds.w--; else bounds.h--;
if (r == 2) bounds.t++;
if (r == 3) bounds.l++;
return (bounds.w * bounds.h < 9);
}
// Checks if the region given by 'bounds' overlaps any existing region.
function overlaps(bounds) {
var rv = false;
for2d(bounds.l, bounds.t, bounds.l+bounds.w, bounds.t+bounds.h, function(x,y) {
rv = rv || regionMap[x][y];
});
return rv;
}
// Puts a new rectangular region at the position given in bounds {Left, Top, Width, Height}.
function makeRegionAt(index, bounds) {
// make points for the region
var l=bounds.l,t=bounds.t,w=bounds.w,h=bounds.h;
var points = [];
map(range(0,w+2), function(i) {
points[i] = perturbedPoint(l+i,t);
points[w+h+i] = perturbedPoint(l+w-i,t+h);
});
map(range(0,h+1), function(i) {
points[w+i] = perturbedPoint(l+w,t+i);
points[w+h+w+i] = perturbedPoint(l,t+h-i);
});
var region = {i: index, p: points, d:[]};
// mark it in the map
for2d(bounds.l, bounds.t, bounds.l + bounds.w, bounds.t + bounds.h, function(x,y){
regionMap[x][y] = region;
});
// return
return region;
}
// Perturbs a point to give the region borders a natural feel.
function perturbedPoint(x,y) {
var angle = (sin(x*x*y*y*600+perturbConst*657)) * 6.28;
var dist = (sin(x*y*600+perturbConst*511)) / 2;
return [x+sin(angle)*dist, y+cos(angle)*dist];
}
// Figures out who borders with who, using the 2d grid in 'regionMap'.
function fillNeighbourLists() {
for2d(1, 1, mapWidth-1, mapHeight-1, function(x,y) {
var region = regionMap[x][y];
if (region) {
if (!region.n) region.n = [];
map([[-1,0],[1,0],[0,-1],[0,1]],function(d) {
var potentialNeighbour = regionMap[x+d[0]][y+d[1]];
if (potentialNeighbour && (potentialNeighbour != region) && (region.n.indexOf(potentialNeighbour) == -1))
region.n.push(potentialNeighbour);
});
}
});
}
}
// ==========================================================
// Initial rendering of the game map as an SVG object.
// ==========================================================
// Returns the center of weight of a given set of [x,y] points.
function centerOfWeight(points) {
var xc = 0.0, yc = 0.0, l = points.length;
map(points, function(p) {
xc += p[0]; yc += p[1];
});
return [xc/l, yc/l];
}
// Affine transform of a sequence of points: [x*xm+xd,y*ym+yd]
function transformPoints(points, xm, ym, xd, yd) {
var c = centerOfWeight(points);
return map(points, function(p) {
return [c[0] + (p[0]-c[0]) * xm + xd, c[1] + (p[1]-c[1]) * ym + yd];
});
}
// 3d projection for the map
function projectPoint(p) {
var x = p[0] / mapWidth, y = p[1] / mapHeight;
var alpha = x * 0.05 + 1;
y = y * alpha + 0.5 * (1-alpha);
return [x*100, y*100];
}
// Generate a SVG gradient stop tag.
function gradientStop(percent, color) {
return elem('stop', {
offset: percent + '%',
s: 'stop-color:' + color
});
}
// Generate a SVG gradient tag for the map.
function makeGradient(id, light, dark) {
return elem('radialGradient', {
i: id,
cx: '-100%', cy: '50%',
fx: '-100%', fy: '50%',
r: '200%',
gradientUnits: 'userSpaceOnUse' // we want it to scale with the map, not the region it's applied to
}, gradientStop(60, dark) + gradientStop(100, light));
}
// Creates a new polygon with the given fill, stroke and clipping path.
function makePolygon(points, id, fill, stroke, clip) {
stroke = stroke || "stroke:#000;stroke-width:0.25;";
fill = fill ? "url(#" + fill + ")" : 'transparent';
var properties = {
i: id,
points: map(points, projectPoint).join(' '),
s: 'fill:' + fill + ";" + stroke + ';'
};
if (clip)
properties['clip-path'] = clip
return elem('polygon', properties);
}
// Takes the map (regions) stored in gameState.r, and creates an SVG map out of it.
function showMap(container, gameState) {
var regions = gameState.r;
// define gradients and clipping paths for rendering
var defs = elem('defs', {},
makeClipPaths() +
makeGradient('b', '#88f', '#113') +
makeGradient('l', '#197', '#042') +
makeGradient('lh', '#fb7', '#741') +
makeGradient('d', '#210', '#000') +
makeGradient('w', '#555', '#000') +
map(gameState.p, function(player, index) {
return makeGradient('p' + index, player.l, player.d) +
makeGradient('p' + index + 'h', player.h, player.hd);
}).join(''));
// create all the layers (5 per region)
var ocean = makePolygon([[0,0],[mapWidth,0],[mapWidth,mapHeight],[0,mapHeight]], 'b', '');
var tops = makeRegionPolys('r', 'l', 1, 1, 0, 0);
var bottoms = makeRegionPolys('d', 'd', 1, 1, .05, .05);
var shadows = makeRegionPolys('w', 'w', 1.05, 1.05, .2, .2, ' ');
var highlighters = makeRegionPolys('hl', '', 1, 1, 0, 0, 'stroke:#fff;stroke-width:1.5;opacity:0.0;', 'clip');
// replace the map container contents with the new map
container.innerHTML = elem('svg', {
viewbox: '0 0 100 100',
preserveAspectRatio: 'none'
}, defs + ocean + shadows + bottoms + tops + highlighters);
// clean some internal structures used to track HTML nodes
soldierDivsById = {};
// hook up region objects to their HTML elements
map(regions, function(region, index) {
region.e = $('r' + index);
region.c = projectPoint(centerOfWeight(region.p));
region.hl = $('hl' + index);
onClickOrTap(region.hl, invokeUICallback.bind(0, region, 'c'));
});
// additional callbacks for better UI
onClickOrTap(doc.body, invokeUICallback.bind(0, null, 'c'));
// make the castle <div>s
makeCastles();
// makes clipping paths for the "highlight" polygons
function makeClipPaths() {
return map(regions, function(region, index) {
return elem('clipPath', {i: 'clip' + index}, makePolygon(region.p, 'cp' + index, 'l', ''));
}).join('');
}
// a helper for creating a polygon with a given setup for all regions
function makeRegionPolys(idPrefix, gradient, xm, ym, xd, yd, stroke, clip) {
return elem('g', {}, map(regions, function(region, index) {
return makePolygon(transformPoints(region.p, xm, ym, xd, yd), idPrefix + index, gradient, stroke, clip ? 'url(#' + clip + index + ')' : '');
}).join(''));
}
// makes castle, which are just <div>s with nested <div>s (the towers)
function makeCastles() {
forEachProperty(gameState.t, function(castle) {
var center = castle.r.c,
style = 'left:' + (center[0]-1.5) + '%;top:' + (center[1]-4) + '%';
// create the castle <div>s
var castleHTML = div({
c: 'o',
s: style
}, '<img class="castle" src="img/castle.png"/>');
// }, div({c: 'i'}, div({c: 'i'}, div({c: 'i'}, div({c: 'i'})))));
castle.e = append('m', castleHTML);
// retrieve elements and bind callbacks
onClickOrTap(castle.e, invokeUICallback.bind(0, castle.r, 't'));
});
}
}
// Prepares the whole sidebar on the left for gameplay use.
function prepareIngameUI(gameState) {
// turn counter
var html = div({i: 'tc', c: 'sc'});
// player box area
html += div({i: 'pd', c: 'sc un'}, map(gameState.p, function(player) {
var pid = player.i;
return div({
i: 'pl' + pid,
c: 'pl',
style: 'background: ' + player.d
}, player.n +
div({c: 'ad', i: 'pr' + pid}) +
div({c: 'ad', i: 'pc' + pid})
);
}).join(''));
// info box
html += div({c: 'sc un ds', i: 'in'});
// set it all
$('d').innerHTML = html;
// show stat box and undo button
map(['mv', 'undo', 'end'], show);
}
// ==========================================================
// This part of the code deals with responding to user actions.
// ==========================================================
var uiCallbacks = {};
// This is the handler that gets attached to most DOM elements.
// Delegation through UI callbacks allows us to react differently
// depending on game-state.
function invokeUICallback(object, type, event) {
var cb = uiCallbacks[type];
if (cb) {
playSound(audioClick);
cb(object);
}
if (event.target.href && event.target.href != "#")
return 1;
event.stopPropagation();
return 0;
}
// This is one of the "player controller" methods - the one that
// is responsible for picking a move for a player. This one does
// that using a human and some UI, and calls reportMoveCallback
// with an object describing the move once its decided.
var uiState = {};
function uiPickMove(player, state, reportMoveCallback) {
var cleanState = {
b: [
{t: 'Cancel move', h:1},
{t: 'End turn'}
]
};
uiCallbacks.c = function(region) {
if ((!region) || (state.d.t == BUILD_ACTION))
setCleanState();
if (!state.d.s && region) {
// no move in progress - start a new move if this is legal
if (regionHasActiveArmy(state, player, region)) {
setCleanState();
state.d.t = MOVE_ARMY;
state.d.s = region;
state.d.c = soldierCount(state, region);
state.d.b[0].h = 0;
state.d.h = region.n.concat(region);
}
} else if (region) {
// we already have a move in progress
var decisionState = state.d;
// what region did we click?
if (region == decisionState.s) {
// the one we're moving an army from - tweak soldier count
decisionState.c = decisionState.c % soldierCount(state, region) + 1;
} else if (decisionState.s.n.indexOf(region) > -1) {
// one of the neighbours - let's finalize the move
uiCallbacks = {};
decisionState.d = region;
return reportMoveCallback(decisionState);
} else {
// some random region - cancel move
setCleanState();
}
}
updateDisplay(state);
};
uiCallbacks.t = function(region) {
var castle = state.t[region.i];
state.d = {
t: BUILD_ACTION,
w: castle, r: region,
b: makeUpgradeButtons(castle)
};
updateDisplay(state);
};
uiCallbacks.s = function(soldier) {
// delegate to the region click handler, after finding out which region it is
var soldierRegion = null;
map(state.r, function(region) {
if (contains(state.s[region.i], soldier))
soldierRegion = region;
});
if (soldierRegion)
uiCallbacks.c(soldierRegion);
};
uiCallbacks.b = function(which) {
if (state.d && state.d.t == BUILD_ACTION) {
// build buttons handled here
if (which >= UPGRADES.length) {
setCleanState();
} else {
// build an upgrade!
state.d.u = UPGRADES[which];
// if its a soldier, store UI state so it can be kept after the move is made
if (state.d.u == SOLDIER)
uiState[player.i] = state.d.r;
// report the move
reportMoveCallback(state.d);
}
} else {
// move action buttons handled here
if (which == 1) {
// end turn
uiCallbacks = {};
reportMoveCallback({t: END_TURN});
} else {
// cancel move
setCleanState();
}
}
};
uiCallbacks.un = function() {
// undo!
performUndo(state);
};
setCleanState();
if (uiState[player.i]) {
uiCallbacks.t(uiState[player.i]);
delete uiState[player.i];
}
function setCleanState() {
state.d = deepCopy(cleanState, 3);
state.d.h = state.r.filter(regionHasActiveArmy.bind(0, state, player));
updateDisplay(state);
}
function makeUpgradeButtons(castle) {
var castleOwner = owner(state, castle.r);
var upgradeButtons = map(UPGRADES, function(upgrade) {
// current upgrade level (either the level of the castle or number of soldiers bought already)
var level = (castle.u == upgrade) ? (castle.l+1) : ((upgrade == SOLDIER) ? (state.m.h || 0) : 0);
var cost = upgrade.c[level];
var text = template(upgrade.n, LEVELS[level]) + elem('b', {}, " (" + cost + "<span class='gold'></span>)");
var description = template(upgrade.d, upgrade.x[level]);
var hidden = false;
hidden = hidden || (upgrade == RESPEC && (!castle.u)); // respec only available if castle is upgraded
hidden = hidden || (castle.u && castle.u != upgrade && upgrade != SOLDIER && upgrade != RESPEC); // the castle is already upgraded with a different upgrade
hidden = hidden || (level >= upgrade.c.length); // highest level reached
hidden = hidden || (level < rawUpgradeLevel(state, castleOwner, upgrade)); // another castle has this upgrade already
hidden = hidden || (castleOwner != player); // we're looking at an opponent's castle
return {t: text, d: description, o: cost > cash(state, player), h: hidden};
});
upgradeButtons.push({t: "Done"});
return upgradeButtons;
}
}
// ==========================================================
// This part of the code helps organize game flow so things are displayed
// in order taking animation into account.
// ==========================================================
var oaatQueue = [];
function oneAtATime(duration, fn) {
oaatQueue.push({d: duration, f: fn});
if (oaatQueue.length == 1)
runOneTask();
function runOneTask() {
// start the first scheduled task
var task = oaatQueue[0];
task.f();
// and wait for it to expire
setTimeout(function() {
// task done, remove from queue
oaatQueue.shift();
// is there something more to do?
if (oaatQueue.length)
runOneTask();
}, task.d);
}
}
// ==========================================================
// This part of the code deals with updating the display to
// match the current game state.
// ==========================================================
var soldierDivsById = {};
function updateMapDisplay(gameState) {
map(gameState.r, updateRegionDisplay);
forEachProperty(gameState.t, updateCastleDisplay);
var soldiersStillAlive = [];
forEachProperty(gameState.s, function(soldiers, regionIndex) {
map(soldiers, updateSoldierDisplay.bind(0, gameState.r[regionIndex]));
});
forEachProperty(soldierDivsById, function(div, id) {
if (soldiersStillAlive.indexOf(parseInt(id)) < 0) {
// this is an ex-div - in other words, the soldier it represented is dead
$('m').removeChild(div);
delete soldierDivsById[id]; // surprisingly, this should be safe to do during iteration - http://stackoverflow.com/a/19564686
// spawn some particles
var x = parseFloat(div.style.left), y = parseFloat(div.style.top);
map(range(0,20), function() {
var angle = Math.random() * 6.28, dist = rint(0,100) / 80;
spawnParticle(x + sin(angle) * dist, y + cos(angle) * dist, 0, -1, '#000');
});
}
});
updateFloatingText();
updateTooltips();
updateSoldierTooltips();
function updateRegionDisplay(region) {
var regionOwner = owner(gameState, region);
var gradientName = (regionOwner ? 'p' + regionOwner.i : 'l');
var highlighted = contains(gameState.d && gameState.d.h || [], region) || // a region is highlighted if it has an available move
(gameState.e && regionOwner == gameState.e); // - or belongs to the winner (end game display highlights the winner)
// highlighting
if (highlighted) {
gradientName += 'h';
}
var highlightedOpacity = 0.1 + region.c[0] * 0.003;
if (gameState.e || (gameState.d && gameState.d.s == region))
highlightedOpacity *= 2;
region.hl.style.opacity = highlighted ? highlightedOpacity : 0.0;
region.hl.style.cursor = highlighted ? 'pointer' : 'default';
// particles
if (gameState.prt == region) {
gameState.prt = 0; // only once
map(region.p, function(point) {
point = projectPoint(point);
var center = region.c;
var alpha = rint(30,100)/100;
var startPoint = [lerp(alpha,center[0],point[0]), lerp(alpha,center[1],point[1])];
var vx = (startPoint[0]-center[0]) / 2, vy = (startPoint[1]-center[1]) / 2 - 0.15;
spawnParticle(startPoint[0], startPoint[1], vx, vy, '#fff');
});
}
// fill
region.e.style.fill = 'url(#' + gradientName + ')';
}
function updateTooltips() {
map(doc.querySelectorAll('.ttp'), $('m').removeChild.bind($('m')));
if (activePlayer(gameState).u != uiPickMove) return;
// "how to move" tooltips
var source = gameState.d && gameState.d.s;
if (source) {
showTooltipOver(source, "Click this region again to change the number of soldiers.");
// pick the furthest neighbour
var furthest = max(source.n, function(neighbour) {
return Math.abs(source.c[0]-neighbour.c[0]) + Math.abs(source.c[1] - neighbour.c[1]);
});
showTooltipOver(furthest, "Click a bordering region to move.");
}
if (!source) {
// "conquering armies cannot move" tooltips
var inactiveArmies = gameState.m.z;
if (inactiveArmies) {
showTooltipOver(inactiveArmies[inactiveArmies.length-1], "Armies that conquer a new region cannot move again.")
showTooltipOver({c: [-2, 80]}, "Once you're done, click 'End turn' here.");
}
}
if (gameState.m.t == 2 && gameState.m.l == 2) {
showTooltipOver({c:[90,93]}, "If you want to undo a move or check the rules, use the buttons here.", 15);
}
}
function showTooltipOver(region, text, width) {
if (gameSetup.tt[text]) return;
setTimeout(function() {
gameSetup.tt[text] = 1; // don't display it again (timeout to handle multiple updateDisplays() in a row)
storeSetupInLocalStorage(gameSetup);
}, 500);
width = width || 7;
var left = region.c[0] - (width+1) * 0.5, bottom = 102 - region.c[1];
var styles = 'bottom: ' + bottom + '%; left: ' + left + '%; width: ' + width + '%';
append('m', div({c: 'tt ttp', s: styles}, text));
}
function updateCastleDisplay(castle) {
var element = castle.e;
// right color and right number of levels (corresponding to upgrade level)
var castleLevels = castle.u ? (castle.l + 3) : 2;
console.log("Castle Level: "+castleLevels);
console.dir(castle.e);
var imgs = ['castle.png', 'fort.png', 'fortress.gif'];
element = castle.e.firstChild;
element.src = 'img/' + imgs[castleLevels - 2];
element.classList.remove("castle");
element.classList.remove("fort");
element.classList.remove("fortress");
element.classList.add(imgs[castleLevels - 2].replace(/\..*/,''));
/*
while (element) {
element.style.display = (castleLevels > 0) ? 'block' : 'none';
// element.style.background = castle.u ? castle.u.b : '#999';
castleLevels--;
element = element.firstChild;
}
*/
// which cursor should we use?
var castleOwner = owner(gameState, castle.r);
castle.e.style.cursor = (appState == APP_INGAME) ? ((castleOwner == activePlayer(gameState)) ? 'zoom-in' : 'help') : 'default';
// highlight?
var selected = gameState.d && gameState.d.w == castle;
toggleClass(castle.e, 'l', selected);
}
function updateSoldierDisplay(region, soldier, index) {
// we're still alive, so no removing our <div>
soldiersStillAlive.push(soldier.i);
// find or create a <div> for showing the soldier
var domElement = soldierDivsById[soldier.i];
if (!domElement) {
var html = div({c: 's', s: 'display: none'});
domElement = soldierDivsById[soldier.i] = append('m', html);
onClickOrTap(domElement, invokeUICallback.bind(0, soldier, 's'));
}
// (re)calculate where the <div> should be
var center = region.c;
var totalSoldiers = soldierCount(gameState, region);
var columnWidth = min([totalSoldiers,4]);
var rowHeight = min([2 / ceil(totalSoldiers / 4), 1]);
var x = index % 4, y = floor(index / 4);
var xOffset = (-0.6 * columnWidth + x * 1.2);
var yOffset = y * rowHeight + (gameState.t[region.i] ? 1.5 : 0);
var xPosition = center[0] + xOffset - yOffset * 0.2;
var yPosition = center[1] + xOffset * 0.2 + yOffset;
if (soldier.a) {
// we're attacking right now - move us closer to target region
var targetCenter = soldier.a.c;
xPosition = (xPosition + targetCenter[0]) / 2;
yPosition = (yPosition + targetCenter[1]) / 2;
}
domElement.style.left = xPosition + '%';
domElement.style.top = yPosition + '%';
domElement.style.zIndex = 20 + y * 5 + x;
domElement.style.display = 'block';
// selected?
var decisionState = gameState.d || {};
toggleClass(domElement, 'l', (decisionState.s == region) && (index < decisionState.c));
}
function updateSoldierTooltips() {
map(gameState.r, function(region, regionIndex) {
var tooltipId = 'sc' + regionIndex;
// delete previous tooltip, if present
var tooltip = $(tooltipId);
// should we have a tooltip?
var count = soldierCount(gameState, region);
if (count > 8) {
var selected = (gameState.d && (gameState.d.s == region)) ? gameState.d.c : 0;
selected += sum(gameState.s[regionIndex], function(soldier) {
return soldier.a ? 1 : 0;
});
if (selected)
count = selected + "<hr>" + count;
if (!tooltip) {
var tooltipHTML = div({
i: tooltipId,
c: 'tt stt',
s: "left:" + (region.c[0] - 1.5) + '%;top:' + (region.c[1] + 1.2) + '%'
}, '');
tooltip = append('m', tooltipHTML);
}
tooltip.innerHTML = count;
} else if (tooltip) {
tooltip.parentNode.removeChild(tooltip);
}
});
}
function updateFloatingText() {
map(gameState.flt || [], function(floater) {
var x, y;
if (floater.r) {
x = floater.r.c[0]; y = floater.r.c[1];
} else {
var node = soldierDivsById[floater.s.i];
x = parseFloat(node.style.left) + 0.2, y = parseFloat(node.style.top) + 0.2;
}
x -= floater.w/2 + 0.5; y -= 4;
var styles = "left: " + x + "%;top:" + y + "%;color:" + floater.c + ";width:" + floater.w + "%";
var floatingNode = append('m', div({c: 'tt', s: styles}, floater.t));
setTransform(floatingNode, "translate3d(0,0,0)");
floatAway(floatingNode, 0, -3);
});
gameState.flt = 0;
}
}
function updateIngameUI(gameState) {
var moveState = gameState.m;
var decisionState = gameState.d;
var buildingMode = decisionState && (decisionState.t == BUILD_ACTION);
var movingArmy = decisionState && decisionState.s;
var active = activePlayer(gameState);
// turn counter/building name
if (buildingMode) {
var info = castleInfo(gameState, decisionState.w);
$('tc').innerHTML = div({}, info.n) + div({c: 'ds'}, info.d);
} else {
$('tc').innerHTML = 'Turn <b>' + gameState.m.t + '</b>' + ((gameSetup.tc != UNLIMITED_TURNS) ? ' / ' + gameSetup.tc : '');
}
// player data
map(gameState.p, function(player, index) {
//$('pl' + index).className = (index == moveState.p) ? 'pl' : 'pi'; // active or not?
var regions = regionCount(gameState, player);
var gameWinner = gameState.e;