Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
2632 lines (2440 loc) · 98.7 KB
/
Copy pathgame.js
File metadata and controls
2632 lines (2440 loc) · 98.7 KB
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
/* ============================================================
EMPERA – game.js
A real-time strategy game inspired by Warcraft / Age of Empires
============================================================ */
'use strict';
// ==================== CONSTANTS ====================
const TS = 48;
let MW = 80;
let MH = 60;
const CAM_SPEED = 6;
const EDGE_ZONE = 20;
const T_GRASS = 0;
const T_TREE = 1;
const T_GOLD = 2;
const T_WATER = 3;
const T_ROCK = 4;
const T_STUMP = 5;
const T_GOLD_EMPTY = 6;
const TILE_COLOR = [
'#3d6e2f','#1a4a0a','#7a6010','#1a5276','#6a6a6a','#5a3e28','#3a3a3a'
];
// ==================== DEFINITIONS ====================
const BDEF = {
main_hall: { name:'Main Hall', size:3, maxHp:1200, cost:{gold:0, wood:0}, buildTime:0, popBonus:0, color:'#9b7a2a', border:'#6a4a10', trains:['worker'] },
barracks: { name:'Barracks', size:2, maxHp:600, cost:{gold:150, wood:100}, buildTime:360, popBonus:0, color:'#3a3a7a', border:'#1a1a5a', trains:['soldier','archer'] },
farm: { name:'Farm', size:2, maxHp:250, cost:{gold:80, wood:60}, buildTime:150, popBonus:5, color:'#4a7a2a', border:'#2a5a0a', trains:[] },
lumber_mill: { name:'Lumber Mill', size:2, maxHp:300, cost:{gold:100, wood:80}, buildTime:200, popBonus:0, color:'#7a4a1a', border:'#5a2a0a', trains:[] },
tower: { name:'Watch Tower', size:1, maxHp:500, cost:{gold:100, wood:80}, buildTime:200, popBonus:0, color:'#8a8a6a', border:'#5a5a3a', trains:[], range:7, damage:20, atkSpeed:60 },
blacksmith: { name:'Blacksmith', size:2, maxHp:400, cost:{gold:120, wood:80}, buildTime:240, popBonus:0, color:'#4a3a2a', border:'#2a1a0a', trains:['knight'] },
mage_tower: { name:'Mage Tower', size:2, maxHp:350, cost:{gold:200, wood:50}, buildTime:300, popBonus:0, color:'#4a2a6a', border:'#2a0a4a', trains:['mage'] },
stable: { name:'Stable', size:2, maxHp:450, cost:{gold:180, wood:120}, buildTime:280, popBonus:0, color:'#7a5a30', border:'#5a3a10', trains:['cavalry'] },
siege_workshop: { name:'Siege Workshop', size:2, maxHp:400, cost:{gold:200, wood:150}, buildTime:320, popBonus:0, color:'#5a5a40', border:'#3a3a20', trains:['catapult'] },
temple: { name:'Temple', size:2, maxHp:380, cost:{gold:150, wood:100}, buildTime:260, popBonus:0, color:'#b0a060', border:'#8a7a30', trains:['priest'] },
tavern: { name:'Tavern', size:2, maxHp:300, cost:{gold:250, wood:100}, buildTime:300, popBonus:0, color:'#8a4a2a', border:'#6a2a0a', trains:['hero'] },
};
const UDEF = {
worker: { name:'Worker', maxHp:70, speed:2.5, cost:{gold:80, wood:0}, trainTime:200, color:'#c8a050', size:11, damage:6, range:1.2, atkSpeed:45, armor:1, canGather:true, canBuild:true },
soldier: { name:'Footman', maxHp:150, speed:2.0, cost:{gold:130, wood:0}, trainTime:280, color:'#4a7adf', size:12, damage:20, range:1.2, atkSpeed:40, armor:3, canGather:false, canBuild:false },
archer: { name:'Archer', maxHp:90, speed:2.2, cost:{gold:100, wood:50}, trainTime:250, color:'#3aa060', size:10, damage:14, range:6.0, atkSpeed:50, armor:1, canGather:false, canBuild:false },
knight: { name:'Knight', maxHp:250, speed:1.8, cost:{gold:200, wood:0}, trainTime:350, color:'#9090c0', size:13, damage:35, range:1.2, atkSpeed:50, armor:8, canGather:false, canBuild:false },
mage: { name:'Mage', maxHp:80, speed:2.0, cost:{gold:150, wood:50}, trainTime:300, color:'#b060d0', size:10, damage:25, range:5.0, atkSpeed:60, armor:0, canGather:false, canBuild:false },
cavalry: { name:'Cavalry', maxHp:220, speed:3.2, cost:{gold:180, wood:0}, trainTime:360, color:'#a08040', size:14, damage:30, range:1.2, atkSpeed:40, armor:4, canGather:false, canBuild:false },
catapult: { name:'Catapult', maxHp:120, speed:0.9, cost:{gold:220, wood:80}, trainTime:450, color:'#707058', size:15, damage:65, range:8.0, atkSpeed:140,armor:0, canGather:false, canBuild:false },
priest: { name:'Priest', maxHp:75, speed:2.1, cost:{gold:140, wood:30}, trainTime:280, color:'#e8e8c0', size:10, damage:8, range:4.5, atkSpeed:55, armor:0, canGather:false, canBuild:false },
hero: { name:'Hero', maxHp:200, speed:2.3, cost:{gold:300, wood:50}, trainTime:500, color:'#ffd700', size:13, damage:30, range:1.5, atkSpeed:38, armor:5, canGather:false, canBuild:false, isHero:true },
// Neutral creatures (no cost, spawned by map)
wolf: { name:'Wolf', maxHp:60, speed:2.8, cost:{gold:0, wood:0}, trainTime:0, color:'#909090', size:10, damage:12, range:1.1, atkSpeed:35, armor:0, canGather:false, canBuild:false },
deer: { name:'Deer', maxHp:30, speed:3.1, cost:{gold:0, wood:0}, trainTime:0, color:'#b08050', size:9, damage:0, range:0, atkSpeed:999,armor:0, canGather:false, canBuild:false },
treant: { name:'Treant', maxHp:400, speed:1.2, cost:{gold:0, wood:0}, trainTime:0, color:'#2a5a0a', size:17, damage:25, range:1.5, atkSpeed:70, armor:3, canGather:false, canBuild:false },
};
// XP thresholds for hero levels 1-10 (index = level-1)
const HERO_XP_THRESH = [0, 100, 250, 450, 700, 1000, 1400, 1850, 2400, 3000];
// XP awarded per enemy kill by type
const XP_REWARD = {
worker:20, soldier:40, archer:35, knight:70, mage:60,
cavalry:65, catapult:80, priest:35, hero:150,
wolf:15, deer:8, treant:100,
};
// ==================== GAME STATE ====================
let canvas, ctx, mmCanvas, mmCtx, portraitCanvas, portraitCtx;
let gameW, gameH;
let camera = { x:0, y:0 };
let mouse = { x:0, y:0, wx:0, wy:0, down:false, downX:0, downY:0 };
let selBox = { active:false, x1:0, y1:0, x2:0, y2:0 };
let keys = {};
let entities = [];
let selectedIds = new Set();
let buildMode = null;
let rallyMode = null; // building id currently having its rally set
let frame = 0;
let resources = { gold:200, wood:150 };
let pop = { cur:0, max:10 };
let map = [];
let tileHP = {};
let notes = [];
let projectiles = []; // { x, y, tx, ty, speed, color, damage, owner, targetId, aoe }
let eid = 0;
let loopRunning = false;
// UI state (used to prevent unnecessary DOM rebuilds)
let lastBuildPanelHash = '';
let lastSelPanelHash = '';
// AI state
let aiResources = { gold:300, wood:200 };
let aiPop = { cur:0, max:10 };
let aiState = 'gathering';
let aiFrame = 0;
let aiBuildAttempted = false;
// Game phase
let gamePhase = 'menu';
let lastConfig = null;
// Options
let showGrid = false;
let soundEnabled = true;
let musicVolume = 50;
// ==================== UTILITY ====================
const uid = () => ++eid;
const tk = (x,y) => `${x},${y}`;
const d2 = (ax,ay,bx,by) => { const dx=ax-bx,dy=ay-by; return Math.sqrt(dx*dx+dy*dy); };
const dist = (a,b) => d2(a.x,a.y,b.x,b.y);
const w2t = (wx,wy) => ({ tx:Math.floor(wx/TS), ty:Math.floor(wy/TS) });
const t2w = (tx,ty) => ({ x:tx*TS+TS/2, y:ty*TS+TS/2 });
const clamp = (v,lo,hi) => Math.max(lo,Math.min(hi,v));
function walkable(tx,ty) {
if (tx<0||ty<0||tx>=MW||ty>=MH) return false;
const t=map[ty][tx];
return t===T_GRASS||t===T_STUMP||t===T_GOLD_EMPTY;
}
function tileOccupied(tx,ty) {
for (const e of entities) {
if (e.isUnit) continue;
const s=BDEF[e.type].size;
const ex=Math.floor(e.x/TS), ey=Math.floor(e.y/TS);
if (tx>=ex&&tx<ex+s&&ty>=ey&&ty<ey+s) return true;
}
return false;
}
function getEntity(id) { return entities.find(e=>e.id===id)||null; }
function addNote(text,wx,wy,color='#ffffff') {
notes.push({ text, x:wx, y:wy, color, life:0, maxLife:80 });
}
// ==================== MAP GENERATION ====================
function generateMap(theme='random') {
map = Array.from({length:MH}, ()=>new Uint8Array(MW));
tileHP = {};
const isForest = theme==='forest';
const isIslands = theme==='islands';
// Water bodies
const lakeCount = isIslands ? 14 : isForest ? 3 : 5;
for (let li=0; li<lakeCount; li++) {
const cx = 3+Math.floor(Math.random()*(MW-6));
const cy = 3+Math.floor(Math.random()*(MH-6));
const r = isIslands ? 4+Math.floor(Math.random()*5) : 3+Math.floor(Math.random()*3);
for (let dy=-r;dy<=r;dy++)
for (let dx=-r;dx<=r;dx++) {
if (dx*dx+dy*dy<=r*r) {
const x=cx+dx, y=cy+dy;
if (x>=0&&x<MW&&y>=0&&y<MH) map[y][x]=T_WATER;
}
}
// River tail
let rx=cx, ry=cy;
const dir=Math.random()<0.5?1:-1;
for (let i=0;i<6+Math.floor(Math.random()*8);i++) {
rx+=dir; ry+=Math.random()<0.3?1:0;
if (rx>=0&&rx<MW&&ry>=0&&ry<MH) {
map[ry][rx]=T_WATER;
if (rx+1<MW) map[ry][rx+1]=T_WATER;
}
}
}
// Forests
const treeDens = isForest ? 0.92 : theme==='meadows' ? 0.28 : 0.82;
const fCount = isForest ? 14 : theme==='meadows' ? 4 : 10;
for (let fi=0;fi<fCount;fi++) {
const fx=3+Math.floor(Math.random()*(MW-6));
const fy=3+Math.floor(Math.random()*(MH-6));
const r =4+Math.floor(Math.random()*5);
for (let dy=-r;dy<=r;dy++)
for (let dx=-r;dx<=r;dx++) {
if (dx*dx+dy*dy<=r*r+Math.random()*4) {
const x=fx+dx, y=fy+dy;
if (x>=0&&x<MW&&y>=0&&y<MH&&map[y][x]===T_GRASS&&Math.random()<treeDens)
map[y][x]=T_TREE;
}
}
}
// Gold mines
const mineCount = isForest ? 4 : 7;
let placed=0, attempts=0;
while (placed<mineCount&&attempts<300) {
attempts++;
const gx=4+Math.floor(Math.random()*(MW-8));
const gy=4+Math.floor(Math.random()*(MH-8));
if (map[gy][gx]===T_WATER) continue;
for (let dy=-1;dy<=1;dy++)
for (let dx=-1;dx<=1;dx++) {
const x=gx+dx, y=gy+dy;
if (x>=0&&x<MW&&y>=0&&y<MH&&map[y][x]===T_TREE) map[y][x]=T_GRASS;
}
map[gy][gx]=T_GOLD;
tileHP[tk(gx,gy)]=800;
placed++;
}
// Rocks
for (let i=0;i<Math.floor(MW*MH*0.004);i++) {
const rx=2+Math.floor(Math.random()*(MW-4));
const ry=2+Math.floor(Math.random()*(MH-4));
if (map[ry][rx]===T_GRASS) map[ry][rx]=T_ROCK;
}
// Tree HP
for (let y=0;y<MH;y++)
for (let x=0;x<MW;x++)
if (map[y][x]===T_TREE) tileHP[tk(x,y)]=100+Math.floor(Math.random()*50);
// ── Player start area (top-left) ──
const psx=7, psy=7;
for (let y=psy;y<psy+13;y++)
for (let x=psx;x<psx+13;x++)
if (y<MH&&x<MW&&(map[y][x]===T_TREE||map[y][x]===T_ROCK||map[y][x]===T_WATER))
map[y][x]=T_GRASS;
// Player gold mine
map[psy+3][psx+9]=T_GOLD; tileHP[tk(psx+9,psy+3)]=800;
// Forest east of start
for (let y=psy+1;y<psy+9;y++)
for (let x=psx+14;x<psx+19;x++)
if (x<MW&&y<MH&&map[y][x]===T_GRASS&&Math.random()<0.7) {
map[y][x]=T_TREE; tileHP[tk(x,y)]=100+Math.floor(Math.random()*50);
}
// ── AI start area (bottom-right) ──
const aisx=Math.max(5,MW-22), aisy=Math.max(5,MH-22);
for (let y=aisy;y<aisy+14&&y<MH;y++)
for (let x=aisx;x<aisx+14&&x<MW;x++)
if (map[y][x]===T_TREE||map[y][x]===T_ROCK||map[y][x]===T_WATER)
map[y][x]=T_GRASS;
const aigx=Math.min(aisx+9,MW-2), aigy=Math.min(aisy+3,MH-2);
map[aigy][aigx]=T_GOLD; tileHP[tk(aigx,aigy)]=800;
// Forest near AI
for (let y=aisy-2;y<aisy+6;y++)
for (let x=aisx-6;x<aisx-1;x++)
if (x>=0&&y>=0&&x<MW&&y<MH&&map[y][x]===T_GRASS&&Math.random()<0.7) {
map[y][x]=T_TREE; tileHP[tk(x,y)]=100+Math.floor(Math.random()*50);
}
}
// ==================== A* PATHFINDING ====================
class MinHeap {
constructor() { this.d=[]; }
push(item,f) { this.d.push({item,f}); this._up(this.d.length-1); }
pop() {
const top=this.d[0].item;
const last=this.d.pop();
if (this.d.length) { this.d[0]=last; this._dn(0); }
return top;
}
get size() { return this.d.length; }
_up(i) {
while (i>0) {
const p=(i-1)>>1;
if (this.d[p].f<=this.d[i].f) break;
[this.d[i],this.d[p]]=[this.d[p],this.d[i]]; i=p;
}
}
_dn(i) {
const n=this.d.length;
while (true) {
let b=i; const l=2*i+1,r=2*i+2;
if (l<n&&this.d[l].f<this.d[b].f) b=l;
if (r<n&&this.d[r].f<this.d[b].f) b=r;
if (b===i) break;
[this.d[i],this.d[b]]=[this.d[b],this.d[i]]; i=b;
}
}
}
const DIRS8 = [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1],[-1,1],[1,1]];
const COST8 = [1,1,1,1,1.414,1.414,1.414,1.414];
function findPath(sx,sy,ex,ey,nearTarget=false) {
if (sx===ex&&sy===ey) return [];
const N=MW*MH;
const gScore=new Float32Array(N).fill(Infinity);
const fScore=new Float32Array(N).fill(Infinity);
const parent=new Int32Array(N).fill(-1);
const closed=new Uint8Array(N);
const ki=(x,y)=>y*MW+x;
const h =(x,y)=>Math.abs(x-ex)+Math.abs(y-ey);
const startK=ki(sx,sy);
gScore[startK]=0;
fScore[startK]=h(sx,sy);
const open=new MinHeap();
open.push(startK,fScore[startK]);
let iters=0;
while (open.size>0&&iters++<5000) {
const ck=open.pop();
if (closed[ck]) continue;
closed[ck]=1;
const cx=ck%MW, cy=(ck/MW)|0;
if (cx===ex&&cy===ey) return smoothPath(reconstruct(parent,startK,ck));
if (nearTarget&&Math.abs(cx-ex)<=1&&Math.abs(cy-ey)<=1) return smoothPath(reconstruct(parent,startK,ck));
for (let d=0;d<8;d++) {
const nx=cx+DIRS8[d][0], ny=cy+DIRS8[d][1];
if (nx<0||ny<0||nx>=MW||ny>=MH) continue;
const passable=(nearTarget&&nx===ex&&ny===ey)?true:(walkable(nx,ny)&&!tileOccupied(nx,ny));
if (!passable) continue;
const nk=ki(nx,ny);
if (closed[nk]) continue;
const ng=gScore[ck]+COST8[d];
if (ng<gScore[nk]) {
parent[nk]=ck; gScore[nk]=ng; fScore[nk]=ng+h(nx,ny);
open.push(nk,fScore[nk]);
}
}
}
return null;
}
function reconstruct(parent,startK,endK) {
const path=[];
let cur=endK;
while (cur!==startK&&parent[cur]!==-1) {
const x=cur%MW, y=(cur/MW)|0;
path.unshift(t2w(x,y));
cur=parent[cur];
}
return path;
}
function smoothPath(path) {
if (!path||path.length<3) return path;
const out=[path[0]];
for (let i=1;i<path.length-1;i++) {
const prev=out[out.length-1];
const cur=path[i], next=path[i+1];
const dx1=cur.x-prev.x, dy1=cur.y-prev.y;
const dx2=next.x-cur.x, dy2=next.y-cur.y;
if (Math.abs(dx1*dy2-dy1*dx2)>18) out.push(cur);
}
out.push(path[path.length-1]);
return out;
}
function adjWalkable(tx,ty) {
for (const [dx,dy] of DIRS8) {
const nx=tx+dx, ny=ty+dy;
if (walkable(nx,ny)&&!tileOccupied(nx,ny)) return {tx:nx,ty:ny};
}
return null;
}
// ==================== ENTITY CREATION ====================
function makeBuilding(type,tx,ty,constructed=false,owner='player') {
const def=BDEF[type];
const e={
id:uid(), type, isUnit:false, owner,
x:tx*TS, y:ty*TS,
hp:constructed?def.maxHp:1, maxHp:def.maxHp,
state:constructed?'idle':'construction',
buildProg:constructed?1:0,
trainQueue:[], trainProg:0, lastAtk:0,
popBonus:def.popBonus||0,
rallyX:null, rallyY:null, // rally point (world coords)
};
entities.push(e);
if (e.popBonus) {
if (owner==='ai') aiPop.max+=e.popBonus;
else pop.max+=e.popBonus;
}
return e;
}
function makeUnit(type,x,y,owner='player') {
const def=UDEF[type];
const e={
id:uid(), type, isUnit:true, owner,
x, y, vx:0, vy:0,
hp:def.maxHp, maxHp:def.maxHp,
speed:def.speed, size:def.size,
damage:def.damage, range:def.range, atkSpeed:def.atkSpeed,
armor:def.armor||0,
canGather:def.canGather, canBuild:def.canBuild,
state:'idle',
path:[], targetTile:null, target:null, buildTarget:null,
carryGold:0, carryWood:0,
gatherTimer:0, atkTimer:0, healTimer:0,
lastResType:null, angle:0,
stuckTimer:0, lastX:x, lastY:y,
// Hero fields
isHero: def.isHero||false,
xp: 0, level: 1,
skillCooldowns:{},
};
entities.push(e);
if (owner==='ai') aiPop.cur++;
else if (owner==='player') pop.cur++;
// neutrals don't count against any pop
return e;
}
function removeEntity(id, killerUnit) {
const i=entities.findIndex(e=>e.id===id);
if (i===-1) return;
const e=entities[i];
if (e.isUnit) {
if (e.owner==='ai') aiPop.cur=Math.max(0,aiPop.cur-1);
else if (e.owner==='player') pop.cur=Math.max(0,pop.cur-1);
// Award XP to killer hero (only player/AI heroes earn XP, not neutral creatures)
if (killerUnit && killerUnit.isHero && killerUnit.owner!==e.owner && killerUnit.owner!=='neutral') {
const xpGain = XP_REWARD[e.type] || 20;
grantHeroXP(killerUnit, xpGain);
}
}
if (!e.isUnit&&e.popBonus) {
if (e.owner==='ai') aiPop.max=Math.max(0,aiPop.max-e.popBonus);
else pop.max=Math.max(0,pop.max-e.popBonus);
}
entities.splice(i,1);
selectedIds.delete(id);
}
function grantHeroXP(hero, amount) {
hero.xp += amount;
const maxLevel = HERO_XP_THRESH.length;
while (hero.level < maxLevel) {
const needed = HERO_XP_THRESH[hero.level]; // next level threshold
if (hero.xp >= needed) {
hero.level++;
// Stat gains per level
const bonusHp = 20;
const bonusDmg = 3;
const bonusArmor= 1;
hero.maxHp += bonusHp;
hero.hp = Math.min(hero.hp + bonusHp, hero.maxHp);
hero.damage += bonusDmg;
hero.armor += bonusArmor;
addNote(`⬆ Hero Lv${hero.level}!`, hero.x, hero.y, '#ffd700');
// Skill at levels 3, 5, 7, 10
const skills = {3:'Battle Cry', 5:'Regeneration', 7:'Thunder Bolt', 10:'Divine Shield'};
if (skills[hero.level]) addNote(`Skill: ${skills[hero.level]}`, hero.x, hero.y-24, '#ffaaff');
} else break;
}
}
// ==================== COMMANDS ====================
function cmdMove(unit,wx,wy) {
const {tx,ty}=w2t(wx,wy);
const utx=Math.floor(unit.x/TS), uty=Math.floor(unit.y/TS);
let gtx=tx, gty=ty;
if (!walkable(gtx,gty)||tileOccupied(gtx,gty)) {
const adj=adjWalkable(tx,ty);
if (adj) { gtx=adj.tx; gty=adj.ty; } else { gtx=utx; gty=uty; }
}
const path=findPath(utx,uty,gtx,gty);
unit.path=path||[]; unit.state=unit.path.length?'moving':'idle';
unit.target=null; unit.targetTile=null; unit.buildTarget=null;
}
function cmdGather(worker,tx,ty) {
const t=map[ty][tx];
if (t!==T_TREE&&t!==T_GOLD) return;
worker.targetTile={tx,ty};
worker.lastResType=t===T_GOLD?'gold':'wood';
const utx=Math.floor(worker.x/TS), uty=Math.floor(worker.y/TS);
const path=findPath(utx,uty,tx,ty,true);
if (path) { worker.path=path; worker.state='moving_gather'; }
else worker.state='idle';
}
function cmdBuild(worker,bId) {
const b=getEntity(bId); if (!b) return;
worker.buildTarget=bId;
const btx=Math.floor(b.x/TS), bty=Math.floor(b.y/TS);
const adj=adjWalkable(btx,bty); if (!adj) return;
const utx=Math.floor(worker.x/TS), uty=Math.floor(worker.y/TS);
const path=findPath(utx,uty,adj.tx,adj.ty);
if (path) { worker.path=path; worker.state='moving_build'; }
}
// ==================== NEAREST QUERIES ====================
function nearestHall(unit) {
const owner=unit.owner||'player';
let best=null, bd=Infinity;
for (const e of entities) {
if (!e.isUnit&&e.type==='main_hall'&&e.state!=='construction'&&(e.owner||'player')===owner) {
const d=dist(unit,{x:e.x+TS*1.5,y:e.y+TS*1.5});
if (d<bd) { bd=d; best=e; }
}
}
return best;
}
function nearestResource(unit,type) {
const tt=type==='gold'?T_GOLD:T_TREE;
let best=null, bd=Infinity;
for (let y=0;y<MH;y++)
for (let x=0;x<MW;x++)
if (map[y][x]===tt) {
const d=d2(unit.x,unit.y,x*TS+TS/2,y*TS+TS/2);
if (d<bd) { bd=d; best={tx:x,ty:y}; }
}
return best;
}
// ==================== UNIT UPDATE ====================
function followPath(unit) {
if (!unit.path||unit.path.length===0) { unit.vx=0; unit.vy=0; return true; }
const wp=unit.path[0];
const dx=wp.x-unit.x, dy=wp.y-unit.y;
const d=Math.sqrt(dx*dx+dy*dy);
if (d<unit.speed+1) {
unit.path.shift();
if (!unit.path.length) { unit.vx=0; unit.vy=0; return true; }
} else {
unit.vx=(dx/d)*unit.speed;
unit.vy=(dy/d)*unit.speed;
unit.angle=Math.atan2(dy,dx);
}
return false;
}
function dealDamage(attacker, target, dmg) {
// Armor reduces damage; minimum 1 ensures even heavy armor can be overcome
const actual = Math.max(1, dmg - (target.armor||0));
target.hp -= actual;
addNote(`-${actual}`, target.x, target.y, '#ff6666');
}
function spawnProjectile(fromX, fromY, target, speed, color, damage, attacker, aoe) {
const tx = target.isUnit ? target.x : target.x + (BDEF[target.type]?.size||1)*TS/2;
const ty = target.isUnit ? target.y : target.y + (BDEF[target.type]?.size||1)*TS/2;
projectiles.push({ x:fromX, y:fromY, tx, ty, speed, color, damage,
attacker, sourceOwner: attacker.owner||'player',
targetId:target.id, aoe:aoe||0, life:0 });
}
function updateUnit(unit) {
// Stuck detection
if (unit.path&&unit.path.length>0) {
if (Math.abs(unit.x-unit.lastX)<0.5&&Math.abs(unit.y-unit.lastY)<0.5) {
unit.stuckTimer++;
if (unit.stuckTimer>60) { unit.stuckTimer=0; unit.path=[]; }
} else {
unit.stuckTimer=0; unit.lastX=unit.x; unit.lastY=unit.y;
}
} else {
unit.lastX=unit.x; unit.lastY=unit.y; unit.stuckTimer=0;
}
const isAI=unit.owner==='ai';
const isNeutral=unit.owner==='neutral';
// ── Neutral creature AI ──────────────────────────────
if (isNeutral) {
if (unit.type==='wolf' || unit.type==='treant') {
if (unit.state==='idle') {
// Wolves and treants attack nearby units of any faction
let nearest=null, nearestD=(unit.type==='treant'?5:8)*TS;
for (const e of entities) {
if (e.owner==='neutral') continue;
const ex=e.isUnit?e.x:e.x+(BDEF[e.type]?.size||1)*TS/2;
const ey=e.isUnit?e.y:e.y+(BDEF[e.type]?.size||1)*TS/2;
const d=d2(unit.x,unit.y,ex,ey);
if (d<nearestD) { nearestD=d; nearest=e; }
}
if (nearest) { unit.target=nearest.id; unit.state='attacking'; unit.path=[]; }
}
} else if (unit.type==='deer') {
if (unit.state==='idle') {
// Deer flee from nearby units
let nearestD=5*TS;
let fleeDir=null;
for (const e of entities) {
if (e.owner==='neutral') continue;
const d=d2(unit.x,unit.y,e.x,e.y);
if (d<nearestD) { nearestD=d; fleeDir={dx:unit.x-e.x, dy:unit.y-e.y}; }
}
if (fleeDir) {
const len=Math.sqrt(fleeDir.dx**2+fleeDir.dy**2)||1;
const fx=unit.x+(fleeDir.dx/len)*8*TS;
const fy=unit.y+(fleeDir.dy/len)*8*TS;
const tx2=clamp(Math.floor(fx/TS),0,MW-1);
const ty2=clamp(Math.floor(fy/TS),0,MH-1);
cmdMove(unit, clamp(fx,0,MW*TS-1), clamp(fy,0,MH*TS-1));
}
}
}
}
// ── AI military: auto-attack nearby player entities within 8 tiles ──
if (isAI&&unit.state==='idle'&&unit.type!=='worker') {
let nearest=null, nearestD=8*TS;
for (const e of entities) {
if ((e.owner||'player')==='ai') continue;
if (e.owner==='neutral') continue;
const cx=e.isUnit?e.x:e.x+(BDEF[e.type]?.size||1)*TS/2;
const cy=e.isUnit?e.y:e.y+(BDEF[e.type]?.size||1)*TS/2;
const d=d2(unit.x,unit.y,cx,cy);
if (d<nearestD) { nearestD=d; nearest=e; }
}
if (nearest) { unit.target=nearest.id; unit.state='attacking'; unit.path=[]; }
}
// ── Priest healing ─────────────────────────────────────
if (!isNeutral && unit.type==='priest' && unit.state==='idle') {
unit.healTimer=(unit.healTimer||0)+1;
if (unit.healTimer>=80) {
unit.healTimer=0;
let worstAlly=null, worstHp=0.95;
for (const e of entities) {
if (!e.isUnit||e.owner!==unit.owner) continue;
const hpf=e.hp/e.maxHp;
if (hpf<worstHp && d2(unit.x,unit.y,e.x,e.y)<5*TS) { worstHp=hpf; worstAlly=e; }
}
if (worstAlly) {
const heal=Math.min(15, worstAlly.maxHp-worstAlly.hp);
worstAlly.hp+=heal;
addNote(`+${heal}`, worstAlly.x, worstAlly.y, '#88ff88');
}
}
}
// ── Hero passive skills ─────────────────────────────────
if (unit.isHero) {
const cd=unit.skillCooldowns;
// L5: Regeneration – heal 1 HP/sec
if (unit.level>=5) {
cd.regen=(cd.regen||0)+1;
if (cd.regen>=60 && unit.hp<unit.maxHp) { unit.hp=Math.min(unit.maxHp,unit.hp+1); cd.regen=0; }
}
// L3: Battle Cry – every 600 frames boost nearby allies for 1 frame (visual note)
if (unit.level>=3) {
cd.cry=(cd.cry||0)+1;
if (cd.cry>=600) {
cd.cry=0;
addNote('⚔ Battle Cry!', unit.x, unit.y-16, '#ff8800');
for (const e of entities) {
if (!e.isUnit||e.owner!==unit.owner) continue;
if (d2(unit.x,unit.y,e.x,e.y)<6*TS) {
// Temporary +8 damage (applied as bonus here, just visual)
addNote('↑ATK', e.x, e.y, '#ffaa44');
}
}
}
}
// L10: Divine Shield – once per 1800 frames, when HP < 30%, become invulnerable for 180 frames
if (unit.level>=10) {
if (!cd.shieldActive) {
cd.shieldCd=(cd.shieldCd||0)+1;
if (unit.hp/unit.maxHp<0.3 && cd.shieldCd>1800) {
cd.shieldCd=0; cd.shieldActive=180;
addNote('🛡 Divine Shield!', unit.x, unit.y-16, '#aaddff');
}
} else {
cd.shieldActive--;
if (cd.shieldActive<=0) delete cd.shieldActive;
}
}
}
switch (unit.state) {
case 'idle':
unit.vx*=0.7; unit.vy*=0.7;
break;
case 'moving':
if (followPath(unit)) unit.state='idle';
break;
case 'patrolling': {
if (!unit.patrolA||!unit.patrolB) { unit.state='idle'; break; }
const dest=unit.patrolTarget===1?unit.patrolB:unit.patrolA;
if (!unit.path||!unit.path.length) {
const utx=Math.floor(unit.x/TS), uty=Math.floor(unit.y/TS);
const dtx=Math.floor(dest.x/TS), dty=Math.floor(dest.y/TS);
const p=findPath(utx,uty,dtx,dty);
if (p) unit.path=p; else { unit.state='idle'; break; }
}
if (followPath(unit)) { unit.patrolTarget = unit.patrolTarget===1?2:1; }
// Attack enemies on patrol
let nearestEnemy=null, nearestD=4*TS;
for (const e of entities) {
if (!isNeutral && e.owner===unit.owner) continue;
if (isNeutral && e.owner==='neutral') continue;
const ex=e.isUnit?e.x:e.x+(BDEF[e.type]?.size||1)*TS/2;
const ey=e.isUnit?e.y:e.y+(BDEF[e.type]?.size||1)*TS/2;
const d=d2(unit.x,unit.y,ex,ey);
if (d<nearestD) { nearestD=d; nearestEnemy=e; }
}
if (nearestEnemy) { unit.patrolInterrupt={x:unit.x,y:unit.y}; unit.target=nearestEnemy.id; unit.state='attacking'; }
break;
}
case 'moving_gather': {
const done=followPath(unit);
if (done||!unit.path.length) {
const tt=unit.targetTile;
if (tt) {
const utx=Math.floor(unit.x/TS), uty=Math.floor(unit.y/TS);
if (Math.abs(utx-tt.tx)<=1&&Math.abs(uty-tt.ty)<=1) {
unit.state='gathering'; unit.gatherTimer=0;
} else {
const path=findPath(utx,uty,tt.tx,tt.ty,true);
if (path) { unit.path=path; unit.state='moving_gather'; } else unit.state='idle';
}
} else unit.state='idle';
}
break;
}
case 'gathering': {
unit.vx=0; unit.vy=0;
const tt=unit.targetTile; if (!tt) { unit.state='idle'; break; }
const tileT=map[tt.ty]&&map[tt.ty][tt.tx];
const isGold=tileT===T_GOLD, isWood=tileT===T_TREE;
if (!isGold&&!isWood) {
if (unit.carryGold||unit.carryWood) { unit.state='returning'; break; }
const nr=nearestResource(unit,unit.lastResType);
if (nr) cmdGather(unit,nr.tx,nr.ty); else unit.state='idle';
break;
}
unit.gatherTimer++;
if (unit.gatherTimer>=40) {
unit.gatherTimer=0;
const key=tk(tt.tx,tt.ty);
const rem=tileHP[key]||0;
if (rem<=0) {
map[tt.ty][tt.tx]=isGold?T_GOLD_EMPTY:T_STUMP;
if (unit.carryGold||unit.carryWood) { unit.state='returning'; break; }
const nr=nearestResource(unit,unit.lastResType);
if (nr) cmdGather(unit,nr.tx,nr.ty); else unit.state='idle';
break;
}
const g=Math.min(1,rem);
tileHP[key]=rem-g;
if (isGold) unit.carryGold=Math.min(10,unit.carryGold+g);
else unit.carryWood=Math.min(10,unit.carryWood+g);
if ((isGold?unit.carryGold:unit.carryWood)>=10) unit.state='returning';
}
break;
}
case 'returning': {
const hall=nearestHall(unit);
if (!hall) { unit.state='idle'; break; }
const hx=hall.x+TS*1.5, hy=hall.y+TS*1.5;
if (dist(unit,{x:hx,y:hy})<TS*3) {
if (isAI) {
aiResources.gold+=unit.carryGold;
aiResources.wood+=unit.carryWood;
} else {
resources.gold+=unit.carryGold;
resources.wood+=unit.carryWood;
if (unit.carryGold) addNote(`+${unit.carryGold}\u{1F4B0}`,unit.x,unit.y,'#ffd700');
if (unit.carryWood) addNote(`+${unit.carryWood}\u{1FAB5}`,unit.x,unit.y,'#c8a050');
}
unit.carryGold=0; unit.carryWood=0;
const tt=unit.targetTile;
if (tt) {
const t2=map[tt.ty][tt.tx];
if (t2===T_GOLD||t2===T_TREE) cmdGather(unit,tt.tx,tt.ty);
else {
const nr=nearestResource(unit,unit.lastResType);
if (nr) cmdGather(unit,nr.tx,nr.ty); else unit.state='idle';
}
} else unit.state='idle';
} else {
if (!unit.path||!unit.path.length) {
const htx=Math.floor(hall.x/TS), hty=Math.floor(hall.y/TS);
const utx=Math.floor(unit.x/TS), uty=Math.floor(unit.y/TS);
const adj=adjWalkable(htx,hty);
if (adj) { const p=findPath(utx,uty,adj.tx,adj.ty); if (p) unit.path=p; }
}
followPath(unit);
}
break;
}
case 'moving_build': {
if (followPath(unit)) {
const b=getEntity(unit.buildTarget);
unit.state=(b&&b.state==='construction')?'building':'idle';
if (unit.state!=='building') unit.buildTarget=null;
}
break;
}
case 'building': {
unit.vx=0; unit.vy=0;
const b=getEntity(unit.buildTarget);
if (!b||b.state!=='construction') { unit.state='idle'; unit.buildTarget=null; break; }
const bx=b.x+BDEF[b.type].size*TS/2, by=b.y+BDEF[b.type].size*TS/2;
unit.angle=Math.atan2(by-unit.y,bx-unit.x);
break;
}
case 'attacking': {
// Divine Shield: immune to damage
if (unit.isHero && unit.skillCooldowns?.shieldActive>0) {
unit.state='idle'; unit.target=null; break;
}
const tgt=getEntity(unit.target);
if (!tgt||tgt.hp<=0) {
unit.state='idle'; unit.target=null;
// Return to patrol if interrupted
if (unit.patrolInterrupt) { cmdMove(unit,unit.patrolInterrupt.x,unit.patrolInterrupt.y); unit.state='patrolling'; unit.patrolInterrupt=null; }
break;
}
const tx2=tgt.x+(tgt.isUnit?0:(BDEF[tgt.type]?.size||1)*TS/2);
const ty2=tgt.y+(tgt.isUnit?0:(BDEF[tgt.type]?.size||1)*TS/2);
const dv=d2(unit.x,unit.y,tx2,ty2);
const rng=unit.range*TS;
if (dv>rng) {
if (!unit.path||!unit.path.length) {
const utx=Math.floor(unit.x/TS), uty=Math.floor(unit.y/TS);
const etx=Math.floor(tgt.x/TS), ety=Math.floor(tgt.y/TS);
const p=findPath(utx,uty,etx,ety,true);
if (p) unit.path=p;
}
followPath(unit);
} else {
unit.vx=0; unit.vy=0;
unit.angle=Math.atan2(ty2-unit.y,tx2-unit.x);
unit.atkTimer++;
if (unit.atkTimer>=unit.atkSpeed) {
unit.atkTimer=0;
// Ranged units (archer, mage, priest, catapult) spawn projectile
const useProjectile = unit.range>2.5;
if (useProjectile) {
const pColor = unit.type==='archer'?'#c8b080':unit.type==='mage'?'#cc66ff':unit.type==='priest'?'#ffffff':'#ff8800';
const aoe = unit.type==='catapult'?2.0:0;
spawnProjectile(unit.x, unit.y-unit.size*0.3, tgt, 6, pColor, unit.damage, unit, aoe);
} else {
// Shield check for target hero
if (!(tgt.isHero && tgt.skillCooldowns?.shieldActive>0)) {
dealDamage(unit, tgt, unit.damage);
if (tgt.hp<=0) { removeEntity(tgt.id, unit); unit.state='idle'; unit.target=null; }
}
}
}
}
break;
}
}
unit.x+=unit.vx; unit.y+=unit.vy;
unit.x=clamp(unit.x,0,MW*TS-1);
unit.y=clamp(unit.y,0,MH*TS-1);
// Unit separation
for (const o of entities) {
if (!o.isUnit||o.id===unit.id) continue;
const dx=unit.x-o.x, dy=unit.y-o.y;
const dd=Math.sqrt(dx*dx+dy*dy);
const minD=unit.size+o.size-2;
if (dd<minD&&dd>0) { const push=(minD-dd)*0.3; unit.x+=dx/dd*push; unit.y+=dy/dd*push; }
}
}
// ==================== BUILDING UPDATE ====================
function updateBuilding(b) {
if (b.state==='construction') {
const workers=entities.filter(e=>e.isUnit&&e.state==='building'&&e.buildTarget===b.id);
if (workers.length) {
b.buildProg+=workers.length/BDEF[b.type].buildTime;
b.hp=Math.ceil(b.maxHp*b.buildProg);
}
if (b.buildProg>=1) {
b.buildProg=1; b.hp=b.maxHp; b.state='idle';
for (const w of workers) { w.state='idle'; w.buildTarget=null; }
addNote(`${BDEF[b.type].name} complete!`,b.x+TS,b.y,'#aaffaa');
}
return;
}
// Training queue
if (b.trainQueue.length) {
b.state='training';
const utype=b.trainQueue[0];
const udef=UDEF[utype];
b.trainProg++;
if (b.trainProg>=udef.trainTime) {
b.trainProg=0; b.trainQueue.shift();
const def=BDEF[b.type];
const spawnX=b.x+def.size*TS+TS*0.6;
const spawnY=b.y+def.size*TS*0.5;
const owner=b.owner||'player';
// Check pop cap
const curPop=owner==='ai'?aiPop.cur:pop.cur;
const maxPop=owner==='ai'?aiPop.max:pop.max;
if (curPop<maxPop) {
const u=makeUnit(utype,spawnX,spawnY,owner);
if (owner==='player') addNote(`${UDEF[utype].name} ready!`,spawnX,spawnY,'#88ff88');
// Send to rally point if set
if (b.rallyX!==null && u) {
cmdMove(u, b.rallyX, b.rallyY);
}
}
if (!b.trainQueue.length) b.state='idle';
}
} else {
b.state='idle';
}
// Tower auto-attack enemies (shoots projectile)
if (b.type==='tower') {
const def=BDEF.tower;
b.lastAtk++;
if (b.lastAtk>=def.atkSpeed) {
b.lastAtk=0;
const bOwner=b.owner||'player';
const range=def.range*TS;
const cx=b.x+TS/2, cy=b.y+TS/2;
let nearest=null, nearestD=range;
for (const e of entities) {
if ((e.owner||'player')===bOwner) continue;
if (e.owner==='neutral') continue;
const ex=e.isUnit?e.x:e.x+(BDEF[e.type]?.size||1)*TS/2;
const ey=e.isUnit?e.y:e.y+(BDEF[e.type]?.size||1)*TS/2;
const d=d2(cx,cy,ex,ey);
if (d<nearestD) { nearestD=d; nearest=e; }
}
if (nearest) {
// Tower fires an arrow projectile
spawnProjectile(cx, cy, nearest, 7, '#ffd700', def.damage, {owner:bOwner, damage:def.damage, isHero:false}, 0);
}
}
}
}
// ==================== PROJECTILE UPDATE ====================
function updateProjectiles() {
for (let i=projectiles.length-1;i>=0;i--) {
const p=projectiles[i];
const dx=p.tx-p.x, dy=p.ty-p.y;
const d=Math.sqrt(dx*dx+dy*dy);
if (d<p.speed+2) {
// Hit!
if (p.aoe>0) {
// AOE splash (catapult)
const aoePx = p.aoe*TS;
for (const e of [...entities]) {
if (!e.isUnit) continue;
if (e.owner===p.sourceOwner) continue;
if (d2(p.tx,p.ty,e.x,e.y)<aoePx) {
if (!(e.isHero && e.skillCooldowns?.shieldActive>0)) {
dealDamage(p.attacker, e, Math.round(p.damage*(0.5+0.5*(1-d2(p.tx,p.ty,e.x,e.y)/aoePx))));
if (e.hp<=0) removeEntity(e.id, p.attacker);
}
}
}
} else {
// Single target
const tgt=getEntity(p.targetId);
if (tgt && tgt.hp>0) {
if (!(tgt.isHero && tgt.skillCooldowns?.shieldActive>0)) {
dealDamage(p.attacker, tgt, p.damage);
if (tgt.hp<=0) removeEntity(tgt.id, p.attacker);
}
}
}
projectiles.splice(i,1);
continue;
}
p.x+=dx/d*p.speed;
p.y+=dy/d*p.speed;
p.life++;
// Remove stale projectiles
if (p.life>300) { projectiles.splice(i,1); continue; }
// Update target position (tracking)
const tgt2=getEntity(p.targetId);
if (tgt2 && tgt2.isUnit) { p.tx=tgt2.x; p.ty=tgt2.y; }
}
}
// ==================== AI SYSTEM ====================
function updateAI() {
if (gamePhase!=='playing') return;
aiFrame++;
const aiWorkers = entities.filter(e=>e.isUnit&&e.owner==='ai'&&e.type==='worker');
const aiMilitary = entities.filter(e=>e.isUnit&&e.owner==='ai'&&e.type!=='worker');
const aiHall = entities.find(e=>!e.isUnit&&e.owner==='ai'&&e.type==='main_hall');
const aiBarracks = entities.find(e=>!e.isUnit&&e.owner==='ai'&&e.type==='barracks'&&e.state!=='construction');
// Keep workers gathering
for (const w of aiWorkers) {
if (w.state==='idle') {
if (aiResources.gold<600) {
const g=nearestResource(w,'gold');
if (g) { cmdGather(w,g.tx,g.ty); continue; }
}