-
Notifications
You must be signed in to change notification settings - Fork 1
/
game_bundle.js
1949 lines (1809 loc) · 61.6 KB
/
game_bundle.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 () {
'use strict';
/** Asserts if the experssion is false, does not do anything in release builds
* @param {Boolean} assertion
* @param {Object} output
* @memberof Debug */
const ASSERT = window.enableAsserts ? (...assert)=> console.assert(...assert) : ()=>{};
/**
* 2D Vector object with vector math library
* <br> - Functions do not change this so they can be chained together
* @example
* let a = new Vector2(2, 3); // vector with coordinates (2, 3)
* let b = new Vector2; // vector with coordinates (0, 0)
* let c = vec2(4, 2); // use the vec2 function to make a Vector2
* let d = a.add(b).scale(5); // operators can be chained
*/
class Vector2
{
/** Create a 2D vector with the x and y passed in, can also be created with vec2()
* @param {Number} [x=0] - X axis location
* @param {Number} [y=0] - Y axis location */
constructor(x=0, y=0)
{
/** @property {Number} - X axis location */
this.x = x;
/** @property {Number} - Y axis location */
this.y = y;
}
/** Returns a new vector that is a copy of this
* @return {Vector2} */
copy() { return new Vector2(this.x, this.y); }
/** Returns a copy of this vector plus the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
add(v) { ASSERT(v.x!=undefined); return new Vector2(this.x + v.x, this.y + v.y); }
/** Returns a copy of this vector minus the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
subtract(v) { ASSERT(v.x!=undefined); return new Vector2(this.x - v.x, this.y - v.y); }
/** Returns a copy of this vector times the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
multiply(v) { ASSERT(v.x!=undefined); return new Vector2(this.x * v.x, this.y * v.y); }
/** Returns a copy of this vector divided by the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
divide(v) { ASSERT(v.x!=undefined); return new Vector2(this.x / v.x, this.y / v.y); }
/** Returns a copy of this vector scaled by the vector passed in
* @param {Number} scale
* @return {Vector2} */
scale(s) { ASSERT(s.x==undefined); return new Vector2(this.x * s, this.y * s); }
/** Returns the length of this vector
* @return {Number} */
length() { return this.lengthSquared()**.5; }
/** Returns the length of this vector squared
* @return {Number} */
lengthSquared() { return this.x**2 + this.y**2; }
/** Returns the distance from this vector to vector passed in
* @param {Vector2} vector
* @return {Number} */
distance(v) { return this.distanceSquared(v)**.5; }
/** Returns the distance squared from this vector to vector passed in
* @param {Vector2} vector
* @return {Number} */
distanceSquared(v) { return (this.x - v.x)**2 + (this.y - v.y)**2; }
/** Returns a new vector in same direction as this one with the length passed in
* @param {Number} [length=1]
* @return {Vector2} */
normalize(length=1) { const l = this.length(); return l ? this.scale(length/l) : new Vector2(0, length); }
/** Returns a new vector clamped to length passed in
* @param {Number} [length=1]
* @return {Vector2} */
clampLength(length=1) { const l = this.length(); return l > length ? this.scale(length/l) : this; }
/** Returns the dot product of this and the vector passed in
* @param {Vector2} vector
* @return {Number} */
dot(v) { ASSERT(v.x!=undefined); return this.x*v.x + this.y*v.y; }
/** Returns the cross product of this and the vector passed in
* @param {Vector2} vector
* @return {Number} */
cross(v) { ASSERT(v.x!=undefined); return this.x*v.y - this.y*v.x; }
/** Returns the angle of this vector, up is angle 0
* @return {Number} */
angle() { return Math.atan2(this.x, this.y); }
/** Sets this vector with angle and length passed in
* @param {Number} [angle=0]
* @param {Number} [length=1] */
setAngle(a=0, length=1) { this.x = length*Math.sin(a); this.y = length*Math.cos(a); return this; }
/** Returns copy of this vector rotated by the angle passed in
* @param {Number} angle
* @return {Vector2} */
rotate(a) { const c = Math.cos(a), s = Math.sin(a); return new Vector2(this.x*c-this.y*s, this.x*s+this.y*c); }
/** Returns the integer direction of this vector, corrosponding to multiples of 90 degree rotation (0-3)
* @return {Number} */
direction() { return abs(this.x) > abs(this.y) ? this.x < 0 ? 3 : 1 : this.y < 0 ? 2 : 0; }
/** Returns a copy of this vector that has been inverted
* @return {Vector2} */
invert() { return new Vector2(this.y, -this.x); }
/** Returns a copy of this vector with each axis floored
* @return {Vector2} */
floor() { return new Vector2(Math.floor(this.x), Math.floor(this.y)); }
/** Returns the area this vector covers as a rectangle
* @return {Number} */
area() { return abs(this.x * this.y); }
/** Returns a new vector that is p percent between this and the vector passed in
* @param {Vector2} vector
* @param {Number} percent
* @return {Vector2} */
lerp(v, p) { ASSERT(v.x!=undefined); return this.add(v.subtract(this).scale(clamp(p))); }
/** Returns true if this vector is within the bounds of an array size passed in
* @param {Vector2} arraySize
* @return {Boolean} */
arrayCheck(arraySize) { return this.x >= 0 && this.y >= 0 && this.x < arraySize.x && this.y < arraySize.y; }
/** Returns this vector expressed as a string
* @param {float} digits - precision to display
* @return {String} */
toString(digits=3)
{ return `(${(this.x<0?'':' ') + this.x.toFixed(digits)},${(this.y<0?'':' ') + this.y.toFixed(digits)} )`; }
}
// import { ZZFX } from '../node_modules/zzfx/ZzFX.js';
// const WORLD_SIZE = 2000;
// Resources
const Gr = 'grain',
Ri = 'rice',
Ka = 'karma',
S = 'stone',
Or = 'ore',
W = 'wood';
const T = true;
const F = false;
const N = null;
const TWO_PI = Math.PI * 2;
// Speed in pixels per millisecond
const MEEP_SPEED = 120 * (1/1000); // pixels per second * s/ms
const PROD_SPEED = MEEP_SPEED;
const CARR_SPEED = MEEP_SPEED * 1.1;
const ENCUMBER = 0.6; // multipler to speed
const IDLE_SPEED = MEEP_SPEED * 0.25;
const WORK_SPEED = MEEP_SPEED * 0.75;
const MAX_PATH_LOOK = 20;
const MAX_WORKERS = 6;
const WIND_KARMA = 300;
const KARMA_PER_RESOURCE = 1;
const MEEPLE_SIZE = 9; // radius
const BUILDING_BASE_SIZE = MEEPLE_SIZE + 5;
const BASE_DEF = 0.5;
const DEF_DEF = 0.9;
const COUNTDOWN = 4 * 60 * 1000; // 600000; // 10 minutes * 60 seconds/min * 1000 ms/sec
const INITIAL_COUNTDOWN = 5 * 60 * 1000;
const INVADER_PATH_RANGE = MEEPLE_SIZE * 20;
const DEFENDER_PATH_RANGE = MEEPLE_SIZE * 10;
const MELEE_DIST = MEEPLE_SIZE * 1.5; // want to allow a little overlap
const DMG = 20;
const HP = 100;
const HEAL = 5 / 1000; // 1 per 1000 ms
const EMBLEM_SIZE = 40;
const $ = (q) => document.querySelector(q);
const $id = (id) => document.getElementById(id);
const on = (el, type, fn) => el.addEventListener(type, fn);
const createSvg = (a) => document.createElementNS('http://www.w3.org/2000/svg', a);
const createAppendSvg = (a, p) => {
const el = createSvg(a);
p.appendChild(el);
return el;
};
const setAttr = (el, o) => {
Object.keys(o).forEach((k) => {
el.setAttribute(k, o[k]);
});
};
const setInputAttr = (el, propName, val) => {
el.setAttribute(propName, val);
el[propName] = val;
};
const setHtml = (sel, html) => {
const el = (typeof sel === 'object') ? sel : $(sel);
if (!el) throw new Error(`Cannot find element ${sel}`);
// if (sel === '#binfo') console.log(el.innerHTML, el.innerHTML.length, '\n...compare to...\n', html, html.length);
if (el.innerHTML === html) return false;
el.innerHTML = html;
return true;
};
const translateStyle = (v) => `translate(${v.x}px, ${v.y}px)`;
// From LittleJs
const rand = (a = 1, b = 0) => b + (a - b) * Math.random();
const randInt = (a = 1, b = 0) => rand(a, b)|0;
const randSign = () => (rand(2)|0) * 2 - 1;
// const distanceSquared = ({x,y}, {x1,y1}) => (x - x1)**2 + (y - y1)**2;
// const distance = (v1, v2) => distanceSquared(v1, v2)**.5;
const vec2 = (x=0, y)=> x.x == undefined ? new Vector2(x, y == undefined? x : y) : new Vector2(x.x, x.y);
// Other mini helpers
const randPick = (arr) => arr[randInt(arr.length)];
const atPoint = (v1, v2, within = 2) => (vec2(v1).distance(v2) <= within);
const setVec = (o, v) => { o.x = v.x; o.y = v.y; return o; };
const resourceTypes = Object.freeze({
grain: { shape: 'polygon', sides: 3, r: 6, offsetAngle: (1/6) * TWO_PI },
rice: { shape: 'polygon', sides: 5, r: 6 },
wood: { shape: 'polygon', sides: 4, r: 6, offsetAngle: (1/8) * TWO_PI },
stone: { shape: 'polygon', sides: 4, r: 6 },
ore: { shape: 'polygon', sides: 3, r: 6 },
});
const JOBS = [
{ key: 'idle', name: 'Wanderer', altName: 'Idle', classification: '💤' },
{ key: 'prod', name: 'Farmer/Artisan', altName: 'Production', classification: '🪚' },
{ key: 'carr', name: 'Carrier/Merchant', altName: 'Transportation', classification: '🧺' },
{ key: 'defe', name: 'Samurai/Soldier', altName: 'Defenders', classification: '🛡️' },
{ key: 'spir', name: 'Monk/Pilgrim', altName: 'Spiritualist', classification: '☸️' },
];
const JOBS_OBJ = JOBS.reduce((o, jobObj) => { o[jobObj.key] = jobObj; return o; }, {});
const JOB_KEYS = Object.keys(JOBS_OBJ);
const baseType = {
name: '',
r: 10, // radius and computes max resources
cap: 0, // inventory capacity
cost: [], // cost to create/upgrade
upgrades: [], // upgrade paths from here
defMax: 0, // contribution to defense max meeples
popMax: 0, // contribution to max meeples
input: [], // input for production
output: [], // output of production
rate: 0, // rate of production: # of outputs per minute
autoWork: F, // does this building work without workers?
classification: '', // production, defense, spirit
emblem: N, // string of polygon points in scale 30x30
};
const buildingTypesArr = [
{
key: 'outpost',
name: 'Outpost',
r: BUILDING_BASE_SIZE + 10, cap: 6, cost: [W, W, S, S],
defMax: 2, popMax: 2,
classification: '🚩',
emblem: '20,0 40,40, 20,40 30,20 10,20 20,40 0,40',
},
{
key: 'connector',
name: 'Crossroad',
r: BUILDING_BASE_SIZE * 0.8, cap: 2, cost: [],
upgrades: ['shrine', 'tower', 'stockpile', 'stoneMine', 'farmHouse', 'woodCutter', 'grainFarm', ],
classification: '🪧'
},
{
key: 'stockpile',
name: 'Stockpile',
r: BUILDING_BASE_SIZE + 20, cap: 20, cost: [S, W, Gr],
upgrades: ['warehouse'],
classification: '📦',
},
{
key: 'warehouse',
name: 'Warehouse',
r: BUILDING_BASE_SIZE + 32, cap: 40, cost: [S, S],
classification: '📦',
},
{
key: 'woodCutter',
name: 'Woodcutter',
r: BUILDING_BASE_SIZE + 10, cap: 6, cost: [Gr],
input: [Gr], output: [W], rate: 4,
upgrades: ['lumberYard'],
classification: '🪚',
},
{
key: 'lumberYard',
name: 'Lumber Yard',
r: BUILDING_BASE_SIZE + 12, cap: 7, cost: [Gr, W, Or],
input: [Gr], output: [W, W], rate: 5,
classification: '🪚',
},
{
key: 'stoneMine',
name: 'Stone Mine',
r: BUILDING_BASE_SIZE + 10, cap: 6, cost: [W, W, W, Gr],
input: [Gr], output: [S], rate: 1.5,
upgrades: ['oreMine', 'stoneMine2'],
classification: '🪚',
},
{
key: 'stoneMine2',
name: 'Stone Mine II',
r: BUILDING_BASE_SIZE + 12, cap: 6, cost: [W, W, Gr],
input: [Gr], output: [S], rate: 3,
upgrades: ['oreMine'],
classification: '🪚',
},
{
key: 'oreMine',
name: 'Ore Mine',
r: BUILDING_BASE_SIZE + 20, cap: 6, cost: [W, S, Gr],
input: [W, Gr], output: [Or], rate: 1,
upgrades: ['oreMine2'],
classification: '🪚',
},
{
key: 'oreMine2',
name: 'Ore Mine II',
r: BUILDING_BASE_SIZE + 21, cap: 7, cost: [W, S, Gr],
input: [W, Gr], output: [Or], rate: 2,
upgrades: ['oreMine3'],
classification: '🪚',
},
{
key: 'oreMine3',
name: 'Ore Mine III',
r: BUILDING_BASE_SIZE + 22, cap: 8, cost: [S, Gr, Ri],
input: [W, Gr], output: [Or, Or], rate: 3,
upgrades: [],
classification: '🪚',
},
{
key: 'tower',
name: 'Watchtower',
r: BUILDING_BASE_SIZE + 4, cap: 2, cost: [S, W, W],
defMax: 3,
upgrades: ['fortress'],
classification: '🛡️',
},
{
key: 'fortress',
name: 'Fortress',
r: BUILDING_BASE_SIZE + 14, cap: 4, cost: [S, S, S, W, Or],
defMax: 6,
upgrades: [],
classification: '🛡️',
},
{
key: 'grainFarm',
name: 'Grain Farm',
r: BUILDING_BASE_SIZE + 10, cap: 8, cost: [W, W],
input: [], output: [Gr], rate: 3,
upgrades: ['riceFarm', 'grainFarm2'],
classification: '🪚',
},
{
key: 'grainFarm2',
name: 'Grain Farm II',
r: BUILDING_BASE_SIZE + 11, cap: 8, cost: [W, W],
input: [], output: [Gr], rate: 6,
upgrades: ['riceFarm'],
classification: '🪚',
},
{
key: 'riceFarm',
name: 'Rice Farm',
r: BUILDING_BASE_SIZE + 14, cap: 6, cost: [W, W, Or, Or],
input: [], output: [Ri], rate: 4,
upgrades: ['riceFarm2'],
classification: '🪚',
},
{
key: 'riceFarm2',
name: 'Rice Farm II',
r: BUILDING_BASE_SIZE + 15, cap: 6, cost: [W, Or, Ri],
input: [], output: [Ri], rate: 6,
upgrades: [],
classification: '🪚',
},
{
key: 'shrine',
name: 'Shrine',
r: BUILDING_BASE_SIZE + 6, cap: 4, cost: [W, S, Or],
input: [Ri], output: [Ka], rate: 3,
upgrades: ['temple'],
classification: '☸️',
},
{
key: 'temple',
name: 'Temple',
r: BUILDING_BASE_SIZE + 22, cap: 6, cost: [S, Or, Or, Ri],
input: [Ri], output: [Ka, Ka], rate: 4,
upgrades: ['temple2'],
classification: '☸️',
},
{
key: 'temple2',
name: 'Temple II',
r: BUILDING_BASE_SIZE + 24, cap: 6, cost: [S, Or, Or, Ri],
input: [Ri], output: [Ka, Ka], rate: 8,
upgrades: ['grandTemple'],
classification: '☸️',
},
{
key: 'grandTemple',
name: 'Grand Temple',
r: BUILDING_BASE_SIZE + 26, cap: 6, cost: [Or, Or, Ri],
input: [Ri], output: [Ka, Ka, Ka], rate: 12,
classification: '☸️',
},
{
key: 'farmHouse',
name: 'Noka (farmhouse)',
r: 20, cap: 2, cost: [W, W, W],
input: [Gr], output: ['meeple'], rate: 1,
popMax: 3,
upgrades: ['urbanHouse', 'farmHouse2'],
autoWork: T,
classification: '🛖',
},
{
key: 'farmHouse2',
name: 'Noka II (farmhouse)',
r: 22, cap: 3, cost: [W, Gr],
input: [Gr], output: ['meeple'], rate: 1,
popMax: 4,
upgrades: ['urbanHouse', 'farmHouse3'],
autoWork: T,
classification: '🛖',
},
{
key: 'farmHouse3',
name: 'Noka III (farmhouse)',
r: 24, cap: 4, cost: [W, Gr],
input: [Gr], output: ['meeple'], rate: 1,
popMax: 5,
upgrades: ['urbanHouse'],
autoWork: T,
classification: '🛖',
},
{ // machiya
key: 'urbanHouse',
name: 'Machiya (urban house)',
r: 30, cap: 4, cost: [W, W, Or, Ri, Ri],
input: [Ri], output: ['meeple'], rate: 1,
popMax: 8,
autoWork: true,
classification: '🛖',
},
];
const buildingTypes = buildingTypesArr.reduce((obj, bt) => {
obj[bt.key] = {
...baseType,
...bt,
};
return obj;
}, {});
function getRandomWorldLocation() {
return { x: randInt(g.world.width / 2), y: randInt(g.world.height) };
}
function getRandomKey(prefix = 'U') {
return [
prefix,
randInt(9999).toString(36),
Number(new Date()).toString(36),
].join('-');
}
/* ------------------------------ Looping ------------------ */
function loopThing(keys, obj, fn) {
return keys.map((key, i) => {
const o = obj[key];
return fn(o, key, i);
});
}
const loopBuildings = (fn) => loopThing(g.buildingKeys, g.buildings, fn);
const loopRoads = (fn) => loopThing(g.roadKeys, g.roads, fn);
const loopCitizens = (fn) => loopThing(g.citizenKeys, g.meeples, fn);
const loopInvaders = (fn) => loopThing(g.invaderKeys, g.meeples, fn);
/* ------------------------------ Adding ------------------ */
function getPopMax() {
return 1 + g.buildingKeys.reduce((sum, k) => sum + (buildingTypes[g.buildings[k].type].popMax || 0), 0);
}
function getDefenderMax() {
return g.buildingKeys.reduce((sum, k) => sum + (buildingTypes[g.buildings[k].type].defMax || 0), 0);
}
function addRoad(bKey1, bKey2, rParam = {}) {
const bKey1From = (bKey1 < bKey2);
const r = {
key: getRandomKey('R'),
from: (bKey1From) ? bKey1 : bKey2,
to: (bKey1From) ? bKey2 : bKey1,
// length: 0,
...rParam,
};
if (g.roads[r.key]) throw new Error('Existing building');
// TODO: search for existing road to/from and throw error if exists already
g.roads[r.key] = r;
g.roadKeys.push(r.key);
return r;
}
function resetProductionCooldown(b, extra = 0) {
const { rate } = buildingTypes[b.type];
if (!rate) {
b.prodCool = 0;
return;
}
const extraNum = (Number.isNaN(extra)) ? 0 : extra;
b.prodHeat = (
60000 // 60000 ms per 1 minute
* (1 / rate) // rate = # of things created in 1 minute
) + extraNum;
if (g.godMode) b.prodHeat = 1;
b.prodCool = b.prodHeat;
}
function addBuilding(bParam = {}, fromBuildingKey = N) {
const b = {
key: getRandomKey('B'),
type: 'connector',
// x: 0,
// y: 0,
supplied: F,
prodCool: 0,
prodHeat: 0,
on: true,
inv: [],
refresh: false, // remove rendered element and recreate
// TODO: maintain links (roads) to other buildings so it is easy to find paths
...getRandomWorldLocation(),
...bParam,
};
resetProductionCooldown(b);
if (g.buildings[b.key]) throw new Error('Existing building');
console.log('Adding building', b);
g.buildings[b.key] = b;
g.buildingKeys.push(b.key);
if (fromBuildingKey) {
addRoad(b.key, fromBuildingKey);
}
return b;
}
function makeMeepleObject(m = {}) {
return {
key: getRandomKey('M'),
job: 'idle',
faction: 'japan',
hp: HP,
defense: BASE_DEF,
carry: N,
weapon: N,
buildingKey: N, // goal
path: [],
inv: [],
// x: 0,
// y: 0,
...getRandomWorldLocation(),
...m,
};
}
function addMeeple(mParam = {}, keyArr) {
const m = makeMeepleObject(mParam);
if (g.meeples[m.key]) throw new Error('Existing meeple');
console.log('Adding meeple', m);
g.meeples[m.key] = m;
keyArr.push(m.key);
return m;
}
function addCitizen(mParam = {}) {
if (g.citizenKeys.length >= getPopMax()) {
// console.warn('Could not add another meeple');
return false;
}
return addMeeple(mParam, g.citizenKeys);
}
function addInvader(mParam) {
return addMeeple({
key: getRandomKey('I'),
job: 'kill',
faction: 'mongol',
hp: HP,
defense: 0.2,
x: 0,
...mParam,
}, g.invaderKeys);
}
/* ------------------------------ Jobs ------------------ */
function getBlankJobCounts() {
return JOB_KEYS.reduce((o, j) => ({ ...o, [j]: 0 }), {});
}
function getJobCounts() {
return g.citizenKeys.reduce((counts, key) => {
const m = g.meeples[key];
counts[m.job] = (counts[m.job] || 0) + 1;
return counts;
}, getBlankJobCounts());
}
function getAdjustedJobCounts(job, val) {
const currJobCounts = getJobCounts();
const desiredJobCounts = {
...currJobCounts,
[job]: val,
};
const diff = desiredJobCounts[job] - currJobCounts[job];
if (diff <= 0) {
// If we're removing jobs, it's easy - we just make them idle
desiredJobCounts.idle += diff * -1;
return desiredJobCounts;
}
// Otherwise we're assigning jobs so we need to find the counts
let left = diff;
if (job !== 'idle') {
const takeFromIdle = Math.min(currJobCounts.idle, diff);
left -= takeFromIdle;
desiredJobCounts.idle -= takeFromIdle;
}
if (left <= 0) return desiredJobCounts;
const leftJobs = JOB_KEYS.reduce((arr, j) => {
if (j !== job && j !== 'idle') arr.push(j);
return arr;
}, []);
leftJobs.forEach((j, i) => {
const leftJobCount = (leftJobs.length - i) || 1;
const remove = Math.min(
Math.ceil(left / leftJobCount),
currJobCounts[j],
);
left -= remove;
desiredJobCounts[j] -= remove;
});
return desiredJobCounts;
}
function assignJobs(desiredJobCounts = {}) {
const currJobCounts = getBlankJobCounts();
const stillNeedJob = (j) => ((currJobCounts[j] || 0) < desiredJobCounts[j]);
const incrementJob = (j) => currJobCounts[j] = (currJobCounts[j] || 0) + 1;
loopCitizens((m) => {
// Still need this job, so keep job and increment count
if (stillNeedJob(m.job)) {
incrementJob(m.job);
return;
}
// Give the meeple a new job
m.job = JOB_KEYS.find(stillNeedJob) || 'idle';
m.path = []; // (m.path.length) ? [m.path[0]] : [];
incrementJob(m.job);
});
JOB_KEYS.forEach((job) => {
if (job === 'idle') return;
});
// console.log('Meeples assigned jobs:', g.meeples, 'desired:', desiredJobCounts, 'final:', currJobCounts);
}
/* ------------------------------ Upgrading ------------------ */
function payBuildingCost(bUpgrading, cost = []) {
const afford = canAffordAllResources(cost);
if (!afford) return F;
let leftToPay = [...cost];
leftToPay = consumeResources(bUpgrading, leftToPay);
// TODO: Loop through buildings based on connections or prioritizing stockpiles
loopBuildings((b) => {
leftToPay = consumeResources(b, leftToPay);
});
loopCitizens((m) => {
leftToPay = consumeResources(m, leftToPay);
});
return T;
}
function upgradeBuilding(bKey, upTypeKey) {
const b = g.buildings[bKey];
const { upgrades = [] } = buildingTypes[b.type];
if (!upgrades.includes(upTypeKey)) throw new Error(`Unknown upTypeKey`);
const paid = payBuildingCost(b, buildingTypes[upTypeKey].cost);
if (!paid) {
// window.alert('Cannot afford this upgrade yet.');
return;
}
b.type = upTypeKey;
b.refresh = T;
resetProductionCooldown(b);
renderBuildings();
}
/* ------------------------------ Rendering ------------------ */
function renderCanvas(ctx) {
// ctx.fillStyle = 'green';
// ctx.fillRect(10, 10, 150, 100);
}
function setCirclePercent(circleSvgEl, r, percent = 0) {
if (!circleSvgEl) throw new Error('No circle element');
const circumference = r * (2 * Math.PI);
const circPercent = percent * circumference;
const dashArray = [circPercent, circumference - circPercent];
setAttr(circleSvgEl, {
r,
// stroke: 'tomato',
'stroke-width': '10',
'stroke-dasharray': dashArray.join(' '),
'stroke-dashoffset': 40, // ?? just picked something that looks okay
// fill: 'none',
});
}
function setBuildingProgressSvg(b) {
const type = buildingTypes[b.type];
const r = type.r + 4;
const percent = getProdPercent(b);
const bEl = $id(b.key);
setCirclePercent(bEl.querySelector('.b-prod-circle'), r, percent);
}
function addBuildingSvg(b, layer) {
const type = buildingTypes[b.type];
const group = createAppendSvg('g', layer);
// group.id = b.key;
setAttr(group, {
id: b.key,
style: `transform: ${translateStyle(b)}`,
});
const prodCircle = createAppendSvg('circle', group);
setAttr(prodCircle, {
// r: type.r + 4,
'class': `b-prod-circle b-prod-${b.type}`,
});
setBuildingProgressSvg(b);
const circle = createAppendSvg('circle', group);
setAttr(circle, {
// cx: b.x,
// cy: b.y,
r: type.r,
'class': `building b-${b.type}`,
});
const emblemPoly = createAppendSvg('polygon', group);
const size = type.r * 1.2; // 1.2 is just a multiplier that looks good
const scale = size / EMBLEM_SIZE;
const x = -0.5 * EMBLEM_SIZE;
setAttr(emblemPoly, {
points: type.emblem || '',
'class': 'b-emblem',
style: `transform: scale(${scale}) ${translateStyle({ x, y: x })}`,
});
const resourceGroup = createAppendSvg('g', group);
setAttr(resourceGroup, { 'class': 'b-res-g res-g' });
return group;
}
function addRoadSvg(r, layer) {
const line = createAppendSvg('line', layer);
line.id = r.key;
const from = g.buildings[r.from];
const to = g.buildings[r.to];
setAttr(line, {
x1: from.x,
y1: from.y,
x2: to.x,
y2: to.y,
'class': 'road',
});
return line;
}
function addMeepleSvg(m, layer) {
const group = createAppendSvg('g', layer);
setAttr(group, {
id: m.key,
style: `transform: ${translateStyle(m)}`,
'class': 'meeple-g',
});
const circle = createAppendSvg('circle', group);
// circle.id = m.key;
setAttr(circle, {
// cx: 0, // m.x,
// cy: 0, // m.y,
r: MEEPLE_SIZE,
'class': `meeple mj-${m.job}`,
});
const resourceGroup = createAppendSvg('g', group);
setAttr(resourceGroup, { 'class': 'm-res-g res-g' });
return group;
}
function getPolygonPoints(sides, r, offsetAngle = 0) {
const points = [];
for (let i = 0; i < sides; i += 1) {
const a = offsetAngle + ((i / sides) * TWO_PI);
const v = vec2().setAngle(a, r);
const { x, y } = v;
points.push([ x, y ].map((n) => Math.round(n * 100) / 100));
}
return points;
}
function addResourceSvg(res, layer) {
const { shape, sides, r, offsetAngle = 0 } = resourceTypes[res];
const shapeEl = createAppendSvg(shape, layer);
const points = getPolygonPoints(sides, r, offsetAngle)
.map((pointsArr) => pointsArr.join(','))
.join(' ');
setAttr(shapeEl, {
points,
r,
'class': `res res-${res}`,
'data-res': res,
});
return shapeEl;
}
function renderResources(inv, gEl, r = 10) {
const children = [...gEl.children];
const expected = [...inv];
children.forEach((el) => {
const { res } = el.dataset;
if (!res) {
el.remove();
return;
}
const i = expected.indexOf(res);
if (i === -1) { // Not expected (anymore)
el.remove();
return;
}
// This resource is expected, so keep the element, but remove from expected list
expected.splice(i, 1);
});
expected.forEach((res) => {
const shape = addResourceSvg(res, gEl);
const v = vec2(0, 0).setAngle(rand(Math.PI * 2), rand(r));
// shape.style.cx = randInt(6) * randSign();
// shape.style.cy = randInt(6) * randSign();
shape.style.cx = v.x;
shape.style.cy = v.y;
shape.style.transform = translateStyle(v);
});
}
function renderBuildings() {
const { layers } = g.world;
loopBuildings((b) => {
const bt = buildingTypes[b.type];
let bEl = $id(b.key);
if (bEl && b.refresh) {
bEl.remove();
bEl = N;
b.refresh = F;
}
if (!bEl) bEl = addBuildingSvg(b, layers.building);
bEl.classList.toggle('closed', !b.on);
bEl.classList.toggle('selectedb', (b.key === g.selectedBuildingKey));
setBuildingProgressSvg(b);
renderResources(b.inv, bEl.querySelector('.res-g'), bt.r);
});
}
function renderMeeple(m, layer) {
let mEl = $id(m.key);
if (!mEl) mEl = addMeepleSvg(m, layer);
const circle = mEl.querySelector('.meeple');
setAttr(circle, { 'class': `meeple mj-${m.job}` });
mEl.classList.toggle('hurt', m.hp < HP);
mEl.style.transform = translateStyle(m);
renderResources(m.inv, mEl.querySelector('.res-g'), MEEPLE_SIZE);
}
function renderSvg(layers) {
renderBuildings();
loopRoads((r) => {
let rEl = $id(r.key);
if (!rEl) rEl = addRoadSvg(r, layers.road);
});
loopCitizens((m) => renderMeeple(m, layers.meeple));
loopInvaders((m) => renderMeeple(m, layers.meeple));
}
function loopJobs(fn) {
JOB_KEYS.forEach((job) => {
const el = $(`#jr-${job}`);
const input = el.querySelector('input[type="range"]');
const numEl = el.querySelector('.jr-num');
fn(job, input, el, numEl);
});
}
function renderJobAssignment() {
if (!g.assigning) return;
const counts = getJobCounts();
const maxMeeples = g.citizenKeys.length;
const maxDefenders = Math.min(maxMeeples, getDefenderMax());
loopJobs((job, input, el, numEl) => {
const n = counts[job];
numEl.innerText = n;
const max = (job === 'defe') ? maxDefenders : maxMeeples;
if (input.max !== max) setInputAttr(input, 'max', max);
if (input.value !== n) setInputAttr(input, 'value', n);
});
}
function getBuildingInfoHtml(b) {
if (!b) return '';
const bt = buildingTypes[b.type];
const butt = (id, active, emoji, text) => `<button id="${id}"${active ? ' class="active"' : ''}><i>${emoji}</i><b>${text}</b></button>`;
const toggleButtons = `<div class="switch">
${butt('b-on', b.on, '🕯️', 'On')}
${butt('b-off', !b.on, '🚫', 'Off')}
</div>`;
let percentHtml = '';
if (isBuildingProducer(b)) {
const percent = Math.floor(getProdPercent(b) * 100);
percentHtml = (isBuildingProducing(b)) ? `${percent}%` : '';
}
const prod = `<div>🪚 Production:
<span class="prodin ${b.supplied ? 'supplied' : 'missing'}">
${(bt.input.length) ? bt.input.join(', ') : '(No input)'}
</span>
➡️ ${(bt.output.length) ? bt.output.join(', ') : '(No output)'}
<span>(${bt.rate}/min)</span>
<span id="b-progress">${percentHtml}</span>
</div>`;
return `<div class="b-info">
<div class="b-name">${bt.classification} ${bt.name || b.type}</div>
${isBuildingProducer(b) ? prod : ''}
${bt.popMax ? `<div>+${bt.popMax} max citizens</div>` : ''}
${bt.defMax ? `<div>+${bt.defMax} max defenders</div>` : ''}
<div>📦 Resources: ${b.inv.length ? b.inv.join(', ') : 'None'} (${b.inv.length} / max: ${bt.cap})</div>
</div>
<div>
${toggleButtons}
</div>`;
}
function renderBuildingInfo(b) {
if (!b) return;
const binfo = getBuildingInfoHtml(b);
setHtml('#binfo', binfo);
}
function renderMeepleCounts() {
const html = `${g.citizenKeys.length} / max: ${getPopMax()}, Defenders max: ${getDefenderMax()}`;
setHtml('#mcounts', html);
}
function renderUi() {
const classes = $('main').classList;
classes.toggle('bselected', g.selectedBuildingKey);
classes.toggle('looping', g.looping);
classes.toggle('creating', g.creating);
classes.toggle('moving', g.moving);
classes.toggle('assigning', g.assigning);
classes.toggle('pop', g.citizenKeys.length > 0);
classes.toggle('intro', g.state === 'intro');
classes.toggle('game', g.state === 'game');
classes.toggle('flash', g.flashMessage);
// Update countdown
if (!g.countdownEl) g.countdownEl = $id('cd');
let cd = g.countdown;
const mins = Math.floor(cd * (1/1000) * (1/60));
cd -= (mins * 1000 * 60);
const sec = Math.floor(cd * (1/1000));
setHtml(g.countdownEl, g.peace ? '☮️' : `⚔️ ${mins}:${sec < 10 ? '0' : ''}${sec}`);
setHtml('#karma', (g.karma) ? `☸️ Karma: ${g.karma} /${WIND_KARMA}` : '');
$('#kamikaze').style.display = (g.karma >= WIND_KARMA) ? 'block' : 'none';
// List
if (g.selectedBuildingKey) {
const b = g.buildings[g.selectedBuildingKey];
renderBuildingInfo(b);
const { upgrades } = buildingTypes[b.type];
let upgradesHtml = (upgrades.length)
? upgrades.map((key) => {
const { name = key, cost, classification } = buildingTypes[key];
const afford = canAffordAllResources(cost);