-
Notifications
You must be signed in to change notification settings - Fork 0
/
jaws.js
2654 lines (2338 loc) · 87.4 KB
/
jaws.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
/**
* @namespace JawsJS core functions. "Field Summary" contains readable properties on the main jaws-object.
*
* @property {int} mouse_x Mouse X position with respect to the canvas-element
* @property {int} mouse_y Mouse Y position with respect to the canvas-element
* @property {canvas} canvas The detected/created canvas-element used for the game
* @property {context} context The detected/created canvas 2D-context, used for all draw-operations
* @property {int} width Width of the canvas-element
* @property {int} height Height of the canvas-element
*
*
* @example
* Jaws, a HTML5 canvas/javascript 2D game development framework
*
* Homepage: http://jawsjs.com/
* Source: http://github.com/ippa/jaws/
* Documentation: http://jawsjs.com/docs/
*
* Works with: Chrome 6.0+, Firefox 3.6+, 4+, IE 9+
* License: LGPL - http://www.gnu.org/licenses/lgpl.html
*
* Jaws uses the "module pattern".
* Adds 1 global, <b>jaws</b>, so plays nice with all other JS libs.
*
* Formating guide:
* jaws.oneFunction()
* jaws.one_variable = 1
* new jaws.OneConstructor
*
* Have fun!
*
* ippa.
*
*/
var jaws = (function(jaws) {
var title
var log_tag
jaws.title = function(value) {
if(value) { return (title.innerHTML = value) }
return title.innerHTML
}
/**
* Unpacks Jaws core-constructors into the global namespace. If a global property is allready taken, a warning will be written to jaws log.
* After calling jaws.unpack() you can use <b>Sprite()</b> instead of <b>jaws.Sprite()</b>, <b>Animation()</b> instead of <b>jaws.Animation()</b> and so on.
*
*/
jaws.unpack = function() {
var make_global = ["Sprite", "SpriteList", "Animation", "Viewport", "SpriteSheet", "Parallax", "TileMap", "Rect", "pressed"]
make_global.forEach( function(item, array, total) {
if(window[item]) { jaws.log(item + "already exists in global namespace") }
else { window[item] = jaws[item] }
});
}
/**
* Logs <b>msg</b> to previously found or created <div id="jaws-log">
* if <b>append</b> is true, append rather than overwrite the last log-msg.
*/
jaws.log = function(msg, append) {
if(log_tag) {
msg += "<br />"
if(append) { log_tag.innerHTML = log_tag.innerHTML.toString() + msg }
else { log_tag.innerHTML = msg }
}
}
/**
* @example
* Initializes / creates:
* jaws.canvas, jaws.context & jaws.dom // our drawable gamearea
* jaws.width & jaws.height // width/height of drawable gamearea
* jaws.url_parameters // hash of key/values of all parameters in current url
* title & log_tag // used internally by jaws
*
* @private
*/
jaws.init = function(options) {
/* Find <title> tag */
title = document.getElementsByTagName('title')[0]
jaws.url_parameters = jaws.getUrlParameters()
/*
* If debug=1 parameter is present in the URL, let's either find <div id="jaws-log"> or create the tag.
* jaws.log(message) will use this div for debug/info output to the gamer or developer
*
*/
log_tag = document.getElementById('jaws-log')
if(jaws.url_parameters["debug"]) {
if(!log_tag) {
log_tag = document.createElement("div")
log_tag.id = "jaws-log"
log_tag.style.cssText = "overflow: auto; color: #aaaaaa; width: 300px; height: 150px; margin: 40px auto 0px auto; padding: 5px; border: #444444 1px solid; clear: both; font: 10px verdana; text-align: left;"
document.body.appendChild(log_tag)
}
}
jaws.canvas = document.getElementsByTagName('canvas')[0]
if(!jaws.canvas) { jaws.dom = document.getElementById("canvas") }
// Ordinary <canvas>, get context
if(jaws.canvas) { jaws.context = jaws.canvas.getContext('2d'); }
// div-canvas / hml5 sprites, set position relative to have sprites with position = "absolute" stay within the canvas
else if(jaws.dom) { jaws.dom.style.position = "relative"; }
// Niether <canvas> or <div>, create a <canvas> with specified or default width/height
else {
jaws.canvas = document.createElement("canvas")
jaws.canvas.width = options.width
jaws.canvas.height = options.height
jaws.context = jaws.canvas.getContext('2d')
document.body.appendChild(jaws.canvas)
}
jaws.width = jaws.canvas ? jaws.canvas.width : jaws.dom.offsetWidth
jaws.height = jaws.canvas ? jaws.canvas.height : jaws.dom.offsetHeight
jaws.mouse_x = 0
jaws.mouse_y = 0
window.addEventListener("mousemove", saveMousePosition)
}
/**
* @private
* Keeps updated mouse coordinates in jaws.mouse_x / jaws.mouse_y
* This is called each time event "mousemove" triggers.
*/
function saveMousePosition(e) {
jaws.mouse_x = (e.pageX || e.clientX)
jaws.mouse_y = (e.pageY || e.clientX)
var game_area = jaws.canvas ? jaws.canvas : jaws.dom
jaws.mouse_x -= game_area.offsetLeft
jaws.mouse_y -= game_area.offsetTop
}
/**
* Quick and easy startup of a jaws game loop.
*
* @example
*
* // jaws.start(YourGameState) It will do the following:
* //
* // 1) Call jaws.init() that will detect any canvas-tag (or create one for you) and set up the 2D context, then available in jaws.canvas and jaws.context.
* //
* // 2) Pre-load all defined assets with jaws.assets.loadAll() while showing progress, then available in jaws.assets.get("your_asset.png").
* //
* // 3) Create an instance of YourGameState() and call setup() on that instance. In setup() you usually create your gameobjects, sprites and so on.
* //
* // 4) Loop calls to update() and draw() with given FPS (default 60) until game ends or another game state is activated.
*
*
* jaws.start(MyGame) // Start game state Game() with default options
* jaws.start(MyGame, {fps: 30}) // Start game state Geme() with options, in this case jaws will run your game with 30 frames per second.
* jaws.start(window) // Use global functions setup(), update() and draw() if available. Not the recommended way but useful for testing and mini-games.
*
* // It's recommended not giving fps-option to jaws.start since then it will default to 60 FPS and using requestAnimationFrame when possible.
*
*/
jaws.start = function(game_state, options,game_state_setup_options) {
if(!options) options = {};
var fps = options.fps || 60
if (options.loading_screen === undefined)
options.loading_screen = true
if(!options.width) options.width = 500;
if(!options.height) options.height = 300;
jaws.init(options)
displayProgress(0)
jaws.log("setupInput()", true)
jaws.setupInput()
function displayProgress(percent_done) {
if(jaws.context && options.loading_screen) {
jaws.context.save()
jaws.context.fillStyle = "black"
jaws.context.fillRect(0, 0, jaws.width, jaws.height);
jaws.context.textAlign = "center"
jaws.context.fillStyle = "white"
jaws.context.font = "15px terminal";
jaws.context.fillText("Loading", jaws.width/2, jaws.height/2-30);
jaws.context.font = "bold 30px terminal";
jaws.context.fillText(percent_done + "%", jaws.width/2, jaws.height/2);
jaws.context.restore()
}
}
/* Callback for when one single assets has been loaded */
function assetLoaded(src, percent_done) {
jaws.log( percent_done + "%: " + src, true)
displayProgress(percent_done)
}
/* Callback for when an asset can't be loaded*/
function assetError(src) {
jaws.log( "Error loading: " + src, true)
}
/* Callback for when all assets are loaded */
function assetsLoaded() {
jaws.log("all assets loaded", true)
jaws.switchGameState(game_state||window, {fps: fps},game_state_setup_options)
}
jaws.log("assets.loadAll()", true)
if(jaws.assets.length() > 0) { jaws.assets.loadAll({onload:assetLoaded, onerror:assetError, onfinish:assetsLoaded}) }
else { assetsLoaded() }
}
/**
* Switch to a new active game state
* Save previous game state in jaws.previous_game_state
*
* @example
*
* function MenuState() {
* this.setup = function() { ... }
* this.draw = function() { ... }
* this.update = function() {
* if(pressed("enter")) jaws.switchGameState(GameState); // Start game when Enter is pressed
* }
* }
*
* function GameState() {
* this.setup = function() { ... }
* this.update = function() { ... }
* this.draw = function() { ... }
* }
*
* jaws.start(MenuState)
*
*/
jaws.switchGameState = function(game_state, options,game_state_setup_options) {
var fps = (options && options.fps) || (jaws.game_loop && jaws.game_loop.fps) || 60
jaws.game_loop && jaws.game_loop.stop()
jaws.clearKeyCallbacks() // clear out all keyboard callbacks
if(jaws.isFunction(game_state)) { game_state = new game_state }
jaws.previous_game_state = jaws.game_state
jaws.game_state = game_state
jaws.game_loop = new jaws.GameLoop(game_state, {fps: fps},game_state_setup_options)
jaws.game_loop.start()
}
/**
* Takes an image, returns a canvas-element containing that image.
* Benchmarks has proven canvas to be faster to work with then images in certain browsers.
* Returns: a canvas-element
*/
jaws.imageToCanvas = function(image) {
var canvas = document.createElement("canvas")
canvas.src = image.src // Make canvas look more like an image
canvas.width = image.width
canvas.height = image.height
var context = canvas.getContext("2d")
context.drawImage(image, 0, 0, image.width, image.height)
return canvas
}
/**
* Return obj as an array. An array is returned as is. This is useful when you want to iterate over an unknown variable.
*
* @example
*
* jaws.forceArray(1) // --> [1]
* jaws.forceArray([1,2]) // --> [1,2]
*
*/
jaws.forceArray = function(obj) {
return Array.isArray(obj) ? obj : [obj]
}
/** Clears screen (the canvas-element) through context.clearRect() */
jaws.clear = function() {
jaws.context.clearRect(0,0,jaws.width,jaws.height)
}
/** Returns true if obj is an Image */
jaws.isImage = function(obj) {
return Object.prototype.toString.call(obj) === "[object HTMLImageElement]"
}
/** Returns true of obj is a Canvas-element */
jaws.isCanvas = function(obj) {
return Object.prototype.toString.call(obj) === "[object HTMLCanvasElement]"
}
/** Returns true of obj is either an Image or a Canvas-element */
jaws.isDrawable = function(obj) {
return jaws.isImage(obj) || jaws.isCanvas(obj)
}
/** Returns true if obj is a String */
jaws.isString = function(obj) {
return (typeof obj == 'string')
}
/** Returns true if obj is an Array */
jaws.isArray = function(obj) {
if(obj === undefined) return false;
return !(obj.constructor.toString().indexOf("Array") == -1)
}
/** Returns true of obj is a Function */
jaws.isFunction = function(obj) {
return (Object.prototype.toString.call(obj) === "[object Function]")
}
/**
* Returns true if <b>item</b> is outside the canvas.
* <b>item</b> needs to have the properties x, y, width & height
*/
jaws.isOutsideCanvas = function(item) {
return (item.x < 0 || item.y < 0 || item.x > jaws.width || item.y > jaws.height)
}
/**
* Force <b>item</b> inside canvas by setting items x/y parameters
* <b>item</b> needs to have the properties x, y, width & height
*/
jaws.forceInsideCanvas = function(item) {
if(item.x < 0) { item.x = 0 }
if(item.x > jaws.width) { item.x = jaws.width }
if(item.y < 0) { item.y = 0 }
if(item.y > jaws.height) { item.y = jaws.height }
}
/**
* Return a hash of url-parameters and their values
*
* @example
* // Given the current URL is <b>http://test.com/?debug=1&foo=bar</b>
* jaws.getUrlParameters() // --> {debug: 1, foo: bar}
*/
jaws.getUrlParameters = function() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
return jaws;
})(jaws || {});
var jaws = (function(jaws) {
var pressed_keys = {}
var keycode_to_string = []
var on_keydown_callbacks = []
var on_keyup_callbacks = []
var mousebuttoncode_to_string = []
/** @private
* Map all javascript keycodes to easy-to-remember letters/words
*/
jaws.setupInput = function() {
var k = []
k[8] = "backspace"
k[9] = "tab"
k[13] = "enter"
k[16] = "shift"
k[17] = "ctrl"
k[18] = "alt"
k[19] = "pause"
k[20] = "capslock"
k[27] = "esc"
k[32] = "space"
k[33] = "pageup"
k[34] = "pagedown"
k[35] = "end"
k[36] = "home"
k[37] = "left"
k[38] = "up"
k[39] = "right"
k[40] = "down"
k[45] = "insert"
k[46] = "delete"
k[91] = "leftwindowkey"
k[92] = "rightwindowkey"
k[93] = "selectkey"
k[106] = "multiply"
k[107] = "add"
k[109] = "subtract"
k[110] = "decimalpoint"
k[111] = "divide"
k[144] = "numlock"
k[145] = "scrollock"
k[186] = "semicolon"
k[187] = "equalsign"
k[188] = "comma"
k[189] = "dash"
k[190] = "period"
k[191] = "forwardslash"
k[192] = "graveaccent"
k[219] = "openbracket"
k[220] = "backslash"
k[221] = "closebracket"
k[222] = "singlequote"
var m = []
m[0] = "left_mouse_button"
m[1] = "center_mouse_button"
m[2] = "right_mouse_button"
mousebuttoncode_to_string = m
var numpadkeys = ["numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9"]
var fkeys = ["f1","f2","f3","f4","f5","f6","f7","f8","f9"]
var numbers = ["0","1","2","3","4","5","6","7","8","9"]
var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for(var i = 0; numbers[i]; i++) { k[48+i] = numbers[i] }
for(var i = 0; letters[i]; i++) { k[65+i] = letters[i] }
for(var i = 0; numpadkeys[i]; i++) { k[96+i] = numpadkeys[i] }
for(var i = 0; fkeys[i]; i++) { k[112+i] = fkeys[i] }
keycode_to_string = k
window.addEventListener("keydown", handleKeyDown)
window.addEventListener("keyup", handleKeyUp)
window.addEventListener('mousedown', handleMouseDown, false);
window.addEventListener('mouseup', handleMouseUp, false);
// this turns off the right click context menu which screws up the mouseup event for button 2
document.oncontextmenu = function() {return false};
}
/** @private
* handle event "onkeydown" by remembering what key was pressed
*/
function handleKeyUp(e) {
event = (e) ? e : window.event
var human_name = keycode_to_string[event.keyCode]
pressed_keys[human_name] = false
if(on_keyup_callbacks[human_name]) {
on_keyup_callbacks[human_name](human_name)
e.preventDefault()
}
if(prevent_default_keys[human_name]) { e.preventDefault() }
}
/** @private
* handle event "onkeydown" by remembering what key was un-pressed
*/
function handleKeyDown(e) {
event = (e) ? e : window.event
var human_name = keycode_to_string[event.keyCode]
pressed_keys[human_name] = true
if(on_keydown_callbacks[human_name]) {
on_keydown_callbacks[human_name](human_name)
e.preventDefault()
}
if(prevent_default_keys[human_name]) { e.preventDefault() }
}
/** @private
* handle event "onmousedown" by remembering what button was pressed
*/
function handleMouseDown(e) {
event = (e) ? e : window.event
var human_name = mousebuttoncode_to_string[event.button] // 0 1 2
pressed_keys[human_name] = true
if(on_keydown_callbacks[human_name]) {
on_keydown_callbacks[human_name](human_name)
e.preventDefault()
}
}
/** @private
* handle event "onmouseup" by remembering what button was un-pressed
*/
function handleMouseUp(e) {
event = (e) ? e : window.event
var human_name = mousebuttoncode_to_string[event.button]
pressed_keys[human_name] = false
if(on_keyup_callbacks[human_name]) {
on_keyup_callbacks[human_name](human_name)
e.preventDefault()
}
// need to investigate prevent default for mouse actions instead of hard coding the oncontextmenu
}
var prevent_default_keys = []
/**
* Prevents default browseraction for given keys.
* @example
* jaws.preventDefaultKeys( ["down"] ) // Stop down-arrow-key from scrolling page down
*/
jaws.preventDefaultKeys = function(array_of_strings) {
array_of_strings.forEach( function(item, index) {
prevent_default_keys[item] = true
});
}
/**
* Returns true if *key* is currently pressed down
* @example
* jaws.pressed("left"); // returns true if arrow key is pressed
* jaws.pressed("a"); // returns true if key "a" is pressed
*/
jaws.pressed = function(key) {
return pressed_keys[key]
}
/**
* sets up a callback for a key (or array of keys) to call when it's pressed down
*
* @example
* // call goLeft() when left arrow key is pressed
* jaws.on_keypress("left", goLeft)
*
* // call fireWeapon() when SPACE or CTRL is pressed
* jaws.on_keypress(["space","ctrl"], fireWeapon)
*/
jaws.on_keydown = function(key, callback) {
if(jaws.isArray(key)) {
for(var i=0; key[i]; i++) {
on_keydown_callbacks[key[i]] = callback
}
}
else {
on_keydown_callbacks[key] = callback
}
}
/**
* sets up a callback when a key (or array of keys) to call when it's released
*/
jaws.on_keyup = function(key, callback) {
if(jaws.isArray(key)) {
for(var i=0; key[i]; i++) {
on_keyup_callbacks[key[i]] = callback
}
}
else {
on_keyup_callbacks[key] = callback
}
}
/** @private
* Clean up all callbacks set by on_keydown / on_keyup
*/
jaws.clearKeyCallbacks = function() {
on_keyup_callbacks = []
on_keydown_callbacks = []
}
return jaws;
})(jaws || {});
var jaws = (function(jaws) {
/**
* @class Loads and processes assets as images, sound, video, json
* Used internally by JawsJS to create <b>jaws.assets</b>
*/
jaws.Assets = function Assets() {
if( !(this instanceof arguments.callee) ) return new arguments.callee();
this.loaded = [] // Hash of all URLs that's been loaded
this.loading = [] // Hash of all URLs currently loading
this.src_list = [] // Hash of all unloaded URLs that loadAll() will try to load
this.data = [] // Hash of loaded raw asset data, URLs are keys
this.bust_cache = false
this.image_to_canvas = true
this.fuchia_to_transparent = true
this.root = ""
this.file_type = {}
this.file_type["json"] = "json"
this.file_type["wav"] = "audio"
this.file_type["mp3"] = "audio"
this.file_type["ogg"] = "audio"
this.file_type["png"] = "image"
this.file_type["jpg"] = "image"
this.file_type["jpeg"] = "image"
this.file_type["gif"] = "image"
this.file_type["bmp"] = "image"
this.file_type["tiff"] = "image"
var that = this
this.length = function() {
return this.src_list.length
}
/*
* Get one or many resources
*
* @param String or Array of strings
* @returns The raw resource or an array of resources
*
*/
this.get = function(src) {
if(jaws.isArray(src)) {
return src.map( function(i) { return that.data[i] } )
}
else {
if(this.loaded[src]) { return this.data[src] }
else { jaws.log("No such asset: " + src, true) }
}
}
/** Return true if src is in the process of loading (but not yet finishing) */
this.isLoading = function(src) {
return this.loading[src]
}
/** Return true if src is loaded in full */
this.isLoaded = function(src) {
return this.loaded[src]
}
this.getPostfix = function(src) {
postfix_regexp = /\.([a-zA-Z0-9]+)/;
return postfix_regexp.exec(src)[1]
}
this.getType = function(src) {
var postfix = this.getPostfix(src)
return (this.file_type[postfix] ? this.file_type[postfix] : postfix)
}
/**
* Add array of paths or single path to asset-list. Later load with loadAll()
*
* @example
*
* jaws.assets.add("player.png")
* jaws.assets.add(["media/bullet1.png", "media/bullet2.png"])
* jaws.loadAll({onfinish: start_game})
*
*/
this.add = function(src) {
if(jaws.isArray(src)) { for(var i=0; src[i]; i++) { this.add(src[i]) } }
else { this.src_list.push(src) }
// else { var path = this.root + src; this.src_list.push(path) }
return this
}
/** Load all pre-specified assets */
this.loadAll = function(options) {
this.load_count = 0
this.error_count = 0
/* With these 3 callbacks you can display progress and act when all assets are loaded */
this.onload = options.onload
this.onerror = options.onerror
this.onfinish = options.onfinish
for(i=0; this.src_list[i]; i++) {
this.load(this.src_list[i])
}
}
/** Calls onload right away if asset is available since before, otherwise try to load it */
this.getOrLoad = function(src, onload, onerror) {
if(this.data[src]) { onload() }
else { this.load(src, onload, onerror) }
}
/**
* Load a single url <b>src</b>.
* if <b>onload</b> is specified, it's called on loading-success
* if <b>onerror</b> is specified, it will be called on any loading-error
*
* @example
*
* jaws.load("media/foo.png")
*
*/
this.load = function(src, onload, onerror) {
var asset = {}
asset.src = src
asset.onload = onload
asset.onerror = onerror
this.loading[src] = true
var resolved_src = this.root + asset.src;
if (this.bust_cache) { resolved_src += "?" + parseInt(Math.random()*10000000) }
switch(this.getType(asset.src)) {
case "image":
asset.image = new Image()
asset.image.asset = asset // enables us to access asset in the callback
//
// TODO: Make http://dev.ippa.se/webgames/test2.html work
//
asset.image.onload = this.assetLoaded
asset.image.onerror = this.assetError
asset.image.src = resolved_src
break;
case "audio":
asset.audio = new Audio(resolved_src)
asset.audio.asset = asset // enables us to access asset in the callback
this.data[asset.src] = asset.audio
asset.audio.addEventListener("canplay", this.assetLoaded, false);
asset.audio.addEventListener("error", this.assetError, false);
asset.audio.load()
break;
default:
var req = new XMLHttpRequest()
req.asset = asset // enables us to access asset in the callback
req.onreadystatechange = this.assetLoaded
req.open('GET', resolved_src, true)
req.send(null)
break;
}
}
/** @private
* Callback for all asset-loading.
* 1) Parse data depending on filetype. Images are (optionally) converted to canvas-objects. json are parsed into native objects and so on.
* 2) Save processed data in internal list for easy fetching with assets.get(src) later on
* 3) Call callbacks if defined
*/
this.assetLoaded = function(e) {
var asset = this.asset
var src = asset.src
var filetype = that.getType(asset.src)
// Keep loading and loaded hash up to date
that.loaded[src] = true
that.loading[src] = false
// Process data depending differently on postfix
if(filetype == "json") {
if (this.readyState != 4) { return }
that.data[asset.src] = JSON.parse(this.responseText)
}
else if(filetype == "image") {
var new_image = that.image_to_canvas ? jaws.imageToCanvas(asset.image) : asset.image
if(that.fuchia_to_transparent && that.getPostfix(asset.src) == "bmp") { new_image = fuchiaToTransparent(new_image) }
that.data[asset.src] = new_image
}
else if(filetype == "audio") {
asset.audio.removeEventListener("canplay", that.assetLoaded, false);
that.data[asset.src] = asset.audio
}
that.load_count++
that.processCallbacks(asset, true)
}
/** @private */
this.assetError = function(e) {
var asset = this.asset
that.error_count++
that.processCallbacks(asset, false)
}
/** @private */
this.processCallbacks = function(asset, ok) {
var percent = parseInt( (that.load_count+that.error_count) / that.src_list.length * 100)
if(ok) {
if(that.onload) that.onload(asset.src, percent);
if(asset.onload) asset.onload();
}
else {
if(that.onerror) that.onerror(asset.src, percent);
if(asset.onerror) asset.onerror(asset);
}
// When loadAll() is 100%, call onfinish() and kill callbacks (reset with next loadAll()-call)
if(percent==100) {
if(that.onfinish) { that.onfinish() }
that.onload = null
that.onerror = null
that.onfinish = null
}
}
}
/** @private
* Make Fuchia (0xFF00FF) transparent
* This is the de-facto standard way to do transparency in BMPs
* Returns: a canvas-element
*/
function fuchiaToTransparent(image) {
canvas = jaws.isImage(image) ? jaws.imageToCanvas(image) : image
var context = canvas.getContext("2d")
var img_data = context.getImageData(0,0,canvas.width,canvas.height)
var pixels = img_data.data
for(var i = 0; i < pixels.length; i += 4) {
if(pixels[i]==255 && pixels[i+1]==0 && pixels[i+2]==255) { // Color: Fuchia
pixels[i+3] = 0 // Set total see-through transparency
}
}
context.putImageData(img_data,0,0);
return canvas
}
jaws.assets = new jaws.Assets()
return jaws;
})(jaws || {});
var jaws = (function(jaws) {
// requestAnim shim layer by Paul Irish
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 16.666);
};
})();
/**
* @class A classic game loop forever looping calls to update() / draw() with given framerate. "Field Summary" contains options for the GameLoop()-constructor.
*
* @property {int} FPS targeted frame rate
*
* @example
*
* game = {}
* draw: function() { ... your stuff executed every 30 FPS ... }
* }
*
* game_loop = new jaws.GameLoop(game, {fps: 30})
* game_loop.start()
*
* // You can also use the shortcut jaws.start(), it will:
* // 1) Load all assets with jaws.assets.loadAll()
* // 2) Create a GameLoop() and start it
* jaws.start(MyGameState, {fps: 30})
*
*/
jaws.GameLoop = function GameLoop(game_object, options,game_state_setup_options) {
if( !(this instanceof arguments.callee) ) return new arguments.callee( game_object, options );
this.ticks = 0
this.tick_duration = 0
this.fps = 0
var update_id
var paused = false
var stopped = false
var that = this
var mean_value = new MeanValue(20) // let's have a smooth, non-jittery FPS-value
/**
* returns how game_loop has been active in milliseconds
* does currently not factor in pause-time
*/
this.runtime = function() {
return (this.last_tick - this.first_tick)
}
/** Start the game loop by calling setup() once and then loop update()/draw() forever with given FPS */
this.start = function() {
jaws.log("game loop start", true)
this.first_tick = (new Date()).getTime();
this.current_tick = (new Date()).getTime();
this.last_tick = (new Date()).getTime();
if(game_object.setup) { game_object.setup(game_state_setup_options) }
step_delay = 1000 / options.fps;
if(options.fps == 60) {
requestAnimFrame(this.loop)
}
else {
update_id = setInterval(this.loop, step_delay);
}
jaws.log("game loop loop", true)
}
/** The core of the game loop. Calculate a mean FPS and call update()/draw() if game loop is not paused */
this.loop = function() {
that.current_tick = (new Date()).getTime();
that.tick_duration = that.current_tick - that.last_tick
that.fps = mean_value.add(1000/that.tick_duration).get()
if(!stopped && !paused) {
if(game_object.update) { game_object.update() }
if(game_object.draw) { game_object.draw() }
that.ticks++
}
if(options.fps == 60 && !stopped) requestAnimFrame(that.loop);
that.last_tick = that.current_tick;
}
/** Pause the game loop. loop() will still get called but not update() / draw() */
this.pause = function() { paused = true }
/** unpause the game loop */
this.unpause = function() { paused = false }
/** Stop the game loop */
this.stop = function() {
if(update_id) clearInterval(update_id);
stopped = true;
}
}
/** @ignore */
function MeanValue(size) {
this.size = size
this.values = new Array(this.size)
this.value
this.add = function(value) {
if(this.values.length > this.size) { // is values filled?
this.values.splice(0,1)
this.value = 0
for(var i=0; this.values[i]; i++) {
this.value += this.values[i]
}
this.value = this.value / this.size
}
this.values.push(value)
return this
}
this.get = function() {
return parseInt(this.value)
}
}
return jaws;
})(jaws || {});
var jaws = (function(jaws) {
/**
@class A Basic rectangle.
@example
rect = new jaws.Rect(5,5,20,20)
rect.right // -> 25
rect.bottom // -> 25
rect.move(10,20)
rect.right // -> 35
rect.bottom // -> 45
rect.width // -> 20
rect.height // -> 20
*/
jaws.Rect = function Rect(x, y, width, height) {
if( !(this instanceof arguments.callee) ) return new arguments.callee(x, y, width, height);
this.x = x
this.y = y
this.width = width
this.height = height
this.right = x + width
this.bottom = y + height
}
/** Return position as [x,y] */
jaws.Rect.prototype.getPosition = function() {
return [this.x, this.y]
}
/** Move rect x pixels horizontally and y pixels vertically */
jaws.Rect.prototype.move = function(x,y) {
this.x += x
this.y += y
this.right += x
this.bottom += y
return this
}
/** Set rects x/y */
jaws.Rect.prototype.moveTo = function(x,y) {
this.x = x
this.y = y
this.right = this.x + this.width
this.bottom = this.y + this.height
return this
}
/** Modify width and height */
jaws.Rect.prototype.resize = function(width,height) {
this.width += width
this.height += height
this.right = this.x + this.width
this.bottom = this.y + this.height
return this
}
/** Set width and height */
jaws.Rect.prototype.resizeTo = function(width,height) {
this.width = width
this.height = height