-
Notifications
You must be signed in to change notification settings - Fork 6
/
kiigame.js
executable file
·1144 lines (997 loc) · 44.2 KB
/
kiigame.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
import Konva from 'konva';
import JSONGetter from './util/JSONGetter.js';
import LayerAdder from './view/stage/konvadata/LayerAdder.js';
import LayerChildAdder from './view/stage/konvadata/LayerChildAdder.js';
import SequencesBuilder from './view/sequence/konvadata/SequencesBuilder.js';
import SequenceBuilder from './view/sequence/konvadata/SequenceBuilder.js';
import DefaultInteractionResolver from './model/DefaultInteractionResolver.js';
import Interactions from './model/Interactions.js';
import HitRegionInitializer from './view/stage/HitRegionInitializer.js';
import HitRegionFilter from './view/stage/hitregion/HitRegionFilter.js';
import Intersection from './view/Intersection.js';
import VisibilityValidator from './view/intersection/VisibilityValidator.js';
import CategoryValidator from './view/intersection/CategoryValidator.js';
import Music from './view/Music.js';
import AudioFactory from './view/music/AudioFactory.js';
import Text from './model/Text.js';
// TODO: Move DI up
import "reflect-metadata";
import { container, TYPES } from "./inversify.config.js";
export class KiiGame {
constructor(
jsonGetter = null,
sequencesBuilder = null,
clickResolvers = [],
dragResolvers = [],
interactions = null,
hitRegionInitializer = null,
intersection = null,
music = null,
text = null
) {
this.jsonGetter = jsonGetter;
this.sequencesBuilder = sequencesBuilder;
this.clickResolvers = clickResolvers;
this.dragResolvers = dragResolvers;
this.interactions = interactions;
this.hitRegionInitializer = hitRegionInitializer;
this.intersection = intersection;
this.music = music;
this.text = text;
if (this.jsonGetter === null) {
this.jsonGetter = new JSONGetter();
}
if (this.sequencesBuilder === null) {
// TODO: Move DI up
const slideBuilder = container.get(TYPES.SlideBuilder);
this.sequencesBuilder = new SequencesBuilder(
new SequenceBuilder(
slideBuilder
)
);
}
if (this.clickResolvers.length == 0) {
this.clickResolvers.push(
new DefaultInteractionResolver('furniture'),
new DefaultInteractionResolver('item')
);
}
if (this.dragResolvers.length == 0) {
this.dragResolvers.push(
new DefaultInteractionResolver('furniture'),
new DefaultInteractionResolver('item')
);
}
if (this.interactions === null) {
this.interactions = new Interactions(
JSON.parse(this.getJSON('data/interactions.json'))
);
}
if (this.hitRegionInitializer === null) {
this.hitRegionInitializer = new HitRegionInitializer(
new HitRegionFilter([], ['Image'])
);
}
if (this.intersection === null) {
this.intersection = new Intersection(
[
new VisibilityValidator(),
new CategoryValidator()
]
);
}
if (this.music === null) {
this.music = new Music(
JSON.parse(this.getJSON('data/music.json')),
new AudioFactory()
);
}
if (this.text === null) {
this.text = new Text(
JSON.parse(this.getJSON('data/texts.json'))
);
}
// Alternative variable for `this` to allow reference even when it's shadowed
var self = this;
// List of items in the inventory. inventory_list.length gives the item amount.
this.inventory_list = [];
// Offset from left for drawing inventory items starting from proper position
this.offsetFromLeft = 50;
// How many items the inventory can show at a time (7 with current settings)
this.inventory_max = 7;
// The item number where the shown items start from
// (how many items from the beginning are not shown)
this.inventory_index = 0;
// Timeout event for showing character animation for certain duration
this.character_animation_timeout;
// Temporary location for inventory items if they need to be moved back to the location because of invalid interaction
this.dragStartX;
this.dragStartY;
// For limiting the amount of intersection checks
this.delayEnabled = false;
// For limiting the speed of inventory browsing when dragging an item
this.dragDelay = 500;
this.dragDelayEnabled = false;
// Menu
this.menu; // also accessed in latkazombit.js
// Track the currently shown menu
this.current_menu;
// The item dragged from the inventory
this.dragged_item;
// Intersection target (object below dragged item)
this.target;
// Animations
// Animation for fading the screen
this.fade_full;
// Animation for fading the room portion of the screen
this.fade_room;
// List of animated objects
this.animated_objects = [];
// List of character animations.
this.character_animations = []; // also accessed in latkazombit.js
// Timeout event for showing character animation for certain duration
this.character_animation_timeout;
// Default character animations
this.speak_animation;
this.idle_animation;
// Variable for saving the current room (for changing backgrounds and object layers)
this.current_layer;
this.current_background;
this.game_start_layer; // also accessed in latkazombit.js
this.start_layer; // also accessed in latkazombit.js
// List of animated objects
this.animated_objects = [];
// List of character animations.
this.character_animations = []; // also accessed in latkazombit.js
// Get jsons from the server
this.images_json = JSON.parse(this.getJSON('data/images.json'));
this.rooms_json = JSON.parse(this.getJSON('data/rooms.json'))['rooms'];
this.character_json = JSON.parse(this.getJSON('data/character.json'));
this.sequences_json = JSON.parse(this.getJSON('data/sequences.json'));
this.menu_json = JSON.parse(this.getJSON('data/menu.json'));
this.items_json = JSON.parse(this.getJSON('data/items.json'));
// Add rooms to images_json for stage building. Add them before the room
// fade layer to ensure correct draw order.
var stageLayerAdder = new LayerAdder();
this.images_json = stageLayerAdder.process(
this.images_json,
this.rooms_json,
'fade_layer_room'
);
// Build an array of all the sequences out of sequences_json and merge them to
// images_json for stage building.
var builtSequences = this.sequencesBuilder.build(this.sequences_json);
this.images_json = stageLayerAdder.process(
this.images_json,
builtSequences,
'start_layer_menu' // TODO: Use fade_layer_full ?
);
// Push items.json contents to correct layer.
var stageLayerChildAdder = new LayerChildAdder();
this.images_json = stageLayerChildAdder.add(
this.images_json,
this.items_json,
'inventory_item_cache'
);
// Push character animation frames to correct layer.
this.images_json = stageLayerChildAdder.add(
this.images_json,
this.character_json.frames,
'character_layer'
);
// Create stage and everything in it from json
this.images_json_text = JSON.stringify(this.images_json);
this.stage = Konva.Node.create(this.images_json_text, 'container');
// Define variables from stage for easier use
// Texts & layers
this.monologue = this.getObject("monologue");
this.character_speech_bubble = this.getObject("character_speech_bubble");
this.npc_monologue = this.getObject("npc_monologue");
this.npc_speech_bubble = this.getObject("npc_speech_bubble");
this.interaction_text = this.getObject("interaction_text");
this.inventory_layer = this.getObject("inventory_layer");
this.inventory_bar_layer = this.getObject("inventory_bar_layer");
this.character_layer = this.getObject("character_layer");
this.text_layer = this.getObject("text_layer");
this.fade_layer_full = this.getObject("fade_layer_full");
this.fade_layer_room = this.getObject("fade_layer_room");
// Scale background and UI elements
this.getObject("black_screen_full").size({width: this.stage.width(), height: this.stage.height()});
this.getObject("black_screen_room").size({width: this.stage.width(), height: this.stage.height() - 100});
this.getObject("inventory_bar").y(this.stage.height() - 100);
this.getObject("inventory_bar").width(this.stage.width());
// Animation for fading the screen
this.fade_full = new Konva.Tween({
node : this.fade_layer_full,
duration : 0.6,
opacity : 1
});
// Animation for fading the room portion of the screen
this.fade_room = new Konva.Tween({
node : this.fade_layer_room,
duration : 0.6,
opacity : 1
});
// Load up frames from json to the character animations array.
var animation_data = this.character_json.animations;
for (var i in animation_data) {
var frames = [];
for (var j in animation_data[i].frames) {
var frame = new Konva.Tween({
node: this.getObject(animation_data[i].frames[j].node),
duration: animation_data[i].frames[j].duration
});
frames.push(frame);
}
this.character_animations[animation_data[i].id] = frames;
}
// Set up onFinish functions for each frame to show the next frame. In the case
// of the last of the frames, show the first frame.
for (var i in this.character_animations) {
for (var j = 0; j < this.character_animations[i].length; j++) {
if (this.character_animations[i].length > j+1) {
this.character_animations[i][j].onFinish = function() {
// `this` refers to the character_animations object,
// `self` refers to the engine object
for (var k in self.character_animations) {
if (self.character_animations[k].indexOf(this) > -1) {
var animation = self.character_animations[k];
var frame_index = self.character_animations[k].indexOf(this);
this.node.hide();
animation[frame_index+1].node.show();
this.reset();
animation[frame_index+1].play();
}
}
}
} else {
this.character_animations[i][j].onFinish = function() {
for (var k in self.character_animations) {
if (self.character_animations[k].indexOf(this) > -1) {
var animation = self.character_animations[k];
this.node.hide();
animation[0].node.show();
this.reset();
animation[0].play();
}
}
}
}
}
}
// Default character animations
this.speak_animation = this.character_animations["speak"];
this.idle_animation = this.character_animations["idle"];
// Creating all image objects from json file based on their attributes
var imageData = this.stage.toObject();
for (var i = 0; i < imageData.children.length; i++) {
for (var j = 0; j < imageData.children[i].children.length; j++) {
if (imageData.children[i].children[j].className == 'Image') {
this.createObject(imageData.children[i].children[j].attrs);
var object_attrs = imageData.children[i].children[j].attrs;
if (object_attrs.animated === true) {
this.create_animation(this.getObject(object_attrs.id));
}
}
}
if (imageData.children[i].attrs.category == 'menu') {
this.create_menu_action(imageData.children[i]);
}
}
// On window load we create image hit regions for our items on object layers
window.onload = () => {
this.hitRegionInitializer.initHitRegions(this, this.stage);
this.readyStage();
};
// Mouse up and touch end events (picking up items from the environment
// Mouse click and tap events (examine items in the inventory)
this.inventory_layer.on('click tap', (event) => {
this.handle_click(event);
});
// Drag start events
this.stage.find('Image').on('dragstart', (event) => {
this.dragged_item = event.target;
this.inventoryDrag(this.dragged_item);
});
// While dragging events (use item on item or object)
this.stage.on('dragmove', (event) => {
this.dragged_item = event.target;
if (!this.delayEnabled) {
// Setting a small delay to not spam intersection check on every moved pixel
this.setDelay(10);
// Loop through all the items on the current object layer
for (var i = 0; i < this.current_layer.children.length; i++) {
var object = (this.current_layer.getChildren())[i];
if (object != undefined && object.getAttr('category') != 'room_background') {
// Break if still intersecting with the same target
if (this.target != null && this.intersection.check(this.dragged_item, this.target)) {
break;
} else if (this.intersection.check(this.dragged_item, object)) {
// If not, check for a new target
if (this.target != object) {
this.target = object;
}
break;
} else {
// No target, move on
this.target = null;
}
}
}
// If no intersecting targets were found on object layer, check the inventory
if (this.target == null) {
// Loop through all the items on the inventory layer
for (var i = 0; i < this.inventory_layer.children.length; i++) {
var object = (this.inventory_layer.getChildren())[i];
if (object != undefined) {
// Look for intersecting targets
if (this.intersection.check(this.dragged_item, object)) {
if (this.target != object) {
this.target = object;
}
break;
} else {
this.target = null;
}
}
}
}
// Next, check the inventory_bar_layer, if the item is dragged over the inventory arrows
if (this.target == null) {
var leftArrow = this.getObject("inventory_left_arrow");
var rightArrow = this.getObject("inventory_right_arrow");
if (!this.dragDelayEnabled) {
if (this.intersection.check(this.dragged_item, leftArrow)) {
this.dragDelayEnabled = true;
this.inventory_index--;
this.redrawInventory();
setTimeout(() => this.dragDelayEnabled = false, this.dragDelay);
} else if (this.intersection.check(this.dragged_item, rightArrow)) {
this.dragDelayEnabled = true;
this.inventory_index++;
this.redrawInventory();
setTimeout(() => this.dragDelayEnabled = false, this.dragDelay);
} else {
this.target = null;
}
}
this.clearText(this.interaction_text);
}
// If target is found, highlight it and show the interaction text
if (this.target != null) {
this.current_layer.getChildren().each((shape, i) => {
shape.shadowBlur(0);
});
this.inventory_layer.getChildren().each((shape, i) => {
shape.shadowBlur(0);
});
this.target.clearCache();
this.target.shadowColor('purple');
this.target.shadowOffset({x: 0, y: 0});
this.target.shadowBlur(20);
this.inventory_layer.draw();
this.interaction_text.text(this.text.getName(this.target.id()));
this.interaction_text.x(this.dragged_item.x() + (this.dragged_item.width() / 2));
this.interaction_text.y(this.dragged_item.y() - 30);
this.interaction_text.offset({
x : this.interaction_text.width() / 2
});
this.text_layer.draw();
} else {
// If no target, clear the texts and highlights
this.current_layer.getChildren().each((shape, i) => {
shape.shadowBlur(0);
});
this.inventory_layer.getChildren().each((shape, i) => {
shape.shadowBlur(0);
});
this.clearText(this.interaction_text);
}
this.current_layer.draw();
}
});
/// Stop character animations and clear monologue when clicked or touched
/// anywhere on the screen.
this.stage.on('touchstart mousedown', (event) => {
this.clearText(this.monologue);
this.clearText(this.npc_monologue);
this.stopCharacterAnimations();
});
/// Touch start and mouse down events (save the coordinates before dragging)
this.inventory_layer.on('touchstart mousedown', (event) => {
this.dragStartX = event.target.x();
this.dragStartY = event.target.y();
});
/// Inventory arrow clicking events
this.inventory_bar_layer.on('click tap', (event) => {
this.handle_click(event);
});
/// Drag end events for inventory items.
this.stage.find('Image').on('dragend', (event) => {
var dragged_item = event.target;
// If nothing's under the dragged item
if (this.target == null) {
dragged_item.x(this.dragStartX);
dragged_item.y(this.dragStartY);
}
// Look up the possible interaction from interactions.json.
else {
var target_category = this.target.getAttr('category');
var dragResolver = this.dragResolvers.filter(function(dragResolver) {
return dragResolver.getTargetCategory() == target_category;
}).pop();
if (dragResolver) {
this.handle_commands(dragResolver.resolveCommands(
this.interactions,
dragged_item.id(),
this.target.id(),
this.target.id()
));
}
}
// Check if dragged item's destroyed, if not, add it to inventory
if (dragged_item.isVisible()) {
this.inventoryAdd(dragged_item);
}
// Clearing the glow effects
this.current_layer.getChildren().each((shape, i) => {
shape.shadowBlur(0);
});
this.inventory_layer.getChildren().each((shape, i) => {
shape.shadowBlur(0);
});
// Clearing the texts
this.clearText(this.interaction_text);
this.redrawInventory();
});
// Set start layer
this.stage.getChildren().each((o) => {
if (o.getAttr('category') === 'room' && o.getAttr('start') === true) {
this.game_start_layer = o;
}
});
// Not using getObject (with its error messaging), because these are optional.
this.start_layer = this.stage.find("#start_layer")[0]; // TODO: get rid of start_layer
// The optional start layer has optional splash screen and optional start menu.
// TODO: Delay transition to game_start_layer?
if (this.stage.find("#start_layer")[0] != null) {
this.current_background = 'start_layer';
this.current_layer = this.start_layer;
if (this.stage.find('#splash_screen')[0] != null) {
this.stage.find('#splash_screen')[0].on('tap click', (event) => {
this.stage.find('#splash_screen')[0].hide();
if (this.stage.find('#start_layer_menu')[0] != null) {
this.display_start_menu();
} else {
this.do_transition(this.game_start_layer.id());
}
});
} else { // no splash screen
if (this.stage.find('#start_layer_menu')[0] != null) {
this.display_start_menu();
} else {
// start layer without splash or menu?!
this.do_transition(this.game_start_layer.id());
}
}
} else {
// no start layer
this.do_transition(this.game_start_layer.id());
}
}
// Draw the stage and start animations
readyStage() {
this.stage.draw();
this.idle_animation[0].node.show();
this.idle_animation[0].play();
}
create_animation(object) {
var attrs = object.getAttr("animation");
var animation = new Konva.Tween({
node: object,
x: attrs.x ? object.x() + attrs.x : object.x(),
y: attrs.y ? object.y() + attrs.y : object.y(),
width: attrs.width ? object.width() - 15 : object.width(),
easing: Konva.Easings.EaseInOut,
duration: attrs.duration,
onFinish: () => {
animation.reverse();
setTimeout(() => {
animation.play();
}, attrs.duration * 1000);
}
});
this.animated_objects.push(animation);
}
/*
Create item actions such as "new game" for the given menu object
Menus may have certain kinds of actions: start_game, credits, main_menu
Other actions (such as "none") are regarded as non-functioning menu buttons
Object menu_image - the menu image object with the items inside
*/
create_menu_action(menu_image) {
var menu_object = this.menu_json[menu_image.attrs.id];
if (!menu_object) {
console.warn("Could not find menu.json entry for menu '", menu_image.attrs.id, "'");
return;
}
// Go through the menu items to bind their actions
for (var i = 0; i < menu_image.children.length; i++) {
var item_id = menu_image.children[i].attrs.id;
var item_action = menu_object.items[item_id];
var item = this.getObject(item_id);
// Don't override custom menu event listeners
if (item.eventListeners.click) {
continue;
}
if (item_action == "start_game") {
item.on('tap click', (event) => {
var resolver = new DefaultInteractionResolver();
this.handle_commands(resolver.resolveCommands(this.interactions, 'start_game'));
});
} else if (item_action == "credits") {
item.on('tap click', (event) => {
this.setMonologue(this.text.getText(event.target.id()));
});
}
}
}
// Display menu for the given layer
// string layerId - the ID of the layer we want to display the menu for
display_menu(layerId) {
this.hide_menu();
this.menu = this.menu_json[layerId] !== undefined ? this.getObject(this.menu_json[layerId]["menu"]) : false;
if (!this.menu) {
return;
}
this.menu.show()
this.current_menu = this.menu;
}
hide_menu() {
if (!this.current_menu) {
return;
}
this.menu.hide();
this.current_menu = null;
}
// Display the start menu including "click" to proceed image
display_start_menu() {
this.start_layer.show();
this.display_menu("start_layer");
this.character_layer.show();
this.inventory_bar_layer.show();
this.stage.draw();
this.music.playMusic('start_layer');
}
/// Plays a sequence defined in sequences.json
/// @param id The sequence id in sequences.json
/// @return The length of sequence in ms. Doesn't include the fade-in!
play_sequence(id) {
var delay = 700;
// Animation cycle for proper fading and drawing order
this.fade_full.reset();
this.fade_layer_full.show();
this.fade_full.play();
var old_layer = this.current_layer;
this.current_layer = this.getObject(id);
var sequence = this.sequences_json[this.current_layer.id()];
var final_fade_duration = sequence.transition_length != null ? sequence.transition_length : 0;
var sequenceCounter = 0;
var slidesTotal = 0;
var slide = null;
this.music.playMusic(id);
for (var i in sequence.slides) {
slidesTotal++;
var lastSlide = slide;
slide = this.getObject(sequence.slides[i].id);
var displaySlide = (i, slide, lastSlide) => {
setTimeout(() => {
this.current_layer.show();
old_layer.hide();
this.fade_layer_full.show();
this.hide_menu(); // So that the menu is hidden after first fadeout.
this.character_layer.hide();
this.inventory_bar_layer.hide();
this.inventory_layer.hide();
this.fade_full.play();
if (lastSlide) {
lastSlide.hide();
}
slide.show();
// Fade-in the slide
var slideFade = sequence.slides[i].do_fade;
if (slideFade === true) {
setTimeout(() => {
this.fade_full.reverse();
this.stage.draw();
}, 700);
} else {
// Immediately display the slide
this.fade_full.reset();
this.stage.draw();
}
sequenceCounter += 1;
}, delay);
}
displaySlide(i, slide, lastSlide);
delay = delay + sequence.slides[i].show_time;
};
// After last slide, do the final fade
if (final_fade_duration > 0) {
setTimeout(() => {
this.fade_full.tween.duration = final_fade_duration;
this.fade_full.play();
setTimeout(() => {
this.fade_full.reverse();
setTimeout(() => {
this.fade_layer_full.hide();
this.fade_full.tween.duration = 600; // reset to default
}, final_fade_duration);
}, final_fade_duration);
}, delay);
// Doesn't include the fade-in!
delay = delay + final_fade_duration;
}
// Return sequence delay
return delay;
}
/// Transition to a room.
/// @param room_id The id of the room to transition to.
/// @param fade_time The fade duration; if null, use a default.
do_transition(room_id, fade_time) {
// By default do fast fade
if (fade_time === null) {
fade_time = 700;
}
// Don't fade if duration is zero.
if (fade_time != 0) {
this.fade_room.tween.duration = fade_time;
this.fade_layer_room.show();
this.fade_room.play();
}
setTimeout(() => {
// Don't fade if duration is zero.
if (fade_time != 0) {
this.fade_room.reverse();
}
// may be null if no start_layer is defined
if (this.current_layer != null) {
this.current_layer.hide();
}
this.current_layer = this.getObject(room_id);
// Play the animations of the room
for (var i in this.animated_objects) {
if (this.animated_objects[i].node.parent.id() == this.current_layer.id()) {
this.animated_objects[i].play();
} else if (this.animated_objects[i].anim.isRunning()) {
this.animated_objects[i].anim.stop(); // Should this be .anim.stop() or .pause()?
}
}
this.current_layer.show();
this.inventory_layer.show();
this.inventory_bar_layer.show();
this.character_layer.show();
this.stage.draw();
setTimeout(() => {
this.fade_layer_room.hide();
this.music.playMusic(this.current_layer.id());
}, fade_time);
}, fade_time);
}
/// Handle click interactions on room objects, inventory items and inventory
/// arrows.
handle_click(event) {
var target = event.target;
var target_category = target.getAttr('category');
var clickResolver = this.clickResolvers.filter(function(clickResolver) {
return clickResolver.getTargetCategory() === target_category;
}).pop();
if (clickResolver) {
this.handle_commands(clickResolver.resolveCommands(
this.interactions,
target.id()
));
return;
}
// Inventory arrow buttons
if (target.getAttr('id') == 'inventory_left_arrow') {
if (target.getAttr('visible') == true) {
this.inventory_index--;
this.redrawInventory();
return;
}
}
if (target.getAttr('id') == 'inventory_right_arrow') {
if (target.getAttr('visible') == true) {
this.inventory_index++;
this.redrawInventory();
return;
}
}
}
/// Loop through a list of interaction commands and execute them with
/// handle_command, with timeout if specified.
handle_commands(commands) {
for (var i in commands) {
if (commands[i].timeout != null) {
((commands, i) => {
setTimeout(() => {
this.handle_command(commands[i]);
}, commands[i].timeout);
})(commands, i);
} else {
this.handle_command(commands[i]);
}
}
}
/// Handle each interaction. Check what command is coming in, and do the thing.
/// Timeouts are done in handle_commands. Order of commands in interactinos.json
/// can be important: for instance, monologue plays the speaking animation, so
/// play_character_animation should come after it, so that the speaking
/// animation is stopped and the defined animation plays, and not vice versa.
handle_command(command) {
if (command.command == "monologue") {
this.setMonologue(this.text.getText(command.textkey.object, command.textkey.string));
} else if (command.command == "inventory_add") {
this.inventoryAdd(this.getObject(command.item));
} else if (command.command == "inventory_remove") {
if (Array.isArray(command.item)) {
for (let item of command.item) {
this.inventoryRemove(this.getObject(item));
}
} else {
this.inventoryRemove(this.getObject(command.item));
}
} else if (command.command == "remove_object") {
this.removeObject(this.getObject(command.object));
} else if (command.command == "add_object") {
this.addObject(this.getObject(command.object));
} else if (command.command == "do_transition") {
this.do_transition(command.destination, command.length != null ? command.length : 700);
} else if (command.command == "play_character_animation") {
// Overrides default speak animation from setMonologue.
this.playCharacterAnimation(this.character_animations[command.animation], command.length);
} else if (command.command == "play_sequence") {
this.play_sequence(command.sequence);
} else if (command.command == "set_idle_animation") {
this.setIdleAnimation(command.animation_name);
} else if (command.command == "set_speak_animation") {
this.setSpeakAnimation(command.animation_name);
} else if (command.command == "npc_monologue") {
this.npcMonologue(
this.getObject(command.npc),
this.text.getText(command.textkey.object, command.textkey.string)
);
} else {
console.warn("Unknown interaction command " + command.command);
}
}
/// Get an object from stage by it's id. Gives an error message in console with
/// the looked up name if it is not found. Basically, a wrapper for
/// stage.find(id) with error messaging, helpful with typos in jsons,
/// and also gives some errors if an object required by the kiigame.js script
/// itself is missing.
/// @param object The name of the object to look up.
/// @return Returns the object if it's found, or null if it isn't.
getObject(id) {
var object = this.stage.find('#' + id)[0];
if (object == null) {
console.warn("Could not find object from stage with id " + id);
}
return object;
}
/// Add an object to the stage. Currently, this means setting its visibility
/// to true. // TODO: Add animations & related parts.
/// @param The object to be added.
addObject(object) {
object.clearCache();
object.show();
object.cache();
this.current_layer.draw();
}
/// Remove an object from stage. Called after interactions that remove objects.
/// The removed object is hidden. Handles animations.
/// @param object The object to be destroyed.
removeObject(object) {
this.removeAnimation(object.id());
object.hide();
this.current_layer.draw();
}
/// Remove an object from the list of animated objects.
/// @param id The id of the object to be de-animated.
removeAnimation(id) {
if (this.animated_objects.indexOf(id) > -1) {
this.animated_objects.splice(this.animated_objects.indexOf(id), 1);
}
}
// Clearing the given text
clearText(text) {
text.text("");
if (text.id() == 'monologue') {
this.character_speech_bubble.hide();
} else if (text.id() == 'npc_monologue') {
this.npc_speech_bubble.hide();
}
this.text_layer.draw();
}
/// Set NPC monologue text and position the NPC speech bubble to the desired
/// NPC.
/// @param npc The object in the stage that will have the speech bubble.
/// @param text The text to be shown in the speech bubble.
npcMonologue(npc, text) {
this.npc_monologue.setWidth('auto');
this.npc_speech_bubble.show();
this.npc_monologue.text(text);
var npc_tag = this.getObject("npc_tag");
if (npc.x() + npc.width() > (this.stage.width()/2)) {
npc_tag.pointerDirection("right");
if (this.npc_monologue.width() > npc.x() - 100) {
this.npc_monologue.width(npc.x() - 100);
}
this.npc_monologue.text(text);
this.npc_speech_bubble.x(npc.x());
} else {
npc_tag.pointerDirection("left");
if (this.npc_monologue.width() > this.stage.width() - (npc.x() + npc.width() + 100)) {
this.npc_monologue.width(this.stage.width() - (npc.x() + npc.width() + 100));
}
this.npc_monologue.text(text);
this.npc_speech_bubble.x(npc.x() + npc.width());
}
this.npc_speech_bubble.y(npc.y() + (npc.height()/3));
this.text_layer.draw();
}
/// Set monologue text.
/// @param text The text to be shown in the monologue bubble.
setMonologue(text) {
this.monologue.setWidth('auto');
this.character_speech_bubble.show();
this.monologue.text(text);
if (this.monologue.width() > 524) {
this.monologue.width(524);
this.monologue.text(text);
}
this.character_speech_bubble.y(this.stage.height() - 100 - 15 - this.monologue.height() / 2);
this.text_layer.draw();
this.playCharacterAnimation(this.speak_animation, 3000);
}
/// Play a character animation
/// @param animation The animation to play.
/// @param timeout The time in ms until the character returns to idle animation.
playCharacterAnimation(animation, timeout) {
this.stopCharacterAnimations();
for (var i in this.idle_animation) {
this.idle_animation[i].node.hide();
this.idle_animation[i].reset();
}
animation[0].node.show();
animation[0].play();
this.character_layer.draw();
clearTimeout(this.character_animation_timeout);
this.character_animation_timeout = setTimeout(() => {
this.stopCharacterAnimations();
}, timeout);