-
Notifications
You must be signed in to change notification settings - Fork 8
/
entities.js
1883 lines (1505 loc) · 67.6 KB
/
entities.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
/*This software is released under MIT License. Texts for license are listed below:
* Aventura do Saber , a educational fantasy action RPG
* Copyright (c) 2012-2013, ITSimples Games
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// *************************
// **** Entidade Heroi *****
// **** Hero entity *********
// *************************
var HeroEntity = me.ObjectEntity.extend({
//Construtor: test
init: function (x , y , settings){
//Definir propriedades do objecto heroi na classe em vez de no mapa:
settings.image="h_male01";
settings.spritewidth=32;
// Chamar o contrutor
this.parent(x, y , settings);
// console.log("TESTING BRANCH...");
//Debug Position
this.pos.x = this.posBeforeCollideX = startHero[0] * ads_tile_size;
this.pos.y = this.posBeforeCollideY = startHero[1] * ads_tile_size;
// This move
this.movemouse = false;
this.distancetotargetx = 0;
this.distancetotargety = 0;
this.xydivision = 0;
// Configurar velocidade do jogador
this.setVelocity(heroVelocity, heroVelocity);
// Configurar velocidade de travagem
// Valores maiores tempo de travagem menor
this.setFriction(0.5, 0.5);
// adjust the bounding box
this.updateColRect(4,24,20,23);
// this.updateColRect(-1,0,20,27);
// disable gravity
this.gravity = 0;
//Direção inicial
this.direction = 'down';
this.collidable= true;
//Config npc's animation
this.renderable.addAnimation("stand-down", [4]);
this.renderable.addAnimation("stand-left", [8]);
this.renderable.addAnimation("stand-up", [1]);
this.renderable.addAnimation("stand-right", [11]);
this.renderable.addAnimation("down", [3,4,5,4]);
this.renderable.addAnimation("left", [6,7,8]);
this.renderable.addAnimation("up", [0,1,2,1]);
this.renderable.addAnimation("right", [9,10,11]);
// Define point of click on mouse :
this.dest_point_X = 0;
this.dest_point_Y = 0;
// Viewport follow hero
me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
//TESTING....
this.makeOneTime = true;
//Check if is showing the inventory enable/disable
this.isShowInv = false;
//Check if is showing the inventory enable/disable
this.isShowHelp = false;
// DEBUG GET KEY TO HERO
// adsGame.Inventory.addItem( ads_items_data[14] );
// Set hero object type
this.type = 'HERO_OBJECT';
// Set to true if hero carries a weapon
this.heroCarryWeapon = false;
// Change Inventory and question layer position
this.layerPosition = "right";
// Keep this last direction to change only when hero change is direction
this.lastDirection = this.direction;
},
//Create weapon player position.
createWeapon : function ( weapon )
{
// console.log("Weapon:", weapon);
// Set global name of weapon
heroWeaponName = weapon.valor;
// Create Thrower with the weapon to hero
var throwerData = throwersData["thr" + weapon.valor];
this.heroWeapon = new throwersEntity( this.pos.x , this.pos.y , throwerData);
me.game.add( this.heroWeapon , 9 );
me.game.sort.defer();
// console.log("this.heroWeapon z: ", this.heroWeapon.z);
// Hero was a weapon now
this.heroCarryWeapon = true;
// Global hero don't have weapon anymore'
heroWeaponEnable = false;
},
//Create weapon player position.
removeWeapon : function removeWeapon( weaponName )
{
// Remove hero wepon
me.game.remove(this.heroWeapon);
// Remove weapon item from inventory
adsGame.Inventory.removeItem( weaponName );
// Hero wasn't a weapon now
this.heroCarryWeapon = false;
// Remove hero weapon slot
heroWeaponSlot = -1;
// Remove hero weapon name
heroWeaponName = "";
this.walkSound = false;
},
//Update player position.
update : function ()
{
// DEBUG MODE remove
if (DEBUG_MODE && this.makeOneTime && giveItemDebug !== undefined ){
ads_items_data[giveItemDebug].specialItem = true;
// Add item to hero
adsGame.Inventory.addItem(ads_items_data[giveItemDebug]);
this.makeOneTime = false;
}
// console.log("Hero Position X:" , this.pos.x , "Y: " , this.pos.y);
if (me.input.isKeyPressed('left'))
{
this.animationspeed = me.sys.fps / (me.sys.fps / 3);
this.vel.x = -this.accel.x * me.timer.tick;
this.renderable.setCurrentAnimation('left');
this.direction = 'left';
}
else if (me.input.isKeyPressed('right'))
{
this.animationspeed = me.sys.fps / (me.sys.fps / 3);
this.vel.x = this.accel.x * me.timer.tick;
this.renderable.setCurrentAnimation('right');
this.direction = 'right';
}
if (me.input.isKeyPressed('up'))
{
this.animationspeed = me.sys.fps / (me.sys.fps / 3);
this.vel.y = -this.accel.y * me.timer.tick;
this.renderable.setCurrentAnimation('up');
this.direction = 'up';
}
else if (me.input.isKeyPressed('down'))
{
this.animationspeed = me.sys.fps / (me.sys.fps / 3);
this.vel.y = this.accel.y * me.timer.tick;
this.renderable.setCurrentAnimation('down');
this.direction = 'down';
}
// Debug mode speed up player
if (me.input.isKeyPressed('ctrl')){
if (me.input.isKeyPressed('speedup')){
heroVelocity = heroVelocity + 1;
this.setVelocity(heroVelocity, heroVelocity);
me.game.HUD.updateItemValue('velocidade' , parseInt(1, 10));
}else if (me.input.isKeyPressed('speeddown')){
heroVelocity = heroVelocity - 1;
this.setVelocity(heroVelocity, heroVelocity);
me.game.HUD.updateItemValue('velocidade' , parseInt(-1, 10));
}
}
// If keypressed I then open the inventory
if (me.input.isKeyPressed('inventory'))
{
if (this.isShowInv){
adsGame.Inventory.hide();
// Disable showing
this.isShowInv = false;
}else{
adsGame.Inventory.show();
// Enable showing
this.isShowInv = true;
}
}
// If keypressed H then open Help window
if (me.input.isKeyPressed('helpWindow'))
{
//If finished window is opened then don't show help
if ( !adsGame.lvlFinishedWindow.isShowing() ) {
if (this.isShowHelp){
adsGame.helpwindow.hide();
// me.state.resume();
// Disable showing
this.isShowHelp = false;
}else{
adsGame.helpwindow.show();
me.state.pause();
me.event.subscribe(me.event.KEYDOWN, function watch_key(action) {
if (action == "helpWindow") {
me.state.resume();
}
});
// Enable showing
this.isShowHelp = true;
}
}
}
//Change inventory and question layer position
// if ( this.pos.x < 1300){
// console.log("Inventory on the right and question on the left.");
// $('#inventoryLayer').css({
// "top": "33px" ,
// "right": "0px"
// });
//
// this.layerPosition = "right";
// }else{
// console.log("Inventory on the left and question on the right.");
// $('#inventoryLayer').fadeOut( 1000 , function(){
// $('#inventoryLayer').css({
// "top": "33px" ,
// "right": "620px"
// });
// $('#inventoryLayer').fadeIn( 1000 );
// } );
//
// this.layerPosition = "left";
// }
// If player Stop set stand animationa
if (this.vel.y === 0 && this.vel.x === 0)
{
this.renderable.setCurrentAnimation('stand-' + this.direction);
}else{
// play a "herowalk" sound
if ( !this.walkSound ){
this.walkSound = true;
me.audio.play("herowalk",false, (function(){
this.walkSound = false;
}).bind(this) , 0.2);
}
}
// If question box is showing then stop the player
if (showingQuestion){
this.renderable.setCurrentAnimation('stand-' + this.direction);
this.vel.x = 0;
this.vel.y = 0;
}
// If hero carry a weapon ?
if (this.heroCarryWeapon){
// But this values on Json to work with any NPC that attack
switch (this.direction){
case "left":
addToPosX = this.heroWeapon.throwerData.posicaoAtirador.left[0];
addToPosY = this.heroWeapon.throwerData.posicaoAtirador.left[1];
// Flip weapon
this.heroWeapon.flipX(true);
break;
case "right":
addToPosX = this.heroWeapon.throwerData.posicaoAtirador.right[0];
addToPosY = this.heroWeapon.throwerData.posicaoAtirador.right[1];
this.heroWeapon.flipX(false);
break;
case "up":
addToPosX = this.heroWeapon.throwerData.posicaoAtirador.up[0];
addToPosY = this.heroWeapon.throwerData.posicaoAtirador.up[1];
this.heroWeapon.flipX(false);
break;
case "down":
addToPosX = this.heroWeapon.throwerData.posicaoAtirador.down[0];
addToPosY = this.heroWeapon.throwerData.posicaoAtirador.down[1];
this.heroWeapon.flipX(false);
// TODO Must refresh the animation
break;
}
this.heroWeapon.pos.x = (this.pos.x + addToPosX);
this.heroWeapon.pos.y = (this.pos.y + addToPosY);
// Make only when change direction to improve velocity
if ( this.direction !== this.lastDirection ) {
// Change Z index when NPC UP
if ( this.direction !== "down" && this.direction !== "left"){
this.heroWeapon.z = this.z - 1;
}else{
this.heroWeapon.z = this.z + 1;
}
me.game.sort();
// Keep this last direction to change only when hero change is direction
this.lastDirection = this.direction;
}
}
// update collision
var res = me.game.collide(this , true);
var self =this;
// Keep hero position before collide
if( res.length == 0 ){
// Save the last hero coordinates before collide with something
self.posBeforeCollideX = self.pos.x;
self.posBeforeCollideY = self.pos.y;
}
// If hero collide with more then one item at same time
var countCollideItems = 0;
$.each(res,(function(i,data){
if ( data.obj.type == "ITEM_OBJECT" ){
countCollideItems++;
}
}).bind(this));
// --- TESTING which OBJECT --- multiple collisions
$.each(res, function(i,data)
{
if (data){
// If more then one item is collide then do nothing hero must collide with only one item
if (data.obj.type == 'ITEM_OBJECT' && countCollideItems < 2) {
// console.log('Hero Collide with Item...' , res.obj.items_data);
// this.setCurrentAnimation('stand-' + this.direction);
// this.pos.x = this.posBeforeCollideX;
// this.pos.y = this.posBeforeCollideY;
// console.log ("****First Time:" , adsGame.Inventory.itemExists( data.obj.items_data ));
if ( (!fullInventory && adsGame.Inventory.itemExists( data.obj.items_data ) != -2 ) || (fullInventory &&
(adsGame.Inventory.itemExists( data.obj.items_data ) != -1 && adsGame.Inventory.itemExists( data.obj.items_data ) != -2) )
|| data.obj.items_data.specialItem || data.obj.items_data.categoria == 'ouro' || data.obj.items_data.categoria == 'conhecimento' ){
self.vel.x = 0;
self.vel.y = 0;
data.obj.getItem();
}else{
adsGame.Inventory.show();
}
}
if (data.obj.type == 'NPC_OBJECT') {
// NPC collide with hero - Don't change NPC direction otherwise NPC and hero stand back to back
// If NPC collide with hero and have opposite directions then NPC don't change his direction
if ( data.obj.heroChangeDirection )
data.obj.changeNPCDirection = false;
}
}
});
// If hero died
// console.log( "me.game.HUDgetItemValue(vida)" , me.game.HUD.getItemValue("vida"));
if ( me.game.HUD.getItemValue("vida") <= 0 ){
// console.log("Player is dead");
// Pause the game
me.state.pause();
// Show window game over
adsGame.heroDies.show()
}
// check & update player movement
updated = this.updateMovement();
// update animation
if (updated)
{
// Actualizar animação
this.parent(this);
}
return updated;
}, // End update method
onDestroyEvent : function(){
// console.log("Hero was destroyed...");
// When hero was destroyed
//Reset hero global variables
setInitialHeroVariables();
}
});
// *****************************
// **** Fim Entidade Heroi ****
// *****************************
// *************************
// **** Entidade Item ****
// *************************
var ItemEntity = me.CollectableEntity.extend({
//Construtor:
init: function (x , y , settings , items_data){
// Chamar o contrutor
this.parent(x, y , settings);
// Item data
this.items_data = items_data;
if (typeof this.items_data.specialItem !== 'undefined' && this.items_data.specialItem) {
this.specialItem = true;
}else{
this.specialItem = false;
}
// console.log ("Item name:", this.items_data.nome , " - Special Item:" , this.specialItem);
// La
adsQtnDataKeys = Object.keys(adsQtnData);
countQtn = adsQtnDataKeys.length;
// Random question number between 0 and number of question less one
// var rndQuestion = randomInt( 0 , (countQtn - 1) );
// this.rndQtnData = adsQtnData[adsQtnDataKeys[rndQuestion]];
this.rndQtnData = adsQtnData[adsQtnDataKeys[qstDone]];
qstDone++;
if ( qstDone == countQtn )
qstDone = 0;
this.type = 'ITEM_OBJECT';
//Change animation if is a special item or not
if (!this.specialItem) {
// Item sparkle animation
this.itemAnimation = new effect(
this.pos.x - 8 , this.pos.y - 8, // Coordinates
me.loader.getImage("sparkle"), // Image
40, 40, // Size
[0,1,2,3,4,5,6,7,8,9,10,11,12,13], //Animation sheet
30, // Speed between 0 - Slowest and 60 - fastest
true, // Repeat animation
100 // Wait between animations 10 milliseconds
);
}else{
// Item sparkle animation
this.itemAnimation = new effect(
this.pos.x - 8 , this.pos.y - 8 , // Coordinates
me.loader.getImage("questitem"), // Image
45, 45, // Size
[0,1,2,3,4,5,6,7,8], //Animation sheet
20, // Speed between 0 - Slowest and 60 - fastest
true,
0
);
}
me.game.add(this.itemAnimation, 6);
me.game.sort();
},
getItem : function ()
{
//When player collide with item Stop player and ask question
var player = adsGame.heroEntity();
// If the answer is correct then update HUD and remove item
heroAnswer = showQuestionLayer(this.items_data , this.rndQtnData);
if (heroAnswer != -1)
{
if ( heroAnswer == this.rndQtnData.correta){ // if hero correct answer
// me.game.HUD.updateItemValue(this.items_data.categoria, parseInt(this.items_data.valor));
//Keep data for all items found by the hero less gold and knowledge increment right away
if (this.items_data.categoria == 'ouro' ||
this.items_data.categoria == 'conhecimento'){
me.game.HUD.updateItemValue(this.items_data.categoria , parseInt(this.items_data.valor, 10));
}else{
adsGame.Inventory.addItem( this.items_data );
}
hideQuestionLayer('C');
}else if(heroAnswer != 0){ // if hero answer to the question but it's not the correct one
var valueRemoved = -(parseInt(this.items_data.valor,10));
//If is velocity then don't remove points
if (this.items_data.categoria != 'velocidade'){
if (this.items_data.categoria == 'vida'){
// play a "hitplayer" sound
me.audio.play("hithero", false , null , hitHeroVolume);
// let's flicker in case we loses health
player.renderable.flicker(25);
}
me.game.HUD.updateItemValue(this.items_data.categoria, valueRemoved);
}
hideQuestionLayer('W');
}else{ // If hero doesn't answer to the question
hideQuestionLayer('D');
}
//If correct answer and specialitem remove item - If not special item remove always the item
if ( (!this.specialItem) || (this.specialItem && heroAnswer == this.rndQtnData.correta) ){
// Remove Item
me.game.remove(this);
// Remove sparkle item animation
me.game.remove(this.itemAnimation);
}else{
// If is a Special item and the answer is not the correct
// then position hero to last position with no collition with item
player.pos.x = player.posBeforeCollideX;
player.pos.y = player.posBeforeCollideY;
// If remove helath then play hit sound and flicker player
if (this.items_data.remover == 'vida'){
// play a "hitplayer" sound
me.audio.play("hithero", false , null , hitHeroVolume);
// let's flicker in case we loses health
player.renderable.flicker(25);
}
// Remove special item value
var valueRemoved = -(parseInt(this.items_data.quantidade,10));
me.game.HUD.updateItemValue(this.items_data.remover, valueRemoved);
}
}
//Destroy player variable
player = undefined;
}
});
// **************************************
// **** Distribuir items pelo mapa ****
// **************************************
//me.InvisibleEntity has been removed, as following previous changes,
//this can now be achieved using a me.ObjectEntity without a renderable component.
var ItemSpawnEntity = me.ObjectEntity.extend({
//Construtor:
init: function(x, y, settings) {
this.parent(x, y, settings);
this.gravity = 0;
var item = [];
var count = 0;
//Create array to store coordinates data
var checkTriggersData = [];
var checknoItemsData = [];
var collision_layer = me.game.currentLevel.getLayerByName("collision");
var background_layer = me.game.currentLevel.getLayerByName("background");
//returns an array of all enumerable property names defined by a given object
var item_keys = Object.keys(ads_items_data);
//Improve this to not spwan items on triggers points
//Triggers Points
$.each(triggersData, function(i, data){
// create a array to store de tiles that belong to trigger
// create the array outside this cicle because don't repeat the same code several times'
var finalHeight = ( data.settings.height / 32 );
var finalWidth = ( data.settings.width / 32 );
// console.log("Trigger:", data);
// console.log("Width:", finalWidth);
// console.log("Height:", finalHeight);
for ( x = 0; x < finalWidth ; x++)
{
for ( y = 0; y < finalHeight ; y++)
{
//Store data coordinates
var triggersCoordinates = {};
triggersCoordinates.x = ( data.coordinates.x + x);
triggersCoordinates.y = ( data.coordinates.y + y);
// console.log("triggers data:", triggersCoordinates);
checkTriggersData.push(triggersCoordinates);
}
}
});
//noItemsData Points
$.each(noItemsData, function(i, data){
// create a array to store de tiles that belong to trigger
// create the array outside this cicle because don't repeat the same code several times'
var finalHeight = ( data.settings.height / 32 );
var finalWidth = ( data.settings.width / 32 );
for ( x = 0; x < finalWidth ; x++)
{
for ( y = 0; y < finalHeight ; y++)
{
//Store data coordinates
var noItemsCoordinates = {};
noItemsCoordinates.x = ( data.coordinates.x + x);
noItemsCoordinates.y = ( data.coordinates.y + y);
// console.log("triggers data:", triggersCoordinates);
checknoItemsData.push(noItemsCoordinates);
}
}
});
// parse all the collision layer tiles
for ( x = 0; x < collision_layer.cols; x++)
{
for ( y = 0; y < collision_layer.rows; y++)
{
var testTileCollision = collision_layer.layerData[x][y];
var testTileBackground = background_layer.layerData[x][y];
// If tile of layer collision is null then we can put an item
if (testTileCollision === null && testTileBackground !== null){
// Item probability
var item_probability = Number.prototype.random(0, itemLucky);
// Total of items
total_items = item_keys.length - 1;
// If is a mission item don't spawn
do{ // If mission item then random new item
//random a item
var randomNumber = Number.prototype.random(0, total_items);
var random_item = item_keys[randomNumber];
}while ( ads_items_data[random_item].categoria == "itemMissao" );
if ( item_probability == Math.round(itemLucky / 2) ){
//Test if not a trigger or special item or born hero
var isCollide = false;
// $.each(triggersData, function(i, data){
// if (data.coordinates.x == x && data.coordinates.y == y)
// isCollide = true;
// });
//Improve this to not spwan items on mission tiles
//special item
$.each(specialItemsData, function(i, data){
if (data.coordinates.x == x && data.coordinates.y == y){
isCollide = true;
}
});
// If is a trigger don't put object
$.each(checkTriggersData, function(i, data){
if (data.x == x && data.y == y){
isCollide = true;
// console.log("Collide with trigger tile!");
}
});
// If is a noitems don't put object
$.each(checknoItemsData, function(i, data){
if (data.x == x && data.y == y){
isCollide = true;
// console.log("Collide with noItems tile!");
}
});
//Hero born
if (x == startHero[0] && y == startHero[1])
isCollide = true;
// Not to spawn item with json criarinicio =false
if ( ads_items_data[random_item].criarinicio !== undefined && !ads_items_data[random_item].criarinicio){
isCollide = true;
}
if (!isCollide)
{
// Item Image
item[count] = new ItemEntity(parseInt(ads_tile_size*x ,10), parseInt(ads_tile_size*y ,10),
{image: ads_items_data[random_item].imagem.replace(".png",""),
spritewidth: 32, spriteheight: 32}, ads_items_data[random_item]);
count++;
// console.log("Populate Map... X:" + parseInt(32*x) +
// " Y:" + parseInt(32*y) +
// " dss Count:" + count + " Item: " + random_item);
}
}
}
}
}
// add items on layer 5
$.each(item, function(i, item){
me.game.add(item,5);
me.game.sort();
});
//Spawn special items
$.each(specialItemsData, function(i, dataSpecialItem){
$.each(ads_items_data, function(i, ads_item_data){
// console.log('dataSpecialItem.value: ' + dataSpecialItem.value + ' ads_item_data.valor: ' + ads_item_data.valor);
if ( dataSpecialItem.value == ads_item_data.valor)
{
ads_item_data.remover = dataSpecialItem.remover;
ads_item_data.removerNome = dataSpecialItem.removerNome;
ads_item_data.quantidade = dataSpecialItem.quantidade;
ads_item_data.specialItem = true;
item = new ItemEntity(parseInt(ads_tile_size*dataSpecialItem.coordinates.x , 10), parseInt(ads_tile_size*dataSpecialItem.coordinates.y ,10),
{image: ads_item_data.imagem.replace(".png",""),
spritewidth: 32, spriteheight: 32}, ads_item_data);
me.game.add(item,5);
me.game.sort();
}
});
});
}
});
// **************************************
// **** TRIGGER INVISIBLE ENTITY ****
// **************************************
//me.InvisibleEntity has been removed, as following previous changes,
//this can now be achieved using a me.ObjectEntity without a renderable component.
var TriggerEntity = me.ObjectEntity.extend({
//Constructor
init: function( x , y , settings , triggerData){
this.parent(x, y , settings );
this.collidable = true;
this.triggerData = triggerData;
// prepare data to message box
this.msgData = {};
this.msgData.msgImage = 'sprites/items/' + triggerData.imageName;
this.msgData.msgName = language.system.TRmessage;
this.msgData.msg = language.triggers[triggerData.message];
this.type = triggerData.type;
this.targX = triggerData.target.x;
this.targY = triggerData.target.y;
this.solution = this.triggerData.solution;
//add remove option
this.remove = this.triggerData.remove;
//check first time pull the trigger
this.oneTime = false;
//check one time for collision to trigger when leave trigger variable reseted
this.oneTimeCollide = false;
// Check if requirements are satisfied to pull the trigger default is true
this.pullTrigger = true;
//Get data from trigger new NPC
if(this.type == "NEW_NPC"){
//Get data that only exists on NEW_NPC trigger
this.npcName = triggerData.npcName;
//Get effect to rise the new NPC
this.appearEffect = adsNpcData[ this.npcName].appearEffect;
}
this.checkSolution = false;
this.isChecked = false;
// Create message box for object
this.message = new adsGame.Message();
//Update always
this.alwaysUpdate = false;
// Show message and play sound only one timw when hero does'nt have the door key
this.oneTimeSoundMessage = false;
// Check requirement if exists only one time
this.checkRequirementOne = false;
},
update : function (){
// Check collisions
var res = me.game.collide( this );
if( res ) {
if( res.obj.name == 'hero' ) {
// Verify if hero have the item only one time
if (!this.isChecked)
{
//Create variable to work for each ?!?!?!?!?
var solution = this.solution;
var checkSolution = false;
// Get index where hero have the key to remove that from the inventory
var itemIndex = null;
//Make it check one time only - Problem var checkSolution = false; have to go inside if doorobject
//check if hero have the Solution
$.each(heroItems, function(i,data)
{
//Check if array is undefined to avoid error (may have empty slots)
if (typeof data !== 'undefined'){
if (data.valor == solution){
// console.log('Hero have the key.', i);
checkSolution = true;
itemIndex = i;
}
}
});
this.checkSolution = checkSolution;
this.isChecked = true;
// console.log('Test times...' + this.checkSolution);
// console.log('Remove the item number : ' + itemIndex);
// If hero have the solution and if the solution is not a subcategoria weapon
// Remove item from inventory - Index + 1 Slot number
if (itemIndex !== null && heroItems[itemIndex].subcategoria !== "weapon"){
adsGame.Inventory.removeItem( 'Slot0' + (itemIndex + 1) );
}
}
// If trigger is a chest object
if (this.type == 'CHEST_OBJECT'){
var self = this;
if (this.checkSolution){
// Remove old chest to empty chest
var lowerObjects = me.game.currentLevel.getLayerByName("lower objects");
//Give tile number create a classe with good methods to the game
// console.log("Tile number:" , lowerObjects.getTileId(this.targX * 32, (this.targY + 3) * 32));
//Remove chest
lowerObjects.clearTile(this.targX , this.targY);
lowerObjects.clearTile(this.targX , this.targY + 1 );
//New upper door exploded
lowerObjects.setTile(this.targX , this.targY , 293);
lowerObjects.setTile(this.targX , this.targY + 1 , 294);
//Next Give Item
// Show inventory window if is not open
if (!adsGame.Inventory.isShowing){
adsGame.Inventory.show();
}
// If is a mission item then set as special item to go the rigth slot (Map items)
if (ads_items_data[this.triggerData.give].categoria == 'itemMissao'){
ads_items_data[this.triggerData.give].specialItem = true;
}
if ( this.triggerData.nomeSom !== undefined && this.triggerData.volumeEfeito !== undefined){
// play a "throwerSound" sound
me.audio.play( this.triggerData.nomeSom , false , null , this.triggerData.volumeEfeito );
}
// Add item to hero
adsGame.Inventory.addItem( ads_items_data[this.triggerData.give] );
//The hero open chest show a message to hero
if (!npcTalking){
this.msgData.msg = language.triggers[this.triggerData.messageOpen];
this.message.show(this.msgData , 10000);
// msgShowing = true;
// var tween = new me.Tween( { x: 0} )
// .to( { x: 1 }, 10000 ).onComplete(function(){
// self.message.hide();
//
// }).start();
// console.log("How many times...");
// Remove Trigger
me.game.remove(this);
}
this.checkSolution = false;
}else{
//The hero hasn't the item to open chest show a message to hero
if (!npcTalking){
this.message.show(this.msgData);
// msgShowing = true;
}
}
} // End chest object
// If trigger is a door object
if (this.type == 'DOOR_OBJECT'){
// Check solution only if requirement does't exist or is satisfied
if ( typeof this.triggerData.requirement !== "undefined" ){
// prepare data to message box
var msgDataReq = {};
msgDataReq.msgImage = 'sprites/information.png' ;
msgDataReq.msgName = language.system.TRmessage;
msgDataReq.msg = language.triggers[this.triggerData.requirementMsg];
if (typeof this.triggerData.requirement.salvarPrisao !== "undefined" && !this.checkRequirementOne ){
this.checkRequirementOne = true;
var self = this;
// var reqSavePrisionerLenght = Object.keys( this.triggerData.requirement.salvarPrisao ).length ;
var addAnd ="";
var isFree = false;
var allFree = true;
// play a "doorlockmessage" sound
me.audio.play("doorlockmessage");
$.each( this.triggerData.requirement.salvarPrisao, function( i , data ) {
// TODO - Must check if hero save the prisoners before
isFree = adsGame.prisonDoors.getPrisonDoorState( adsNpcData[data].prisao.numero );
// Not free
if ( !isFree ) {
// One prisoner is not free opss
allFree = false;
}
});
// If not all prisoners are free than show message
if ( !allFree ){
if (!npcTalking){
this.message.show(msgDataReq);
// msgShowing = true;
}
}
// If all prisioner not free then don't pull the trigger otherwise pull the trigger
this.pullTrigger = allFree;
}
}
if (this.pullTrigger){
if (this.checkSolution){
// // Open the door
// this.doorLayer.clearTile(this.targX,this.targY);
// this.collisionLayer.clearTile(this.targX,this.targY);
// //Remove this object
// me.game.remove(this);