/
World.dart
1198 lines (1137 loc) · 41.8 KB
/
World.dart
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
part of BigIsland;
// Big Island video game source code file
// Copyright (C) 2012 Severin Ibarluzea
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
class World {
Map dataTree,mapsTree,currentMapTree;
TileManager bottomTileManager;
TileManager topTileManager;
List<MenuInterface> menuInterfaces;
OverlayManager overlay;
Camera camera;
List<GameObject> objects;
List<GameObject> onscene,offscene;
int map_width;
List<bool> collisionMap;
List<html.ImageElement> itemImages;
List<html.ImageElement> uiImages;
num AGRO_DISTANCE= 256;
num ZOMBIE_WANDER_DISTANCE = 256;
num ZOMBIE_SPEED = .6;
num ZOMBIE_ARMOR = 1;
num ZOMBIE_DAMAGE = 25;
List<Path> paths;
List<PathNode> pathnodes;
num time = 7;//24:00 clock (Start at 7)
num dayLength = 60 * 60 * 3;
bool night_mode = false;
int totalPopulation = 200;
int saved = 0;
int awakePopulation = 0;
int dayCount = 1;
int zombie_max = 100;
int zombie_out = 0;
int zombies_killed = 0;
int rapid_clicks = 0;
int guard_total = 2;//2
int guard_price = 100;
int difficultyMode = 0;
bool controlsOpen = true;
html.ImageElement controlsImage;
List<bool> playerWeapons;
int currentWeapon = 0;
List<num> weaponDamage;
List<int> weaponAttackTime;
List<int> weaponAttackTypes;
List<num> weaponAttackRadius;
List<int> weaponCost;
List<int> weaponCost2;//For second upgrade
List<String> weaponName;
List<int> weaponStartFrame;
int multiplier = 1;
num multiplier_time = 0;
final List<int> max_multiplier_time = const [120,120,120,100,80,60,50,40,35,30,25,20,20,20,20,20,10,5,5,5,5];
int coin = 0;//Player Money
Animation player_animation;
int player_max_health = 100;
bool intro = true;
int slideTime = 0;
int currentSlide = 0;
final List<String> slides = const["This is Big Island",
"At day, all is peaceful",
"But come night, horrific monsters of the black appear",
"The ever-curious villagers often stray into the darkness",
"Do you have what it takes to defend them?"];
final List<num> slidex_pos = const[2400,4581,4329,2324,8221];
final List<num> slidey_pos = const[1000,5251,6819,8114,6860];
final List<num> slide_dir = const[2,2,3,-2,-2];
bool paused;
//List<String> dayName = const["The Beginning","Long Night","","","","","","","","","","","","","",""];
Avatar player;
World(){
objects = new List<GameObject>();
onscene = new List<GameObject>();
offscene = new List<GameObject>();
camera = new Camera(0,0,1);
overlay = new OverlayManager();
menuInterfaces = new List<MenuInterface>();
paths = new List<Path>();
pathnodes = new List<PathNode>();
playerWeapons = [true,true ,true ,true , true,true];
playerWeapons = [true,false,false,false,false,false];
//[0] = fist
//[1] = dagger
//[2] = bow
//[3] = staff
//[4] = spear
//[5] = rapier
//[6] = longsword
weaponDamage = [25, 34, 20, 34, 75, 45, 70 ];
weaponAttackTypes = [0, 0, 1, 2, 2, 0, 0 ];
weaponAttackTime = [12, 10, 24, 15, 20, 12, 18 ];
weaponAttackRadius = [64, 64, 256, 64, 64, 64, 64 ];
weaponCost = [0, 120, 240, 150, 400, 300, 500 ];
weaponCost2 = [0, 120, 240, 150, 400, 300, 500 ];
weaponStartFrame = [0, 0, 25, 0, 0, 0, 0 ];
weaponName = ["fist","dagger","bow","staff",'spear','rapier','longsword'];
}
void load(String json,callback){
print("Beginning Parse");
dataTree = JSON.parse(json);
List objectList = dataTree["objects"];
mapsTree = dataTree["maps"];
print("Unpacking Game");
unpackObjects(objectList);
print("Data Parsed");
res.loadSplitImage("items.png",(List<html.ImageElement> imgs){
itemImages = imgs;
print("items loaded");
res.loadSplitImage("ui.png",(List<html.ImageElement> ui_imgs){
uiImages = ui_imgs;
res.loadImage("controls.png",(html.ImageElement img){
controlsImage = img;
print("Loading 'test' map");
loadMap("test",callback); //TODO 'test' should be variable
});
});
});
}
void loadMap(name,callback){
var map = currentMapTree = mapsTree[name];
unpackMapObjects(map["objects"]);
unpackMapPaths(map['paths']);
bottomTileManager = new TileManager("map_bottom");
topTileManager = new TileManager("map_top");
res.loadFile(map["collision-map"],(data){
fmtCollisionMap(data);
callback();
});
}
GameObject spawnObject(String type,Map props){
GameObject ob = classMap[type](props);
ob.type = type;
ob.tags.add(type);
ob.tags.add("uninit");
addTag(ob,type);
addTag(ob,"uninit");
addObject(ob);
return ob;
}
void unpackMapObjects(rol){//Raw Object List
for (var i = 0;i<rol.length;i++){
spawnObject(rol[i]["type"],rol[i]);
}
}
void unpackMapPaths(List<Map> lst){
lst.forEach((Map raw){
//Make vec2
List<Vec2> points = new List<Vec2>();
for (int i = 0;i<raw["point_x"].length;i++){
points.add(new Vec2(raw["point_x"][i],raw["point_y"][i]));
}
Path path;
paths.add(path = new Path(points[0],points[points.length-1],points,raw["startHouse"],raw["endHouse"]));
pathnodes.add(path.start);
pathnodes.add(path.end);
});
}
void unpackObjects(list){
for (int i = 0;i<list.length;i++){
switch(list[i]["type"]){
case "animation":
animationMap[list[i]["name"]] = new Animation(list[i]);
break;
case "avatar":
classMap[list[i]['name']] = (p){
Avatar a = new Avatar(list[i]["properties"]);
a.loadProperties(p);
return a;
};
break;
case "item":
classMap[list[i]['name']] = (p){
Item a = new Item(list[i]["properties"]);
a.loadProperties(p);
return a;
};
break;
case "node":
classMap[list[i]['name']] = (p){
GameObject a = new GameObject(list[i]["properties"],0,0);
a.loadProperties(p);
return a;
};
break;
default:
print("Type not found: ${list[i]['type']}");
break;
}
}
}
void fmtCollisionMap(String data){
collisionMap = new List<bool>();
List<String> chars = data.splitChars();
for (int cir = 0;cir<data.length * 4;cir++){
int ci = (cir/4).toInt();
int bseq = cir%4;
List<int> hexMap = binaryHexMap[chars[ci]];
if (hexMap!=null){
collisionMap.add((hexMap[bseq] == 1)?true:false);
}
}
map_width = sqrt(collisionMap.length).ceil().toInt();
print("Collision Map Loaded, Size : ${collisionMap.length}");
}
bool collisionAt(num x,num y){
x = (x/GRAPHIC_BLOCK_SIZE).toInt();
y = (y/GRAPHIC_BLOCK_SIZE+.5).toInt();
return collisionMap[x + y * map_width];
}
bool collisionAtVec2(Vec2 v){
return collisionAt(v.x,v.y);
}
void increaseDifficulty([int times = 0]){
ZOMBIE_WANDER_DISTANCE = (ZOMBIE_WANDER_DISTANCE * 1.5).toInt();
ZOMBIE_SPEED *= 1.1;
ZOMBIE_SPEED = ZOMBIE_SPEED<2?ZOMBIE_SPEED:2;
ZOMBIE_DAMAGE += 10 * ((75 - ZOMBIE_DAMAGE)/75);
ZOMBIE_ARMOR -= (ZOMBIE_ARMOR - .25)/10;
AGRO_DISTANCE -= (AGRO_DISTANCE - 512)/10;
zombie_max += 20;
return (times > 0) ? increaseDifficulty(times-1) : null;
}
void openMenu(String type){
print("Opening $type menu");
switch(type){
case "weapons":
List<Map> optionMap = [];
for (int nci = 0;nci<playerWeapons.length;nci++){
int i = nci;//For closure
if (!playerWeapons[i]){
optionMap.add({
"name":"${weaponName[i].splitChars()[0].toUpperCase().concat(weaponName[i].substring(1))} ${weaponCost[i]}c",
"func":()=> coin >= weaponCost[i] ? menuInterfaces.add(new MenuInterface("confirm",{
"text":"Would you like to buy the ${weaponName[i]} for ${weaponCost[i]}c?",
"func":()=>purchaseWeapon(i)
})) : menuInterfaces.add(new MenuInterface("broke",{"text":"You cannot afford the ${weaponName[i]}, come back when you have ${weaponCost[i]}c."}))
});
}
}
menuInterfaces.add(new MenuInterface("options",{
"options":optionMap
}));
break;
case "upgrades":
List<Map> optionMap = [];
for (int nci = 1;nci<playerWeapons.length;nci++){
int i = nci;//For closure
if (playerWeapons[i]){
optionMap.add({
"name":"${weaponName[i].splitChars()[0].toUpperCase().concat(weaponName[i].substring(1))} Damage ${weaponCost[i]}c",
"func":()=> coin >= weaponCost[i] ? menuInterfaces.add(new MenuInterface("confirm",{
"text":"Would you like to buy a ${weaponName[i]} damage upgrade for ${weaponCost[i]}c?",
"func":()=>purchaseUpgrade("damage",i)
})) : menuInterfaces.add(new MenuInterface("broke",{"text":"You cannot afford a ${weaponName[i]} damage upgrade, come back when you have ${weaponCost2[i]}c."}))
});
optionMap.add({
"name":"${weaponName[i].splitChars()[0].toUpperCase().concat(weaponName[i].substring(1))} Attack Rate ${weaponCost2[i]}c",
"func":()=> coin >= weaponCost2[i] ? menuInterfaces.add(new MenuInterface("confirm",{
"text":"Would you like to buy a ${weaponName[i]} damage upgrade for ${weaponCost2[i]}c?",
"func":()=>purchaseUpgrade("rate",i)
})) : menuInterfaces.add(new MenuInterface("broke",{"text":"You cannot afford a ${weaponName[i]} attack rate upgrade, come back when you have ${weaponCost2[i]}c."}))
});
}
}
menuInterfaces.add(new MenuInterface("options",{
"options":optionMap
}));
break;
case "health":
if (coin >= 300){
menuInterfaces.add(new MenuInterface("confirm",{
"text":"Would you like to buy a health upgrade for 300c?",
"func":(){
player_max_health+=50;
coin-=300;
}
}));
}else{
menuInterfaces.add(new MenuInterface("broke",{
"text":"Would you like to buy a health upgrade for 300c?"
}));
}
break;
case "guards":
if (coin >= guard_price){
menuInterfaces.add(new MenuInterface("confirm",{
"text":"Would you like to buy an additional patrol guard for ${guard_price}c?",
"func":(){
guard_total ++;
spawnGuard();
coin-=guard_price;
guard_price += 50;
}
}));
}else{
menuInterfaces.add(new MenuInterface("broke",{
"text":"You cannot afford an additional guard."
}));
}
break;
}
}
void purchaseWeapon(int weaponID){
coin -= weaponCost[weaponID];
playerWeapons[weaponID] = true;
//weaponCost becomes upgrade cost
weaponCost[weaponID] = (weaponCost[weaponID]/2).toInt();
weaponCost2[weaponID] = weaponCost[weaponID];
notify("Press E to change weapons");
}
void purchaseUpgrade(String type,int weaponID){
switch(type){
case "damage":
weaponDamage[weaponID] *= 1.5;
coin -= weaponCost[weaponID];
weaponCost[weaponID]*=2;
break;
case "rate":
weaponAttackTime[weaponID] -=2;
coin -= weaponCost2[weaponID];
weaponCost2[weaponID]*=2;
break;
}
}
void addObject(GameObject instance){
objects.add(instance);
onscene.add(instance);
}
List<PathNode> getClosePathNodes(Vec2 v){
List<PathNode> cnodes = new List<PathNode>();
pathnodes.forEach((PathNode node){
if (node.distanceTo(v) < 256){
cnodes.add(node);
}
});
return cnodes;
}
void spawnGuard(){
PathNode pn = pathnodes[(pathnodes.length * rng()).toInt()];
spawnObject("guard",{"x":pn.x,"y":pn.y});
}
void setGuardPath(Avatar guard){
PathNode destinationNode;
//Get next path point
List<PathNode> cnodes = getClosePathNodes(guard);
if (cnodes.length == 0){
//Find closest path node
num closestDistance = 9999;
PathNode closest;
world.pathnodes.forEach((PathNode node){
if (node.distanceTo(guard) < closestDistance){
closest = node;
}
});
destinationNode = closest;
}else{
destinationNode = cnodes[(rng() * cnodes.length).toInt()];
}
guard["path"] = destinationNode.path;
guard["destination"] = destinationNode.clone().add(guard["positionOffset"]);
guard["pathDirection"] = destinationNode.start ? 1 : -1;
guard["pathIndex"] = destinationNode.start ? 0 : destinationNode.path.points.length-1;
}
void startCycle(context){
//Set camera to player position
player = tags["player"][0];
if (difficultyMode > 0){
increaseDifficulty(difficultyMode);
}
if (intro){
player_animation = player.animation;
player.animation = new Animation({});
}
for (int i = 0;i<guard_total;i++){
spawnGuard();
}
player.removeTag("citizen");
sortScreenObjects();
camera.set(player.x,player.y);
paused = false;
event.onKeyPress.add((e){
if (event.key("E")==1 || event.key("Q") == 1){
currentWeapon = (currentWeapon+event.key("E")-event.key("Q"))%playerWeapons.length;
while(!playerWeapons[currentWeapon]){
currentWeapon = (currentWeapon+1)%playerWeapons.length;
}
if (currentWeapon!=0){
player.weaponAnimation = animationMap["weapon$currentWeapon"];
}else{
player.weaponAnimation = null;
}
player.damage = weaponDamage[currentWeapon];
player.attackTime = weaponAttackTime[currentWeapon];
player.attackType = weaponAttackTypes[currentWeapon];
notify("Using ${weaponName[currentWeapon]}");
}else if (event.key("F") == 1){
//TODO support firefox + opera
if (!html.document.webkitIsFullScreen){
html.document.body.webkitRequestFullscreen();
}else{
html.document.webkitCancelFullScreen();
}
}else if (event.key("Y") == 1 && (time > 7 && time < 21) ){
notify("Skipping right to night...");
final int max_iter = 10;
var interval;
interval = new Timer.repeating(new Duration(milliseconds:16),(Timer timer){
int i = 0;
while(time < 20 && i < max_iter){
update();
i++;
}
if (time > 20){
interval.cancel();
}
});
}else if (event.key("C") == 1){
//Open controls menu
controlsOpen = !controlsOpen;
}
});
if (DEBUG){
List<Vec2> debugPathNodes = new List<Vec2>();
event.onKeyPress.add((e){
if (event.key("space")==1 && menuInterfaces.length == 0){
String prompt(String s,[String def = ""]){
return html.window.prompt(s, def);
}
menuInterfaces.add(new MenuInterface("options",{
"options":[{
"name":"Place Spawn",
"func":(){
//What kind of spawn?
menuInterfaces.add(new MenuInterface("options",{
"options":[{
"name":"Zombie Node",
"func":() {
currentMapTree["objects"].add({
"type":"node",
"tag":["zombie-spawn"],
"x":player.x,
"y":player.y
});
}
},{
"name":"Custom Emitter",
"func":() => currentMapTree["objects"].add({
"type":"spawn",
"emit":prompt("Emit Type"),
"emit-properties":{
"tag":prompt("Emit Properties (',' delimited)").split(",")
},
"freq":int.parse(prompt("Freq (60 = 1 second)")),
"limit":int.parse(prompt("Limit")),
"x":player.x.toInt(),
"y":player.y.toInt()
})
}
]
}));
}
},{
"name":"Place Object",
"func":(){
menuInterfaces.add(new MenuInterface("options",{
"options":[
{
"name":"Custom Object",
"func":()=>currentMapTree["objects"].add({
"type":prompt("Type"),
"tag":prompt("Tags, delimit with ','").split(","),
"x":player.x.toInt(),
"y":player.y.toInt()
})
}
]
}));
}
},
{
"name":"Place Node",
"func": () => menuInterfaces.add(new MenuInterface("options",{
"options":[
{
"name":"House Node",
"func":() => currentMapTree["objects"].add({
"type":"node",
"tag":["house"],
"x":player.x.toInt(),
"y":player.y.toInt()
})
},
{
"name":"Path Node",
"func":() => debugPathNodes.add(player.clone())
},
{
"name":"End Path Node",
"func":() {
debugPathNodes.add(player.clone());
List<int> ax = new List<int>();
List<int> ay = new List<int>();
debugPathNodes.forEach((Vec2 node){
ax.add(node.x.toInt());
ay.add(node.y.toInt());
});
Vec2 end = debugPathNodes[debugPathNodes.length - 1];
Vec2 start = debugPathNodes[0];
bool endHouse = false;
bool startHouse = false;
tags["house"].forEach((GameObject house){
if (house.distanceTo(end) < 256){
endHouse = true;
}
if (house.distanceTo(start) < 256){
startHouse = true;
}
});
currentMapTree["paths"].add({
"type":"path",
"point_x":ax,
"point_y":ay,
"endHouse":endHouse,
"startHouse":startHouse
});
debugPathNodes = new List<Vec2>();
}
}
]
}))
},{
"name":"Advance time one hour",
"func":()=>time+=1
},
{
"name":"Toggle Debug Mode",
"func":(){DEBUG=!DEBUG;}
},
{
"name":"Simulate 2 hours",
"func":(){
for (int i = 0;i<dayLength/12;i++){
update();
}
}
},
{
"name":"Dump Trace",
"func":(){
print("Player : Health : ${player.health} : Damage : ${player.damage} : Armor : ${player.armor}");
print("Mouse : ${event.mouse_position.toString()}");
}
},
{
"name":"Game Over",
"func":()=>GameOver(game.context)
},
{
"name":"Prosperity",
"func":(){
giveCoin(player,2000);
totalPopulation += 200;
}
},
{
"name":"Test Menu",
"func":()=>menuInterfaces.add(new MenuInterface("confirm",{
"text":"Would you like to confirm?",
"func":(){
print("Confirmed");
}
}))
}
,{
"name":"Get JSON",
"func":() => print(html.window.open("javascript:document.body.innerHTML='${JSON.stringify(dataTree)}';", "JSON Data",'height=300,width=300'))
}]
}));
}
});
}
event.onClick.add((e){
rapid_clicks ++;
if (rapid_clicks>5){
notify("HOLD the mouse button to attack");
}
if (!intro){
controlsOpen = false;
}
//Do menu stuff
if (menuInterfaces.length != 0){
event.mouseDown = false;
}
for (int i = menuInterfaces.length-1;i>=0;i--){
if (menuInterfaces[i].clickAt(event.mouse_position.x,event.mouse_position.y)){
menuInterfaces.removeRange(i, 1);
}
}
//Check if player is near items
//TODO permatags
tags["item"].any((Item item){
if (player.distanceTo(item) < 32){
event.mouseDown = false;
notify("You found ${item.prop.containsKey('properName')?item['properName']:item.type}");
pickUpItem(item);
return true;
}
return false;
});
});
event.onKeyPress.add((e){
if (event.key("space") == 1){
tags["salesman"].forEach((Avatar a){
if (a.distanceTo(player)<128){
openMenu(a["menu"]);
}
});
}
});
bool cycle(a){
if (!paused){
html.window.requestAnimationFrame(cycle);
render(context);
}
}
var interval;
interval = new Timer.repeating(new Duration(milliseconds:16),(Timer timer){
if (!paused){
update();
if (event.key("T")==1){
update();
update();
update();
}
}else{
interval.cancel();
}
});
cycle(0);
}
void equipWeapon(Avatar avatar,int weaponID){
if (weaponID != 0){
avatar.weaponAnimation = animationMap["weapon$weaponID"];
}else{
avatar.weaponAnimation = null;
}
avatar.damage = weaponDamage[weaponID];
avatar.attackTime = weaponAttackTime[weaponID];
avatar.attackType = weaponAttackTypes[weaponID];
avatar.attackRadius = weaponAttackRadius[weaponID]/2;
}
html.ImageElement getItemImage(int index){
if (itemImages != null){
return itemImages[index];
}else{
return BLANK_IMAGE;
}
}
void pickUpItem(Item item){
print("TODO : MAKE PICK UP ITEM");
}
void sortScreenObjects(){
//Find objects that are onscreen in offscene and switch
if (offscene.length >= 1){
for (int iter = (rng() * offscene.length).toInt(),times = 0;times < offscene.length/16+1;iter++,times++){
int i = iter%offscene.length;
if (offscene[i].distanceTo(player) < RENDER_DISTANCE){
onscene.add(offscene[i]);
offscene.removeRange(i, 1);
}else if (offscene[i].markedForRemoval){
offscene.removeRange(i, 1);
}
}
}
//Find objects that are offscreen in onscene and switch
for (int iter = (rng() * onscene.length).toInt(),times = 0;times < onscene.length/16;iter++,times++){
int i = iter%onscene.length;
if (onscene[i].distanceTo(player) > RENDER_DISTANCE){
offscene.add(onscene[i]);
onscene.removeRange(i, 1);
}else if (onscene[i].markedForRemoval){
onscene.removeRange(i, 1);
}
}
//Objects have to be in the correct order for rendering to work properly;
//To avoid sorting all the objects every frame, we'll sort a few every frame,
//and hope they eventually line up right
//TODO revise this, maybe have a grid-based system
if (onscene.length >= 1){
for (int iter = 0;iter < 1 + onscene.length / 4;iter++){
int i0 = (rng() * onscene.length).toInt();
//It's more likely to switch places if i1 is near i0
int i1 = (i0 + rng() * 6 - 3).toInt() % onscene.length;
if (i0 > i1){
int a = i0;
i0 = i1;
i1 = a;
}
if (i0 != i1){
Vec2 a0 = onscene[i0];
Vec2 a1 = onscene[i1];
if (a0.y > a1.y){
onscene[i0] = a1;
onscene[i1] = a0;
}
}
}
}
}
void update(){
rpatCount += (rng() * 64).toInt();
if (rapid_clicks > 0 && rpat(30)){
rapid_clicks --;
}
if (multiplier_time <= 0){
if (multiplier <= 2){
multiplier = 1;
}else{
multiplier --;
multiplier_time = max_multiplier_time[multiplier];
}
}else{
multiplier_time --;
}
//Day/Night Cycle Events
if (night_mode && time>6.5 && time<21){//6:30 is wake up time
night_mode = false;
dayCount ++;
zombie_out = 0;
notify("Day $dayCount");
notify("Total Population : $totalPopulation");
if (totalPopulation<100){
if (totalPopulation<50){
notify("The population has fallen below 50");
GameOver(game.context);
}else{
notify("WARNING! If your population falls below 50 you lose!");
}
}
if (dayCount > 1){
//ON DAY INCREMENT
increaseDifficulty();
}
//Lost citizens become unlost during the day
tags["lost"].forEach((Avatar a){
a.removeTag("lost");
rmTag(a,"lost");
});
tags["following"].forEach((Avatar a){
switchTag(a,"following","wander");
a.say("Thank you!");
a.tags.add("nice");
addTag(a,"nice");
});
tags["zombie"].forEach((Avatar a){
a.markForRemoval();
});
}else if (!night_mode && (time > 21 || time < 6.5)){
night_mode = true;
//Send citizens into their houses
tags["wander"].forEach((Avatar citizen){
if (citizen.hasTag("ai") && !citizen.hasTag("lost") && citizen.hasTag("citizen")){
if (rng() < .9){
switchTag(citizen,"wander","homebound");
tagEvents["homebound"]["init"](citizen);
}else{
citizen.tags.add("lost");
addTag(citizen,"lost");
}
}
});
notify("Lost Citizens : ${tags['lost'].length}");
notify("Save as many as possible!");
}
if (!night_mode && time > 16 && rpat(5)){
Avatar citizen = tags["wander"][(tags["wander"].length * rng()).toInt()];
if (citizen.hasTag("ai") && !citizen.hasTag("lost") && citizen.hasTag("citizen")){
if (rng() < .9){
switchTag(citizen,"wander","homebound");
tagEvents["homebound"]["init"](citizen);
}else{
citizen.tags.add("lost");
addTag(citizen,"lost");
}
}
}
if(!night_mode && time < 12 && awakePopulation < totalPopulation){
//Get a random house
GameObject house = tags["house"][(tags["house"].length * rng()).toInt()];
//Spawn a citizen at the house
spawnObject("citizen",{
"tag":["friendly",(rng()<.5)?"wander":"traveler","ai"],
"x":house.x,
"y":house.y,
"home":house
});
awakePopulation ++;
}
//Release Zombies (if night)
if (night_mode){
if (time < 4 || time > 21){
if (zombie_out < zombie_max - 50 || (zombie_out < zombie_max && rpat(16))){
zombie_out ++;
List<GameObject> zs_list = tags["zombie-spawn"];
GameObject zs = zs_list[(zs_list.length * rng()).toInt()];
Avatar a = spawnObject("zombie",{"x":zs.x,"y":zs.y});
}
}else if (zombie_out > 0 && rpat(30)){
Avatar zom = tags["zombie"][(tags["zombie"].length * rng()).toInt()];
if (!zom.hasTag("nestbound")){
zom.removeTag("hostile");
rmTag(zom,"hostile");
zom.removeTag("hostile-wander");
rmTag(zom,"hostile-wander");
zom.tags.add("nestbound");
addTag(zom,"nestbound");
tagEvents["nestbound"]["init"](zom);
}
}
}
//Protips
if (rpat(2000)){
final List<String> protips = [
"You can switch weapons with E",
"Villagers tend to be meaner when you kill them",
"Villagers will be nicer if you keep saving them",
"Upgrades can be purchased for all weapons",
"Zombies grow stronger every day, equip yourself accordingly",
"You can press T to speed up time",
"Press the SHIFT key to sprint",
"You can purchase patrol guards to help keep villagers safe",
"Health upgrades can be found in the bottom left region of the map",
"Weapons can be purchased in the bottom right region of the map",
"All vendors are located in towns",
"Weapon upgrades are in the top right region of the map"
];
notify("Tip : ${protips[(protips.length * rng()).toInt()]}");
}
//Tag events
//The Lost
if (night_mode && rpat(60) && tags["lost"].length>0){
tags["lost"][(tags["lost"].length * rng()).toInt()].say(lostSpeech[(lostSpeech.length * rng()).toInt()]);
}
if (!intro){
//Player Tag
Vec2 inc = new Vec2(event.key("d") - event.key("a"),event.key("s") - event.key("w"));
inc.normalize().multiplyScalar(2 * ( 1 + 1 * event.key("shift")));
player.velocity.add(inc);
}else{
slideTime ++;
camera.x = slidex_pos[currentSlide] + slideTime * slide_dir[currentSlide];
camera.y = slidey_pos[currentSlide] ;
player.set(camera.x, camera.y);
if (slideTime >= 300){
slideTime = 0;
currentSlide++;
if (currentSlide>=slides.length){
intro = false;
notify("Day $dayCount");
notify("Total Population : $totalPopulation");
player.set(4793,4342);
player.animation = player_animation;
notify("Explore the island while it's safe!");
}
}
}
//Check if player is trying to attack
if (event.mouseDown){
if (player.currentAttackTime == 0){
player.currentFrame = weaponStartFrame[currentWeapon]*5;
}
player.attacking = true;
player.attackDirection = event.mouse_position.clone().subTo(SCREEN_WIDTH/2,SCREEN_HEIGHT/2).normalize();
}else{
player.currentAttackTime = 0;
player.attacking = false;
}
camera.x -= (camera.x - (player.x+player.velocity.x * 5))/5;
camera.y -= (camera.y - (player.y+player.velocity.y * 5))/5;
if (DEBUG){
camera.zoom += (event.key("up") - event.key("down"))/10.0;
}
camera.update();
//Uninit Tag (newly spawns)
tags["uninit"].forEach((GameObject ob){
ob.fireTagEvent("init");
ob.removeTag("uninit");
});
tags["uninit"] = new List<GameObject>();
//Update All Tags
for (String tag in tags.keys){
List<GameObject> lst = tags[tag];
for (int i = (rng() * lst.length).toInt(),iter = 0;iter<lst.length/16;iter++,i++){
int index = i%lst.length;
if (lst[index].markedForRemoval){
lst.removeRange(index, 1);
}
}
}
for (int i = (objects.length * rng()).toInt(),iter = 0;iter<objects.length/16;iter++,i++){
int index = i%objects.length;
if (objects[index].markedForRemoval){
objects.removeRange(index,1);
}
}
objects.forEach((GameObject g) => g.fireTagEvent("update"));
//Actor Tag
tags["actor"].forEach((Avatar actor){
if (actor.alive){
if (actor.attacking){
actor.currentAttackTime = actor.currentAttackTime + 1;
if (actor.currentAttackTime > actor.attackTime){
actor.currentAttackTime = 0;
//TODO use switch here
if (actor.attackType == 0){
//Melee Attack
List<Avatar> attacked = damageBubble(actor.clone().add(actor.attackDirection.clone().multiplyScalar(actor.attackRadius)),actor.attackRadius/2,actor.damage,actor.attackDirection);
for (int i = 0;i<attacked.length;i++){
if (!attacked[i].alive){
actor.fireTagEvent("kill");
}
}
if (actor.distanceTo(player) < 256){
audio.play("bump");
}
}else if (actor.attackType == 1){
//Ranged Attack
spawnObject("arrow",{
"direction":actor.attackDirection.clone().multiplyScalar(128),
"x":actor.x + actor.attackDirection.x * 32,
"y":actor.y + actor.attackDirection.y * 32,
"damage":actor.damage
});