-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmin.js
2548 lines (2092 loc) · 69.6 KB
/
min.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() {// `crunch: audit these for unused or underused functions
// HTML ==============================================================
var global = window
, doc = document
, $ = function () { return doc.querySelector.apply(doc, arguments); }
, reqAnimFrame = global.requestAnimationFrame || global.mozRequestAnimationFrame
, notify = function(msg) {
$('#game-message').textContent = msg;
}
, setLabel = function(msg) {
$('#game-label').textContent = msg;
}
// Math ==============================================================
, pi = Math.PI
, xy = function(x, y) { return {x:x, y:y}; }
, rth = function(r, th) { return {r:r, th:th}; } // r/theta circular coords
, squared = function(x) { return Math.pow(x, 2); }
, dist = function(p1, p2) {
return Math.sqrt(squared(p1.x - p2.x) + squared(p1.y - p2.y));
}
, midpoint = function(p1, p2) {
return xy(p1.x + (p2.x - p1.x)/2, p1.y + (p2.y - p1.y)/2);
}
, sin = Math.sin
, cos = Math.cos
, abs = Math.abs
, min = Math.min
, max = Math.max
, rnd = Math.random
, rnds = function(a, b) {
if (typeof b === 'undefined') { b = a; a = 0; }
return a + rnd() * (b - a);
}
, rnd_choice = function(array) {
return array[Math.floor(rnds(array.length))];
}
, probability = function(n) { return rnd() < n; }
, vec_add = function(p1, p2) {
return xy(p1.x + p2.x, p1.y + p2.y);
}
, vec_subtract = function(p1, p2) {
// `todo `crunch: not sure if i'll use this function more than once
return xy(p1.x - p2.x, p1.y - p2.y);
}
, vec_dot = function(p1, p2) {
// `CRUNCH: there's a lot of stuff that could make use of this
return xy(p1.x * p2.x, p1.y * p2.y);
}
, scale = function(p, s) {
return xy(p.x * s, p.y * s);
}
, polar2cart = function(p) {
return xy(
p.r * cos(p.th),
p.r * sin(p.th)
)
}
, cart2polar = function(p) { // `crunch not sure this is being used
return rth(
Math.sqrt(p.x*p.x + p.y*p.y),
Math.atan2(p.y, p.x)
)
}
, interpolate = function(x, p1, p2) { // Linear
if (!p1) { return xy(p2.x, p2.y); }
if (!p2) { return xy(p1.x, p1.y); }
if (p1.x === p2.x) { return xy(p1.x, p2.y); }
var f = (x - p1.x) / (p2.x - p1.x);
return xy(x, p1.y + f*(p2.y - p1.y));
}
, roundTo = function(x, n) {
return Math.round(x / n) * n;
}
, floorTo = function(x, n) {
return Math.floor(x / n) * n;
}
, ceilTo = function(x, n) {
return Math.ceil(x / n) * n;
}
, bounds = function(x, bounds) {
return max(min(x, max.apply(null, bounds)), min.apply(null, bounds));
}
, vcopy = function(p) {
return xy(p.x, p.y);
}
// `crunch: maybe elsewhere in the code could use this
, range = function(start, end, skip) {
skip = skip || 1;
var output_range = [];
for (var i = start; i < end; i += skip) {
output_range.push(i);
}
return output_range;
}
, perturb = function(value, amount) {
return value + rnds(-amount, amount);
}
// other stuff...
, resetify = function(item) { if (item.reset) item.reset(); }
, tickity = function(item) { if (item.tick && !item.skip_tick) item.tick(); }
, drawity = function(item) { if (item.draw) item.draw(); }
, null_function = function() {}
;
// All 2d points should be input as {x:xval, y:yval}
var draw = {
// Utility method - apply params only for a particular drawing
do: function(ctx, params, draw_function) {
params = params || {};
ctx.save();
for (var p in params) { ctx[p] = params[p]; }
ctx.beginPath();
draw_function();
if (params.cls) { ctx.closePath(); }
if (params.fll) { ctx.fill(); }
if (params.strk) { ctx.stroke(); }
ctx.restore();
},
shapeStyle: function(color, extra) {
var output = {fillStyle: color, strk: 0, fll: 1, cls: 1};
for (var s in extra) { output[s] = extra[s]; };
return output;
},
lineStyle: function(color, extra) {
var output = {strokeStyle: color, strk: 1, fll: 0, cls: 0, lineWidth: 0.1};
for (var s in extra) { output[s] = extra[s]; };
return output;
},
// Clear
clr: function(ctx, p0, p1) {
p0 = p0 || xy(0, 0);
p1 = p1 || xy(ctx.canvas.width, ctx.canvas.height);
ctx.clearRect(p0.x, p0.y, p1.x - p0.x, p1.y - p0.y);
},
clrp: function(ctx, p0, p1, alpha) {
// props to: http://stackoverflow.com/questions/16776665/canvas-clearrect-with-alpha
this.clr(global.fader.ctx, p0, p1);
global.fader.ctx.globalAlpha = alpha;
global.fader.ctx.drawImage(ctx.canvas, global.fader.size.x, global.fader.size.y, global.fader.ctx.canvas.width/game_scale.x, global.fader.ctx.canvas.height/game_scale.y);
this.clr(ctx, p0, p1);
ctx.drawImage(global.fader.canvas, global.fader.size.x, global.fader.size.y, ctx.canvas.width/game_scale.x, ctx.canvas.height/game_scale.y);
},
// Fill
f: function(ctx, params) {
params = params || this.shapeStyle("#fff");
this.do(ctx, params, function() {
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
})
},
// Line
l: function(ctx, p0, p1, params) {
params = params || this.lineStyle("#fff");
this.do(ctx, params, function() {
ctx.moveTo(p0.x, p0.y);
ctx.lineTo(p1.x, p1.y);
ctx.moveTo(p1.x, p1.y);
})
},
// Rectangle
r: function(ctx, p0, p1, params) {
params = params || this.shapeStyle("#fff");
this.do(ctx, params, function() {
ctx.rect(p0.x, p0.y, p1.x-p0.x, p1.y-p0.y);
})
},
// Circle
c: function(ctx, center, radius, params) {
this.a(ctx, center, radius, 0, 2*Math.PI, params);
},
// Arc
a: function(ctx, center, radius, angle1, angle2, params) {
params = params || this.lineStyle("#fff");
this.do(ctx, params, function() {
ctx.arc(center.x, center.y, radius, angle1, angle2, false);
})
},
// Bezier
// `crunch: the only time beziers are used, this function isn't called...
b: function(ctx, p0, p1, c0, c1, params) {
params = params || this.lineStyle("#fff");
this.do(ctx, params, function() {
ctx.moveTo(p0.x, p0.y);
ctx.bezierCurveTo(c0.x, c0.y, c1.x, c1.y, p1.x, p1.y);
});
},
// Polygon
// `todo convert pts to xy rather than array
p: function(ctx, pts, params) {
params = params || this.lineStyle("#fff");
this.do(ctx, params, function() {
ctx.moveTo(pts[0].x, pts[0].y);
pts.forEach(function(p) {
ctx.lineTo(p.x, p.y);
})
})
}
}
// All units in game units except for game_scale
// Game and camera settings
var game_scale = xy(30,30) // pixels -> game units conversion
, game_size = xy((global.innerWidth - 20)/game_scale.x, (global.innerHeight / game_scale.y))
, camera_margin = xy(4, 4)
, units_per_meter = 2 // for realistic size conversions
, world_size = [-25, 1000] // Horizontal bounds
, world_buffer = 10
, drone_upper_bound = game_size.y * 1.3
// Environment
, num_tower_clumps = 60
, num_towers_per_clump = 10
, tower_clump_width = 80
, tower_dome_probability = 0.1
, tower_slant_probability = 0.1
, tower_range = [world_size[0] + 20, world_size[1] - 20]
// Buildings
, door_size = xy(0.7, 1.2) // slightly larger than person
, person_frequency = 0.15 // people per game unit. not evenly distributed
, avg_people_per_building = 4 // AVERAGE
, avg_building_size = xy(10, 10)
, people_comeout_window = 8
// Dynamics
// *** Gravity estimate is very sensitive to FPS measurement
, min_dynamics_frame = 5
, gravAccel = function() { return xy(0, gameplay_frame < min_dynamics_frame ? 0 : -9.8 / 2 / bounds(avg_fps * avg_fps, [0, 1000])); } // 9.8 m/s^2 translated to units/frame^2
, droneTiltAccel = 0.001
, dronePowerAccel = 0.0001
, max_tilt = pi/4
, tilt_decay = 0.1
, sideways_velocity_bump = 0.07
, tiltOffset = function(depth) {
// `todo: customize this function with depth; then have successive keydown events (i.e. key being held down) increase the depth
return function(t) {
t += 1; // so that the zero thingy isn't triggered
t *= 0.2; // for scaling
return -max(0, 1.5*Math.exp(-t/2)*t/1.5);
}
}
// Lightning
, lightning_chance = 0.001 // Chance that lightning will start on any given frame
, lightning_chance_drone = 0.3 // Of each lightning strike, chance that it will hit the drone
, lightning_integrity_decrease = 0.3 // OUCH!
// Wind
, wind_probability = 1/400
, wind_storm_probability = 1/30 // `nb unused currently
, wind_influence_distance = 1
// People
, person_size = xy(0.3, 0.6)
, person_speed = 0.3
, person_control_rate = 0.05 // rate at which control level increases or drops
, min_person_resistance = 2 * person_control_rate
, person_interaction_window = 15
, interaction_distance = 1
, shoot_drone_window = 15
// Drone
, drone_body_size = xy(0.3, 0.2)
, drone_arm_size = xy(0.4, 0.05) // from center
, drone_blade_size = xy(0.5, 0.05)
, drone_drain_rate = 0.00005 // energy per frame
, drone_low_energy = 0.1
, drone_high_energy = 0.9
, drone_max_sideways_accel = 0.01
, dronw_x_bounds = [-20, 1000] // `todo fix 2nd one
// Bullets
, bullet_radius = 0.075
, bullet_hit_distance = 0.5
, bullet_speed = 1.8
, bullet_frequency = 50 // frames between a guard's bullets
, bullet_integrity_decrease = 0.05 // how much structural integrity does a bullet disrupt?
// Items
, battery_size = {x: 0.5, y: 0.3}
// Ideas
, idea_scale = 0.7
// HUD - positions are referenced from the upper right corner of game
, hud_dial_radius = 0.4
, bar_meter_size = xy(2, 0.25)
, energy_meter_position = xy(-6, -0.75)
, integrity_meter_position = xy(-10, -0.75)
, rpm_meter_position = xy(-1.5, -0.75)
// mouse
, mouse_hover_distance = 1
// Colors
, fadeout_color = '#eee'
, environment_color = '#1b1b1b'
, backgroundGradient = [
[1.0, '#777788'],
[0.4, '#999999'],
[0, '#cccccc']
]
, awesome_glow_color = '#fff'
, fog_color = '#fff'
, tower_color1 = '#666366'
, tower_color2 = '#555255'
, building_color = '#3E373E'
, door_color = '#636666'
, person_color = '#000'
, controlled_person_color = '#000'
, drone_color = '#000'
, drone_signal_color = '#9eb'
, bullet_color = '#eee'
, battery_color = "#000"
, idea_color = "#ddd"
, hud_color = '#445'
, hud_color_dark = '#aab'
, hud_red = '#811'
, hud_green = '#161'
, hud_text = '#112'
, wind_colors = [
// color, linewidth, alpha
['#ddd', 0.3, 0.05],
// ['#ddd', 0.2, 0.05],
['#fff', 0.1, 0.05]
]
;
// `crunch remove this from the css I suppose
$("#game-message").style.color = hud_text;
$("body").style.color = fadeout_color;
$("#game-intro").style.color = fadeout_color;
// SETUP =============================================================
function Layer(selector, size, scale) {
this.canvas = $(selector);
this.ctx = this.canvas.getContext('2d');
this.canvas.setAttribute("width", size.x * scale.x);
this.canvas.setAttribute("height", size.y * scale.y);
this.origin = xy(0, 0);
this.size = size;
this.scale = scale;
// x/y grid, origin at lower left corner. Positive is up and rightwards
// note: it will move left/right as the player moves camera
this.ctx.setTransform(scale.x, 0, 0, -scale.y, 0, size.y * scale.y);
this.ctx.lineWidth = 0;
this.clear = function() {
draw.clr(this.ctx, this.origin, xy(this.origin.x + this.size.x, this.origin.y + this.size.y));
}
this.clearPartial = function(alpha) {
draw.clrp(this.ctx, this.origin, xy(this.origin.x + this.size.x, this.origin.y + this.size.y), alpha);
}
this.moveBy = function(p) {
p = this.transCoords(p);
this.ctx.translate(-p.x, -p.y);
this.origin = vec_add(this.origin, p);
}
// Translate from global game units into this layer's units
this.transCoords = function(p) {
return xy(
p.x * this.scale.x / game_scale.x,
p.y * this.scale.y / game_scale.y
);
}
}
var Camera = {
tick: function() {
this.focusOnPlayerDrone();
},
moveBy: function(p) {
game_origin = vec_add(game_origin, p);
global.fader.moveBy(p);
global.bg1.moveBy(p);
global.bg2.moveBy(p);
global.stage.moveBy(p);
global.windlayer.moveBy(p);
environment.redraw_bg = true;
Player.tutorial.has_scrolled = true;
},
focusOnPlayerDrone: function() {
var dx = Player.drone.p.x - game_origin.x, dy = Player.drone.p.y - game_origin.y;
if (dx < camera_margin.x) { this.moveBy(xy(dx - camera_margin.x, 0)); }
if ((game_size.x - dx) < camera_margin.x) { this.moveBy(xy(camera_margin.x - (game_size.x - dx), 0)); }
}
}
global.game_origin = xy(0, 0);
global.fader = new Layer("#fader", game_size, game_scale);
global.bg1 = new Layer("#game_background1", scale(game_size, 1/0.9), scale(game_scale, 0.9));
global.bg2 = new Layer("#game_background2", scale(game_size, 1/0.95), scale(game_scale, 0.95));
global.stage = new Layer("#game_stage", game_size, game_scale);
global.windlayer = new Layer("#game_wind", game_size, game_scale); // this one will fade out slowly
global.overlay = new Layer("#game_overlay", game_size, game_scale);
global.introimg = new Layer("#intro-img", game_size, game_scale);
// this is the container for all the layers
$("#game-layers").style.height = (game_size.y * game_scale.y) + "px";
// `crunch: that constructor is a mess, ha!
var Platform = function(origin, xres, xrange, ypoints, thickness) {
this.origin = origin; // this is an xy position
this.y0 = origin.y;
this.xres = xres;
this.xres_offset = xrange[0] % xres;
this.xrange = xrange;
this.y = ypoints;
this.thickness = thickness;
this.yAt = function(x) {
return this.pointAt(x).y;
}
this.pointAt = function(x) {
x = bounds(x, [this.xrange[0], this.xrange[1]]);
var x1 = floorTo(x - this.xres_offset, this.xres) + this.xres_offset;
var x2 = ceilTo(x - this.xres_offset, this.xres) + this.xres_offset;
return interpolate(x,
xy(x1, this.y[x1]),
xy(x2, this.y[x2])
);
};
this.getMin = function(x1, x2) {
x1 = floorTo(x1 - this.xres_offset, this.xres) + this.xres_offset;
x2 = ceilTo(x2 - this.xres_offset, this.xres) + this.xres_offset;
var platform = this;
return min.apply(null, range(x1, x2 + 1, platform.xres).map(function(x) { return platform.y[x]; }))
};
this.getPolygon = function(thickness) {
var pts = [];
pts.push(xy(this.xrange[0], this.y0 - thickness));
for (var x = this.xrange[0]; x <= this.xrange[1]; x += this.xres) {
pts.push(xy(x, this.y[x]));
}
pts.push(xy(this.xrange[1], this.y0 - thickness));
return pts;
};
this.pts = this.getPolygon(this.thickness);
this.drawRepr = function(style) {
draw.p(stage.ctx, this.pts, style);
}
};
// Make a simple two-point platform
// `crunch: this might not be really necessary
// origin is the lower left corner
function makePlatform(origin, size) {
var y = {};
y[origin.x] = origin.y + size.y;
y[origin.x + size.x] = origin.y + size.y;
return new Platform(xy(origin.x, origin.y + size.y), size.x, [origin.x, origin.x + size.x], y, size.y);
}
// Buildings:
// (a) exist on other platforms (like the ground)
// (b) provide more platforms (like their roof) - NOT FULLY DECIDED/IMPLEMENTED - `todo `decide
// (c) can store people inside
// (d) have a doorway to admit people
// position p is the building's center
global.buildings = []; // index of all buildings in game
function Building(x0, size, platform) {
this.container_platform = platform || environment.ground;
this.p = xy(
x0,
this.container_platform.getMin(x0, x0 + size.y)
)
this.size = size; // xy of width and height
this.platforms = [];
this.people = [];
this.emptied = false;
this.door_p = vec_add(this.p, xy(door_size.x + rnd() * (this.size.x - 2*door_size.x), 0));
this.__proto__.setupPlatform.call(this, makePlatform(this.p, this.size));
global.buildings.push(this);
this.peopleCounts = {};
}
Building.prototype = {
// peopleCounts: maps person role -> number of people
prepopulate: function(peopleCounts) {
peopleCounts = peopleCounts || this.peopleCounts;
for (var roleName in peopleCounts) {
var role = roles[roleName];
for (var i = 0; i < peopleCounts[roleName]; i++) {
var p = (new Person()).init({platform: this, role: role});
this.personEnter(p);
addToLoop('foreground1', p);
}
}
},
tick: function() {
if (!this.emptied && dist(Player.drone.p, this.p) < people_comeout_window) {
this.everyoneExits();
}
},
draw: function() {
this.platforms[0].drawRepr(draw.shapeStyle(building_color));
draw.r(stage.ctx, this.door_p, vec_add(this.door_p, door_size), draw.shapeStyle(door_color));
},
setupPlatform: function(platform) {
this.platforms.push(platform);
// `todo: a way for people to access the platform
},
personEnter: function(person) {
person.hidden = true;
person.platform = this;
this.people.push(person);
},
personExit: function() {
if (this.people.length === 0) { return; }
var person = this.people.shift(); // take first person
person.hidden = false;
person.platform = this.container_platform;
return person;
},
everyoneExits: function(direction) {
for (var i = 0; i < this.people.length; i++) {
var building = this;
scheduleEvent(i*50, function() {
var dir = direction || rnds(-1, 1)
building.personExit().v = xy(dir * perturb(0.1, 0.02), 0);
})
}
this.emptied = true;
},
// make it function like a platform
pointAt: function() { return xy(this.door_p.x + door_size.x/2, this.door_p.y); },
yAt: function() { return this.door_p.y; }
}
// ENVIRONMENT =======================================================
var environment = {
ground: new Platform(xy(world_size[0], 4), 1, world_size, {}),
pts: [],
towers: [], // Towers in the background skyline represented by [x, width, height]
buildings: [], // buildings in the foreground which hold people
redraw_bg: false,
// Game loop
reset: function() {
stage.clear();
overlay.clear();
windlayer.clearPartial(0.95);
if (this.redraw_bg || gameplay_frame === 0) {
bg2.clear();
// Background
// (even though this is drawing-related, it needs to come before anything else)
var grd = bg1.ctx.createLinearGradient(0, 0, 0, bg1.size.y * 1.2);
backgroundGradient.forEach(function(params) {
grd.addColorStop.apply(grd, params);
})
draw.r(bg1.ctx, bg1.origin, xy(bg1.origin.x + bg1.size.x, bg1.origin.y + bg1.size.y), draw.shapeStyle(grd));
// Draw towers (decorative only for now)
// (subtract 0.5 so that there's no gap betw ground and tower. `temp)
this.towers.forEach(this.drawTower);
}
this.redraw_bg = false;
},
tick: function() {},
draw: function() {
// Ground
var fill = draw.shapeStyle(environment_color);
draw.p(stage.ctx, this.pts, fill);
this.drawBoundaryFog();
},
drawBoundaryFog: function() {
var p1 = xy(world_size[0] - 50, 0),
p2 = xy(world_size[0] + 50, game_size.y),
p3 = xy(world_size[1] + 50, 0),
p4 = xy(world_size[1] - 50, game_size.y);
var grd1 = stage.ctx.createLinearGradient(p1.x, 0, p2.x, 0);
var grd2 = stage.ctx.createLinearGradient(p3.x, 0, p4.x, 0);
grd1.addColorStop(0.5, 'white');
grd1.addColorStop(1, 'rgba(0, 0, 0, 0)');
grd2.addColorStop(0.5, 'white');
grd2.addColorStop(1, 'rgba(0, 0, 0, 0)');
draw.r(stage.ctx, p1, p2, draw.shapeStyle(grd1));
draw.r(stage.ctx, p3, p4, draw.shapeStyle(grd2));
},
drawTower: function(tower) {
var x1 = tower.x - tower.w/2;
var x2 = tower.x + tower.w/2;
var y0 = min(environment.ground.pointAt(x1).y, environment.ground.pointAt(x2).y);
var fill = draw.shapeStyle(tower.color);
draw.r(tower.ctx,
xy(x1, y0 - 0.5),
xy(x2, y0 + tower.h),
fill
)
if (tower.dome) {
draw.c(tower.ctx,
xy(tower.x, y0 + tower.h),
tower.w/2 * 0.8,
fill
)
}
if (tower.slant) {
var h = y0 + tower.h - 0.1;
var r1 = 0.9 * tower.w/2;
var r2 = r1 * tower.slant_ratio;
var p0 = xy(tower.x, y0 + tower.h)
draw.p(tower.ctx,
[
xy(tower.x - r1, h),
xy(tower.x + r1, h),
xy(tower.x, h + r2),
],
fill
)
}
},
generate: function() {
this.pts.push(xy(this.ground.xrange[0], 0));
var terrain = this.generateTerrainFunction();
for (var x = this.ground.xrange[0]; x < this.ground.xrange[1]; x += this.ground.xres) {
this.ground.y[x] = this.ground.y0 + terrain(x);
this.pts.push(xy(x, this.ground.y[x]));
}
this.pts.push(xy(this.ground.xrange[1],0));
for (var i = 0; i < num_tower_clumps; i++) {
this.generateTowerClump();
}
this.generatePeopleBuildings();
},
generateTowerClump: function() {
var x0 = rnds.apply(global, tower_range);
var n = num_towers_per_clump + rnds(-3, 3);
for (var i = 0; i < n; i++) {
var t = {
x: rnds(x0 - tower_clump_width/2, x0 + tower_clump_width/2),
w: rnds(4, 7),
h: rnds(5, 22),
ctx: rnd_choice([bg1.ctx, bg2.ctx])
};
t.slant = probability(tower_dome_probability);
if (t.slant) { t.slant_ratio = rnds(1.2, 1.5); }
t.dome = !t.slant && probability(tower_slant_probability);
t.ctx = (t.h > 18) ? bg1.ctx : bg2.ctx;
t.color = (t.h > 18) ? tower_color1 : tower_color2;
this.towers.push(t);
}
},
generateTerrainFunction: function() {
var mfp = function(m, f, p) { return {m:m, f:f, p:p}; } // magnitude, frequency, phase
var frequencies = [];
for (var i = 0; i < 10; i++) {
var f = 1/rnds(1, 5);
frequencies.push(mfp(f, 1/(f*100), rnds(0, 100)));
}
// some lower-frequency rolling
for (var i = 0; i < 10; i++) {
var f = 1/rnds(20, 40);
frequencies.push(mfp(f, 1/(f*100), rnds(0, 100)));
}
return function(x) {
var y = 0;
frequencies.forEach(function(f) {
y += f.m * sin(f.f*x + f.p + rnds(0, 0.05));
})
return y;
}
},
// `crunch
generatePeopleBuildings: function() {
var num_people = person_frequency * (world_size[1] - world_size[0]);
var num_buildings = num_people / avg_people_per_building;
var avg_building_spacing = (world_size[1] - world_size[0]) / num_buildings;
// building positions should be evenly distributed
// ... but perturbed a little bit
// Also, don't generate a building in the vicinity of the drone spawn
var buildings = range(game_size.x * 2, world_size[1] - world_buffer, avg_building_spacing)
.forEach(function(pos) {
var b = new Building(
perturb(pos, 10),
xy(perturb(10, 4), perturb(12, 4)) // `temp size. it should depend on number of people
);
b.peopleCounts = {normal: avg_people_per_building};
environment.buildings.push(b);
})
}
}
// Each idea is global; person objects have refs to the same idea object
// Ideas are not included in the game loop
function Idea(name, options) {
options = options || {};
this.name = name;
// This drawing method will be drawn right above the people talking about it
// arguments: p, scale, style
this.drawRepr = options.draw || null_function;
}
// ACTORS ============================================================
// they move around
// ** parent object
function Actor(p) {
this.p = p || xy(0, 0);
this.v = xy(0, 0);
this.gravity = false;
this.platform = environment.ground;
this.stay_on_platform = false;
this.tick = function() {
this.p.x += this.v.x;
this.p.y += this.v.y;
if (this.gravity) {
this.v = vec_add(this.v, gravAccel());
}
// Ground collision
var y0 = this.platform.yAt(this.p.x);
if (this.p.y < y0) {
this.p.y = y0;
// Don't do this every frame so that actor doesn't get stuck
this.v.y = max(this.v.y, 0);
// this.color = 'red';
}
if (this.stay_on_platform) {
// Set y coordinate to be the platform's y coordinate
this.p =this.platform.pointAt(this.p.x);
}
this.handleBehavior();
}
// Behavior stuff ============================
this.behaviors = {
idle: function() {
// do nothing
return;
}
}
this.current_behavior = 'idle';
this.current_behavior_timeleft = -1;
this.current_behavior_params = {};
this.handleBehavior = function() {
this.current_behavior_timeleft -= 1;
var start_behavior = false;
if (this.current_behavior_timeleft < 0) {
this.switchBehavior();
start_behavior = true;
}
this.behaviors[this.current_behavior].call(this, start_behavior);
}
this.switchBehavior = function(new_behavior) {
// For now, choose another behavior at random
this.current_behavior = new_behavior || rnd_choice(Object.keys(this.behaviors));
this.current_behavior_timeleft = rnds(50, 300);
};
}
// PEOPLE ============================================================
function Person() {
var ctx = stage.ctx;
this.p = xy(0, 0);
this.color = person_color;
this.drone_distance = null; // only relevant when person is within the interaction window
this.inventory_item = null; // each person can only hold 1 thing at a time
this.resistance = rnd();
this.control_level = 0; // the person is fully controlled when this exceeds the resistance measure
this.talking_dir = 0;
this.stay_on_platform = true;
this.role = roles.normal;
this.hidden = false;
this.init = function(properties) {
for (var prop in properties) {
this[prop] = properties[prop];
}
this.addIdea(global.ideas.smalltalk);
return this;
}
this.behaviors = {
idle: function(start) {
// do nothing
if (start) { this.v = xy(0, 0); }
return;
},
amble: function(start) {
if (Player.drone.person === this) { return; }
// Set a new velocity
if (start) { this.v = xy(rnds(-1, 1) / 20, 0); }
},
talk: function(start) {
var target_person = this.current_behavior_params.person;
if (!target_person) return;
var d = target_person.p.x - this.p.x;
if (abs(d) > interaction_distance) {
// move toward target person
this.v = xy(0.5/20, 0);
if (d < 0) { this.v.x *= -1; }
// delay starting the countdown until the person has been reached
this.current_behavior_timeleft += 1;
}
else {
// talk to the person
this.v = xy(0, 0);
this.talking_dir = abs(d)/d;
this.talking_idea = this.latest_idea;
target_person.addIdea(this.talking_idea);
}
}
}
this.switchBehavior = function(new_behavior) {
if (!new_behavior) {
// Switch between walking and idle
new_behavior = this.current_behavior === 'amble' ? 'idle' : 'amble'
}
// For now, choose another behavior at random
this.current_behavior = new_behavior;
this.current_behavior_timeleft = rnds(50, 100);
};
this.talkTo = function(person) {
this.current_behavior_params = {person: person};
this.switchBehavior('talk');
};
this.talkToClosestPerson = function() {
this.talkTo(this.getClosestPerson());
}
// `crunch `crunch `crunch - this method is basically the same as all the other 'getClosestX' functions
// maybe put it in the Actor
this.getClosestPerson = function() {
// `todo `todo `todo!
return global.p3;
}
// Roles ======================================================
this.byRole = function(method) {
if (!(method in this.role)) { console.warn('Uh oh, person role does not have method:', method); return; }
this.role[method].apply(this);
}
// Game loop / drawing ========================================
this.reset = function() {
this.talking_dir = 0;
this.drone_distance = null;
if (abs(Player.drone.p.x - this.p.x) < person_interaction_window) {
close_people_per_tick.push(this);
this.drone_distance = dist(this.p, Player.drone.p);
}
}
this.tick = function() {
this.__proto__.tick.apply(this);
if (this.control_level < this.resistance && this.control_level > 0) {
// Decay the control level
this.control_level -= person_control_rate;
this.control_level = max(this.control_level, 0);
}
this.byRole('tick');
}
this.draw = function() {
if (this.hidden) { return; }
var dir = this.v.x;
this.drawRepr(this.p, 1.3, draw.shapeStyle(drone_signal_color, {globalAlpha: this.control_level * Player.drone.controlStrength(this)}), dir);
this.drawRepr(this.p, 1, draw.shapeStyle(this.color), dir);
if (this.talking_dir !== 0) {
this.drawSpeechSquiggles(this.talking_dir);
this.talking_idea.drawRepr(vec_add(this.p, xy(this.talking_dir * 0.5, 1.2)), idea_scale, draw.shapeStyle(idea_color), {freeze: true});
}
this.byRole('draw');
}
this.drawRepr = function(p, scale, fill, dir) {
// Dir should be negative (person facing leftwards), 0 (forwards), or positive (rightwards)
// `CRUNCH
dir = dir || 0;
var scaled_size = xy(scale * person_size.x, scale * person_size.y);
p = vec_add(p, xy(0, -(scaled_size.y - person_size.y)/2));
// for displaying the person walking left/right
var x1_offset_scale = (dir < 0 ? 1/3 : 1/2);
var x2_offset_scale = (dir > 0 ? 1/3 : 1/2);