-
Notifications
You must be signed in to change notification settings - Fork 0
/
pacmaze.html
executable file
·1538 lines (1333 loc) · 51.6 KB
/
pacmaze.html
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
<!--
Pacmaze. This is a pacman-like 3d game based on webgl, html and javascript.
Copyright (C) <2015> <Lappas Dionysis [email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="Pacmaze is a pacman 3d game based on web technologies">
<meta name="keywords" content="pacmaze, webgl">
<meta name="author" content="Lappas Dionysis">
<title>Pacmaze</title>
<!-- external libraries for matrix calculations and maintenance -->
<script type="text/javascript" src="./sandbox_files/glMatrix-0.9.5.min.js"></script>
<script type="text/javascript" src="./sandbox_files/webgl-utils.js"></script>
<!-- Code for the vertex shader-->
<script id="shader-vs" type="x-shader/x-vertex">
//attributes for the vertex shader (different for every thread/core that will execute a copy of this)
attribute vec3 aVertexPosition;
attribute vec4 aVertexColor;
attribute vec4 aNormal;
uniform mat4 uNormalMatrix; //Transformation matrix of the normal
uniform vec3 uLightColor; //Light color
uniform vec3 uLightPosition; //Position of the light source (in the world coordinate system)
uniform vec3 uLightDirection;
uniform vec3 uAmbientLight; //Ambient light color
uniform int uDrawCustomColor;
//ModelView and Projection Matrices
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
//Variable to be forwarded to the corresponding thread of the fragment shader
varying vec4 vColor;
//main function of the vertex shader
//this code will be copied to many shader cores/threads and executed with the associated
//data for every vertex (matrices, color, etc)
void main(void) {
vec4 color = aVertexColor;
if (uDrawCustomColor == 1){
//yellow
color = vec4(1.0, 1.0, 0.0, 1.0);
}else if (uDrawCustomColor == 2){
//red
color = vec4(1.0, 0.0, 0.0, 1.0);
}else if (uDrawCustomColor == 3){
//pink
color = vec4(1.0, 0.753, 0.796, 1.0);
}else if (uDrawCustomColor == 4){
//cyan
color = vec4(0.0, 1.0, 1.0, 1.0);
}else if (uDrawCustomColor == 5){
//orange
color = vec4(1.0, 0.647, 0.0, 1.0);
}else if (uDrawCustomColor == 6){
//orange
color = vec4(0.0, 0.0, 1.0, 1.0);
}
//Each vertex is multiplied with the ModelView and Projection matrices and created a fragment
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
//Recalculate normal with normal matrix and make its length 1.0
vec3 normal = normalize(vec3(uNormalMatrix * aNormal));
//Calculate the world coordinate of the vertex
vec4 newVertexPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
//Calculate the light direction and make it 1.0 in length
vec3 lightDirection = normalize(uLightPosition - vec3(newVertexPosition));
//Dot product of the light direction and the orientation of a surface (the normal)
float nDotL = max(dot(lightDirection, normal), 0.0);
//Calculate the color due to diffuse reflection, color is forwarded to the fragment shader
vec3 diffuse = uLightColor * color.rgb * nDotL;
//Calculate the color due to ambient reflection
vec3 ambient = uAmbientLight * color.rgb;
//Add surface colors due to diffuse and ambient reflection
vColor = vec4(diffuse + ambient, color.a);
}
</script>
<!-- Code for the fragment shader-->
<script id="shader-fs" type="x-shader/x-fragment">
//necessary code for compatibility
precision mediump float;
//Variable coming from the vertex shader
varying vec4 vColor;
void main(void) {
//the fragment gets its color value.
//in the fragment shader many advanced shading algorithms can be implemented (Phong etc..)
gl_FragColor = vColor;
}
</script>
<!-- Javascript code for the main functionality of the WebGL application-->
<script type="text/javascript">
//ModelView and Projection matrices
//mat4 comes from the external library
var mvMatrix = mat4.create();
var mvMatrixStack = [];
var pMatrix = mat4.create();
var normalMatrix = mat4.create();
var sphereLighting = false;
//This var is used to encode 6 olor values
//[0]->Off, [1]->yellow, [2]->red, [3]->pink, [4]->cyan, [5]->orange, [6]->blue
var drawCustomColor = 0;
//the variable that will accommodate the WebGL context
//every call to the state machine will be done through this variable
var gl;
//The matrix stack operation are implemented below to handle local transformations
//Push Matrix Operation
function mvPushMatrix() {
var copy = mat4.create();
mat4.set(mvMatrix, copy);
mvMatrixStack.push(copy);
}
//Pop Matrix Operation
function mvPopMatrix() {
if (mvMatrixStack.length == 0) {
throw "Invalid popMatrix!";
}
mvMatrix = mvMatrixStack.pop();
}
//Sets + Updates matrix uniforms
function setMatrixUniforms() {
gl.uniform1i(shaderProgram.uDrawCustomColor, drawCustomColor);
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
//Set the light color (white)
gl.uniform3f(shaderProgram.uLightColor, 0.5, 0.5, 0.5);
//Set the light direction (in the world coordinate)
var lightDirection = [2.3, 4.0, 3.5];
gl.uniform3fv(shaderProgram.uLightDirection, new Float32Array(lightDirection));
gl.uniform3f(shaderProgram.uAmbientLight, 0.5, 0.1, 0.4);
//Pass the transformation matrix for normal to u_NormalMatrix
gl.uniformMatrix4fv(shaderProgram.uNormalMatrix, false, new Float32Array(normalMatrix));
//Set the position of the light source (in the world coordinate)
gl.uniform3f(shaderProgram.uLightPosition, 8.0, 7.0, -10.0);
}
//Rotation function helper
function degToRad(degrees) {
return degrees * Math.PI / 180;
}
//Initialize WebGL
function initGL(canvas) {
try {
//get a webgl context
gl = canvas.getContext("webgl");
//assign a viewport width and height based on the HTML canvas element properties
//(check last lines of code)
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
//any error is handled here
//all errors are visible in the console (F12 in Google chrome)
} catch (e) {
}
if (!gl) {
alert("Could not initialise WebGL, sorry :-(");
}
}
//Find and compile shaders (vertex + fragment shader)
function getShader(gl, id) {
//gets the shader scripts (vertex + fragment)
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
//create shaders
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
//ask WebGL to compile shaders
//we check for errors here too
//all errors are visible in the console (F12 in Google chrome)
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
var shaderProgram;
//Creates a program from a vertex + fragment shader pair
function initShaders() {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
//link the compiled binaries
gl.linkProgram(shaderProgram);
//check for errors, again
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
//activate current program
//this sandbox has only on shader pair
//we can have as many as we wish in more complex applications
gl.useProgram(shaderProgram);
//Update attributes for the vertex shader
//attributes are accessible only from the vertex shader
//if we want accessible data from a fragment shader we can use uniform variables,
//or varyings that will be forwarded from the vertex shader to the fragment shader
//Vertex position data
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
//Vertex color data
shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
//Vertex normal data
shaderProgram.aNormal = gl.getAttribLocation(shaderProgram, 'aNormal');
gl.enableVertexAttribArray(shaderProgram.aNormal);
//Update uniform variables
//this variables can be accessed from both the vertex and fragment shader
//Get the storage locations
shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
shaderProgram.uLightColor = gl.getUniformLocation(shaderProgram, 'uLightColor');
shaderProgram.uLightDirection = gl.getUniformLocation(shaderProgram, 'uLightDirection');
shaderProgram.uAmbientLight = gl.getUniformLocation(shaderProgram, 'uAmbientLight');
shaderProgram.uNormalMatrix = gl.getUniformLocation(shaderProgram, 'uNormalMatrix');
shaderProgram.uLightPosition = gl.getUniformLocation(shaderProgram, 'uLightPosition');
shaderProgram.uDrawCustomColor = gl.getUniformLocation(shaderProgram, 'uDrawCustomColor');
}
//Vertex, Index and Color Data
var cubeVertexPositionBuffer; //contains coordinates
var cubeVertexColorBuffer; //contains color per vertex
var cubeVertexIndexBuffer; //contains indices for chains of vertices to draw triangles/other geometry
var cubeVertexNormalBuffer;//cube normals
var spherePositionsBuffer; //contains sphere coordinates
var sphereIndicesBuffer; //contains indices for sphere
var sphereVertexNormalBuffer;//sphere normals
//Initialize VBOs, IBOs and color
function initBuffers() {
//Create a cube
// v6----- v5
// /| /|
// v1------v0|
// | | | |
// | |v7---|-|v4
// |/ |/
// v2------v3
//Vertex Buffer Object
cubeVertexPositionBuffer = gl.createBuffer();
//Bind buffer to ARRAY_BUFFER
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
vertices = [
//Front face
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
//Back face
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
//Top face
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
//Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
//Right face
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
//Left face
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0
];
//every item has 3 coordinates (x,y,z)
cubeVertexPositionBuffer.itemSize = 3;
//we have 24 vertices
cubeVertexPositionBuffer.numItems = 24;
//Bind buffer to ARRAY_BUFFER
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
//Write data to buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
//Assign the buffer object bound to gl.ARRAY_BUFFER to the attribute variable shaderProgram.vertexPositionAttribute
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, cubeVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
//gl.bindBuffer(gl.ARRAY_BUFFER, null);
//Color
cubeVertexColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
colors = [
[1.0, 0.0, 0.0, 1.0], //Front face
[1.0, 1.0, 0.0, 1.0], //Back face
[0.0, 1.0, 0.0, 1.0], //Top face
[1.0, 1.0, 0.5, 1.0], //Bottom face
[1.0, 0.0, 1.0, 1.0], //Right face
[0.0, 0.0, 1.0, 1.0] //Left face
];
var unpackedColors = [];
for (var i in colors) {
var color = colors[i];
//assign colors for each vertex of each face based on the packed representation above
for (var j=0; j < 4; j++) {
unpackedColors = unpackedColors.concat(color);
}
}
//every color has 4 values: red, green, blue and alpha (transparency: use 1.0 (opaque) for this demo)
cubeVertexColorBuffer.itemSize = 4;
//24 color values (we have 24 vertices to color...)
cubeVertexColorBuffer.numItems = 24;
//Bind the buffer for the cube colors to ARRAY_BUFFER
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
//Write data to buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(unpackedColors), gl.STATIC_DRAW);
//Assign the buffer object bound to gl.ARRAY_BUFFER to the attribute variable shaderProgram.vertexColorAttribute
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, cubeVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
//gl.bindBuffer(gl.ARRAY_BUFFER, null);
//Normal Vectors
var normals = [ //Normal
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, //v0-v1-v2-v3 front
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, //v0-v3-v4-v5 right
0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, //v0-v5-v6-v1 up
-1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, //v1-v6-v7-v2 left
0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, //v7-v4-v3-v2 down
0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0 //v4-v7-v6-v5 back
];
//Normal buffer object
cubeVertexNormalBuffer = gl.createBuffer();
//every vertex has 3 normal vectors
cubeVertexNormalBuffer.itemSize = 3;
//every face has 4 verices, a total fo 24 normals
cubeVertexNormalBuffer.numItems = 24;
//Bind the buffer for the cube normals to ARRAY_BUFFER
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexNormalBuffer);
//Write data to buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);
//Assign the buffer object bound to gl.ARRAY_BUFFER to the attribute variable shaderProgram.
gl.vertexAttribPointer(shaderProgram.aNormal, cubeVertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0);
//Index Buffer Object
//it joins sets of vertices into faces
cubeVertexIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
var cubeVertexIndices = [
//this numbers are positions in the VBO array above
0, 1, 2, 0, 2, 3, //Front face
4, 5, 6, 4, 6, 7, //Back face
8, 9, 10, 8, 10, 11, //Top face
12, 13, 14, 12, 14, 15, //Bottom face
16, 17, 18, 16, 18, 19, //Right face
20, 21, 22, 20, 22, 23 //Left face
];
//we have one item - the cube
cubeVertexIndexBuffer.itemSize = 1;
//we have 36 indices (6 faces, every face has 2 triangles, each triangle 3 vertices: 2x3x6=36)
cubeVertexIndexBuffer.numItems = 36;
//Bind the buffer for vertex indices to ELEMENT_ARRAY_BUFFER
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
//Write data to buffer
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
//gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
}
//Helper Variables
var rCube = 0;
var xTrans = 0.0;
var yTrans = 0.0;
var xzTrans = 0.0;
var swinging = 0.01;
var movDirection = true;
//array for keeping pressed keys
var currentlyPressedKeys = {};
//Keyboard handler
//do not touch :)
function handleKeyDown(event) {
currentlyPressedKeys[event.keyCode] = true;
if (String.fromCharCode(event.keyCode) == "P") {
//Enable Panoramic game camera
game.gameCamera = false;
} else if (String.fromCharCode(event.keyCode) == "T"){
//Enable Tracking game camera
game.gameCamera = true;
}
}
//Keyboard handler
//do not touch :)
function handleKeyUp(event) {
currentlyPressedKeys[event.keyCode] = false;
}
//Key pressed callback
//37-40 are the codes for the arrow keys
//xTrans + yTrans are used in the ModelView matrix for local transformation of the cube
function handleKeys() {
//checkPossibleMoves(pacman);
if (game.ignoreKeys == false){
if (currentlyPressedKeys[37]) {
//Left cursor key
pacman.nextDirection = 10;
//determineMove(pacman);
}
if (currentlyPressedKeys[39]) {
//Right cursor key
pacman.nextDirection = 20;
//determineMove(pacman);
}
if (currentlyPressedKeys[38]) {
//Up cursor key
pacman.nextDirection = 1;
//determineMove(pacman);
}
if (currentlyPressedKeys[40]) {
//Down cursor key
pacman.nextDirection = 2;
//determineMove(pacman);
}
}
}
//x: maze blocks, p: pellets, U: power Pellets
var x = 'x';
var p = 'p';
var U = 'U';
var level1_design = [
[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],
[x,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,x],
[x,p,x,x,x,x,x,x,p,x,p,x,x,x,x,x,x,p,x],
[x,p,p,p,p,x,p,p,p,x,p,p,p,x,p,p,p,p,x],
[x,x,p,x,p,x,p,x,x,x,x,x,p,x,p,x,p,x,x],
[x,p,p,x,p,p,p,p,p,p,p,p,p,p,p,x,p,p,x],
[x,U,x,x,p,x,x,x,p,x,p,x,x,x,p,x,x,U,x],
[x,p,p,p,p,p,p,p,p,x,p,p,p,p,p,p,p,p,x],
[x,p,x,x,p,x,p,x,x,x,x,x,p,x,p,x,x,p,x],
[x,p,p,p,p,x,p,p,p,p,p,p,p,x,p,p,p,p,x],
[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x]
];
var level2_design = [
[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],
[x,U,p,p,p,p,p,x,x,x,p,p,p,p,p,p,p,x,x,x,p,p,p,p,p,p,p,p,U,x],
[x,p,x,x,x,x,p,x,p,p,p,x,p,x,x,x,p,p,p,p,p,x,x,x,p,x,x,x,p,x],
[x,p,x,p,p,p,p,x,p,x,x,x,p,x,p,p,p,p,x,x,x,x,p,p,p,p,p,p,p,x],
[x,p,x,p,x,x,p,x,p,x,p,p,p,x,p,x,x,p,p,p,p,p,p,p,x,p,x,p,x,x],
[x,p,x,p,x,x,p,x,p,p,p,x,p,p,p,x,x,p,x,x,p,x,p,x,x,p,x,p,p,x],
[x,p,p,p,p,p,p,p,x,p,x,x,p,x,x,p,p,p,x,p,p,x,p,x,x,p,x,x,p,x],
[x,p,x,x,x,p,x,p,x,p,p,p,p,p,p,p,x,p,x,p,x,x,p,x,p,p,p,p,p,x],
[x,p,x,x,x,p,x,p,p,p,x,x,x,p,x,p,x,p,p,p,p,p,p,p,p,x,p,x,p,x],
[x,p,p,p,p,p,x,p,x,p,p,p,p,p,x,p,p,x,x,x,p,x,x,x,p,x,p,p,p,x],
[x,x,p,x,p,x,x,p,x,p,x,p,x,p,p,x,p,p,p,x,p,p,p,p,p,x,x,x,p,x],
[x,x,p,x,p,p,p,p,p,p,x,p,x,x,p,x,p,x,p,x,p,x,x,x,p,p,p,p,p,x],
[x,x,p,x,p,x,p,x,p,p,p,p,p,x,p,x,p,x,p,x,p,p,p,p,x,x,x,x,p,x],
[x,x,p,x,p,x,p,p,x,x,p,x,p,p,p,p,p,x,p,x,p,x,x,x,p,p,p,p,p,x],
[x,p,p,p,p,x,x,p,x,x,p,x,p,x,x,p,x,p,p,p,p,p,p,p,p,x,x,x,x,x],
[x,p,x,x,p,x,p,p,p,x,p,x,p,x,p,p,x,p,x,p,x,x,p,p,p,p,p,p,p,x],
[x,p,x,x,p,x,p,x,p,x,p,p,p,x,p,x,x,p,x,p,x,x,x,x,p,x,x,x,p,x],
[x,U,p,p,p,p,p,x,p,p,p,x,x,x,p,p,p,p,x,p,p,p,p,p,p,p,p,p,U,x],
[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x]
];
function mazeTile(aType, num, indx, indz) {
this.type = aType; //Types are x:maze, p:pellet, U:powerPellet
this.vertices = []; //Vertices of cube's bottom face [x,z] pairs
this.num = num;
this.mCenter = []; //The center of mass
this.indX = indx; //Index on the x-axis
this.indZ = indz; //Index on the z-axis
//4xi array, i=(0, 1) if move is allowed or not
//First index codes the direction of movement. If movement
//to that direction is allowed, store reference to tile.
//[1]> move up, [2]-> move down, [10]-> move left, [20]-> move right
//E.g. If elem[0][1] !== undefined -> move up allowed, elem[0][1]
//holds reference to that tile.
this.moves = [];
}
function createLevel(levelDesign){
var width = levelDesign[0].length;
var height = levelDesign.length;
var createdLevel = [];
var tmpTileVec = [];
for (var i=0; i<height; i++){
for (var j=0; j<width; j++){
var tileNum = i*width + j;
tmpTileVec.push(new mazeTile(levelDesign[i][j], tileNum, i, j));
}
createdLevel.push(tmpTileVec);
tmpTileVec = [];
}
return createdLevel;
}
function initLevelMoves(levelDesign, tilesArray) {
var width = levelDesign[0].length;
var height = levelDesign.length;
for (var i=0; i<height; i++){
for (var j=0; j<width; j++){
//Check if there is up tile
if (i+1 < height){
var upTile = tilesArray[i+1][j];
//Check if move is allowed
if (upTile.type == 'p' || upTile.type == 'U' ){
//Store tile
tilesArray[i][j].moves[1] = upTile;
}
}
//Check if there is down tile
if (0 <= i-1){
var downTile = tilesArray[i-1][j];
//Check if move is allowed
if (downTile.type == 'p' || downTile.type == 'U' ){
//Store tile
tilesArray[i][j].moves[2] = downTile;
}
}
//Check if there is left tile
if (0 <= j-1){
var leftTile = tilesArray[i][j-1];
//Check if move is allowed
if (leftTile.type == 'p' || leftTile.type == 'U' ){
//Store tile
tilesArray[i][j].moves[10] = leftTile;
}
}
//Check if there is right tile
if (j+1 < width){
var rightTile = tilesArray[i][j+1];
//Check if move is allowed
if (rightTile.type == 'p' || rightTile.type == 'U' ){
//Store tile
tilesArray[i][j].moves[20] = rightTile;
}
}
//Store pellets
if ( tilesArray[i][j].type == 'p' || tilesArray[i][j].type == 'U'){
maze.pellets.push(tilesArray[i][j]);
maze.totalPellets++;
}
}
}
}
var maze = {
//The current maze level. 2D array created based on
//levelDesign. Extra members: level[][].moves[], level[][].num
level: [],
height: 0, //Height of current maze level
width: 0, //Width of current maze level
speed: 0.07, //Distance to move on every move
pellets: [], //Pellet tiles
totalPellets: 0, //Total maze pellets at any time
init: function(level, height, width){
this.level = level;
this.height = height;
this.width = width;
this.pellets = [];
this.totalPellets = 0;
}
};
var tileMold = {
baseEdge: 2.0, //Based on cube's initial coords(-1, 1)
scale: 1.0, //Scale factor to apply
scaleX: 0.0, //Scale factor for x-axis
scaleY: 0.4, //Scale factor for y-axis
scaleZ: 0.0, //Scale factor for z-axis
edge: 0.0, //The edge of each tile
transY: -5.0, //Translation of each tile on y-axis
zDirection: -1.0, //Tile propagation direction on z-axis
//Initialized parameters
init: function(){
this.scaleX = this.scale;
this.scaleZ = this.scale;
this.edge = this.baseEdge * this.scale;
}
};
var game = {
normalSpeed: 0.07, //Normal game speed
slowGhostSpeed: 0.02, //Power pellet mode, slow speed for ghosts
defGhostSpeed: 0.065, //The default speed at which ghosts move
curGhostSpeed: 0.065, //The current speed at which ghosts move
moveDirections: [1, 2, 10, 20], //Available move directions
gameOver: false, //Game Over
lives: 3, //pacman's current lives
lostLife: false, //pacman lost one life
ignoreKeys: false, //Ignore or not arrow keystrokes
gameCamera: true, //True is tracking camera, false Panoramic
powerMode: false, //For power pellets
levelUp: false, //For next level
powerModeDur: 6000, //How much time pacman is in power mode, in ms
score: -50, //The game score, 50 points for earch pellet
ghostsBusted: [], //Ghosts that were busted
levelNum: 1, //The current game level (e.g. 1, 2 etc)
init: function(){
this.ignoreKeys = false;
this.gameOver = false;
this.lostLife = false;
this.gameCamera = true;
this.powerMode = false;
this.levelUp = false;
this.lives = 3;
this.ghostSpeed = 0.065;
this.powerModeDur = 6000;
this.score = -50;
this.ghostsBusted = [];
}
}
function moveGhosts(ghost){
var move;
if (ghost.curDirection == 0){
//Make a random move from available moves
move = game.moveDirections[Math.floor(Math.random()*game.moveDirections.length)];
}else{
move = ghost.curDirection;
}
return move;
}
function checkGameplay(){
//Check if game is over
if (game.gameOver == false){
//Check if pacman lost a life
if (game.lostLife == true){
game.lives--;
displayInfo(game.score, game.lives);
//Check pacman's available lives
if (game.lives == 0){
//Game is Over
game.gameOver == true;
game.ignoreKeys = true;
gameControl.gameOver = true; //global variable
alert('The game is over');
}
else{
//inform the user
alert('You have: '+game.lives+' lives remaining!');
//RE INITIALIZE
//empty keys object
currentlyPressedKeys = {};
game.ignoreKeys = true;
game.lostLife = false;
game.gameCamera = true;
if (game.levelNum == 1)
pacman.init(104);
else if (game.levelNum == 2)
pacman.init(255);
var range = maze.pellets.length;
var rand = [];
//Initialize ghosts - Random unique tile generation
for (var i=0; i<ghosts.length; i++){
rand[i] = generateRandom(range, 20, rand[0], rand[1], rand[2]);
ghosts[i].init(maze.pellets[rand[i]].num);
}
//alert("Pacman was busted!");
console.log('pacman busted');
}
} else {
//Check if going to next level
if (game.levelUp == true){
game.levelNum++;
//Initialize the maze
initMaze(level2_design);
} else {
//Check if level complete
console.log()
if (maze.totalPellets == 0){
game.levelUp = true;
alert ("Congrats! Loading Next Level!");
}else{
game.ignoreKeys = false;
game.gameOver = false;
game.lostLife = false;
determineMove(pacman, game.normalSpeed);
//Check if in power pellet mode
if (game.powerMode == true){
game.gameCamera = false; //set panoramic camera
game.curGhostSpeed = game.slowGhostSpeed;
//Check if power mode's time is out
if (passedTime(game.powerModeDur)){
regenerateGhosts(game.ghostsBusted);
game.powerMode = false;
game.gameCamera = true; //set tracking camera
game.curGhostSpeed = game.defGhostSpeed;
}
}
detectCollisions(game.powerMode);
checkPellets();
for (var i=0; i<ghosts.length; i++){
ghosts[i].nextDirection = moveGhosts(ghosts[i]);
determineMove(ghosts[i], game.curGhostSpeed);
}
}
}
}
} else {
alert('GAME OVER! Sorry...');
game.ignoreKeys = true;
}
}
var timePoint = 0;
// Refresh every 'time' ms
function passedTime(timeMargin){
if (timePoint == 0){
timePoint = new Date().getTime();
}
var curTime = new Date().getTime();
if (curTime - timePoint > timeMargin){
timePoint = 0;
return true;
} else
return false;
}
function checkPellets(){
//Find current position
var xPos = pacman.mCenter[0];
var zPos = pacman.mCenter[1];
//Get coordinates of current tile
var i = pacman.curTile.indX;
var j = pacman.curTile.indZ;
if (pacman.curDirection == 1){
//Going up
var nextTile = maze.level[i+1][j];
if (nextTile.type !=""){
if (Math.abs(zPos-nextTile.mCenter[1]) < tileMold.edge/2){
if (nextTile.type =='U'){
game.powerMode = true;
}
nextTile.type = "";
maze.totalPellets--;
game.score += 50;
displayInfo(game.score, game.lives);
}
}
}else if (pacman.curDirection == 2){
//Going down
var nextTile = maze.level[i-1][j];
if (nextTile.type !=""){
if (Math.abs(zPos-nextTile.mCenter[1]) < tileMold.edge/2){
if (nextTile.type =='U'){
game.powerMode = true;
}
nextTile.type = "";
maze.totalPellets--;
game.score += 50;
displayInfo(game.score, game.lives);
}
}
}else if (pacman.curDirection == 10){
//Goind left
var nextTile = maze.level[i][j-1];
if (nextTile.type !=""){
if (Math.abs(xPos-nextTile.mCenter[0]) < tileMold.edge/2){
if (nextTile.type =='U'){
game.powerMode = true;
}
nextTile.type = "";
maze.totalPellets--;
game.score += 50;
displayInfo(game.score, game.lives);
}
}
}else if (pacman.curDirection == 20){
//Goind right
var nextTile = maze.level[i][j+1];
if (nextTile.type !=""){
if (Math.abs(xPos-nextTile.mCenter[0]) < tileMold.edge/2){
if (nextTile.type =='U'){
game.powerMode = true;
}
nextTile.type = "";
maze.totalPellets--;
game.score += 50;
displayInfo(game.score, game.lives);
}
}
}else if (pacman.curDirection == 0){
//Stopped
if (pacman.curTile.type =='p' || pacman.curTile.type =='U'){
pacman.curTile.type = "";
maze.totalPellets--;
game.score += 50;
displayInfo(game.score, game.lives);
}
}
}
function regenerateGhosts(ghostsBusted) {
//Check if any ghosts were busted
for (var i=0; i<ghostsBusted.length; i++){
var tileNum = generateRandom(maze.pellets.length, pacman.curTile, 0, 0, 0);
ghostsBusted[i].init(maze.pellets[tileNum].num);
}
ghostsBusted = [];
}
function initMaze(levelDesign) {
console.log('initMaze');
//Set the mold for maze tiles
tileMold.init();
//Create level
var level = createLevel(levelDesign);
//level width
var width = level[0].length;
//level height
var height = level.length;
//Initialize maze with level
maze.init(level, height, width);
//Calculate coordinates and mass center for tiles
calculateMazeCoords(maze.level, maze.height, maze.width, tileMold.edge, tileMold.zDirection);
//Initialize possible moves from evey tile
initLevelMoves(levelDesign, maze.level);
//Create and initialize pacman
pacman = null;
pacman = new character("pacman");
//Create ghosts
ghosts = [];
ghosts.push(new character("blinky"));
ghosts.push(new character("pinky"));
ghosts.push(new character("inky"));
ghosts.push(new character("clyde"));
var range = maze.pellets.length;
var rand = [];
//Initialize ghosts - Random unique tile generation
for (var i=0; i<ghosts.length; i++){
rand[i] = generateRandom(range, 20, rand[0], rand[1], rand[2]);
ghosts[i].init(maze.pellets[rand[i]].num);
}
//Initialize game
game.init();
if (game.levelNum == 1)
pacman.init(104);
else if (game.levelNum == 2)
pacman.init(255);
}
function detectCollisions(powerMode){
//For circles CHECK 2*r, r=radius
var distFromGhostX = [];
var distFromGhostZ = [];
for (var i=0; i<ghosts.length; i++){
if ( Math.abs(pacman.curTile.num - ghosts[i].curTile.num) == 1) {
distFromGhostX[i] = Math.abs(pacman.mCenter[0]-ghosts[i].mCenter[0]);
if (distFromGhostX[i] < tileMold.edge-maze.speed){
if (powerMode == true){ //power mode
displayInfo(game.score, game.lives);
game.ghostsBusted.push(ghosts[i]);
ghosts[i].busted = true;
} else
game.lostLife = true;
}
}else if (Math.abs(pacman.curTile.num - ghosts[i].curTile.num) == maze.width){
distFromGhostZ[i] = Math.abs(pacman.mCenter[1]-ghosts[i].mCenter[1]);
if (distFromGhostZ[i] < tileMold.edge-maze.speed){
if (powerMode == true){//power mode
displayInfo(game.score, game.lives);
game.ghostsBusted.push(ghosts[i]);
ghosts[i].busted = true;
} else
game.lostLife = true;
}
}
}
}
var pacman = {};
var ghosts = [];
function character(name) {
this.mCenter = []; //The center of mass
//Code direction and movement
//(1) -> moving up, (2) moving down, (10) moving left
//(20) -> moving right, (0) -> stopped
this.curDirection = 0;
this.nextDirection = 0;
this.scale = 1.0; //Scale character
this.curTile = {}; //Reference to the current tile