forked from christkv/mongoman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
472 lines (432 loc) · 21.9 KB
/
game.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
// Game state variables
var maingame = null;
var maze = null;
var client = null;
var currentGhosts = {};
var newObjects = [];
var remotePlayerPositionUpdates = {};
var remotePlayersInformationById = {};
var sound = true;
// User states
var isMongoman = false;
var playerName = '';
// The user moved
var updateObject = null;
// The board changed
var boardUpdateObjects = [];
// Load the game box
gbox.onLoad(function () {
help.akihabaraInit({
title: "Mongoman"
});
// Load the logo, do at the start so it will be there first for the title screen
gbox.addImage("logo","resources/capman/logo.png");
// Load the sprite sheet
gbox.addImage("cels","resources/capman/cels.png");
// Load the font set
gbox.addImage("font","resources/capman/font.png");
// Font are mapped over an image, setting the first letter, the letter size, the length of all rows of letters and a horizontal/vertical gap.
gbox.addFont({id: "small", image: "font", firstletter: " ", tileh: 8, tilew: 8, tilerow: 255, gapx: 0, gapy: 0});
// Cut up all the sprites
gbox.addTiles({id:"mongoman",image:"cels",tileh:12,tilew:12,tilerow:10,gapx:0,gapy:0});
gbox.addTiles({id:"ghost1",image:"cels",tileh:12,tilew:12,tilerow:3,gapx:0,gapy:12});
gbox.addTiles({id:"ghost2",image:"cels",tileh:12,tilew:12,tilerow:3,gapx:36,gapy:12});
gbox.addTiles({id:"ghost3",image:"cels",tileh:12,tilew:12,tilerow:3,gapx:36*2,gapy:12});
gbox.addTiles({id:"ghost4",image:"cels",tileh:12,tilew:12,tilerow:3,gapx:36*3,gapy:12});
gbox.addTiles({id:"ghostscared",image:"cels",tileh:12,tilew:12,tilerow:3,gapx:36*4,gapy:12});
gbox.addTiles({id:"ghosteaten",image:"cels",tileh:12,tilew:12,tilerow:3,gapx:36*5,gapy:12});
gbox.addTiles({id:"bonus",image:"cels",tileh:12,tilew:12,tilerow:8,gapx:0,gapy:24});
gbox.addTiles({id:"maze",image:"cels",tileh:4,tilew:4,tilerow:10,gapx:0,gapy:36});
// Player
gbox.addTiles({id:"playerghost",image:"cels",tileh:12,tilew:12,tilerow:3,gapx:0,gapy:12});
// Now let's load some audio samples...
var audioserver = "resources/audio/";
gbox.addAudio("eatghost", [audioserver+"laser.mp3",audioserver+"laser.ogg"],{channel:"sfx"});
// determine browser
var filetype;
var agent = navigator.userAgent.toLowerCase();
// adjust for browser
if(agent.indexOf("chrome") > -1){
filetype = ".mp3";
} else if(agent.indexOf("opera") > -1) {
filetype = ".ogg";
} else if(agent.indexOf("firefox") > -1) {
filetype = ".ogg";
} else if(agent.indexOf("safari") > -1) {
filetype = ".mp3";
} else if(agent.indexOf("msie") > -1) {
filetype = ".mp3";
}
// Load all the audio using SoundJS
SoundJS.onLoadQueueComplete = function() {
// The loadAll function loads all the resources and triggers the main game loop
gbox.loadAll(go);
// Start the game
gbox.go();
};
// Batch the audio
SoundJS.addBatch([
{name:"eat", src:(audioserver + "eat" + filetype), instances:20},
{name:"eatghost", src:(audioserver + "laser" + filetype), instances:1},
{name:"powerpill", src:(audioserver + "powerup3" + filetype), instances:1},
{name:"die", src:(audioserver + "die" + filetype), instances:1},
{name:"music", src:(audioserver + "capman-ingame" + filetype), instances:1}]);
}, false);
// Start game function
var go = function() {
gbox.setGroups(["background", "ghosts", "player", "sparks", "gamecycle"]);
// Set up the main loop object
maingame = gamecycle.createMaingame("gamecycle","gamecycle");
maingame.bullettimer = 0;
// Set method called each time we change the level
maingame.changeLevel = function(level) {
// start the music
SoundJS.play("music", null, 0.2, true);
// Reset local score
maingame.hud.setWidget("score",{widget:"label",font:"small",value:0, dx:240, dy:25, clear:true});
// Let's add the player
if(isMongoman) {
gbox.addObject(createPlayerMongoman());
} else {
gbox.addObject(createPlayerGhost());
}
// For all ghosts set's the to chasing status
var keys = Object.keys(currentGhosts);
for(var i = 0; i < keys.length; i++) {
currentGhosts[keys[i]].status = 'chasing';
currentGhosts[keys[i]].tileset = currentGhosts[keys[i]].id;
}
// Set player ghost to chasing if it exists
var playerGhost = gbox.getObject("player", "playerghost");
if(playerGhost) {
playerGhost.status = 'chasing';
playerGhost.tileset = playerGhost.id;
}
// Create a maze object based on the tilemap, mapping function
// and the function that determines if a tile is solid or not
maze = help.finalizeTilemap({
tileset: "maze",
map: help.asciiArtToMap(tilemap, tilemapTranslation),
tileIsSolid: isTileSolid
});
// Create a canvas using the calculated size of the maze
gbox.createCanvas("mazecanvas", {w:maze.w,h:maze.h});
// Render the tilemap to the canvas
gbox.blitTilemap(gbox.getCanvasContext("mazecanvas"), maze);
// Set up the pill count
this.pillscount = 0;
for (var y=0;y<maze.map.length;y++) // Let's iterate all the rows...
for (var x=0;x<maze.map[y].length;x++) // ... and all the colums
if(maze.map[y][x] > 7) this.pillscount++; // If the row/column contains a "pill" tile (8 for plain pill, 9 for powerpill), let's
// Start the game
this.newLife();
}
maingame.gameIsOver = function() {
// Reset game
this.changeLevel();
// Return game over
return true;
}
maingame.newLife = function() {
maingame.bullettimer=0
// Spawn the main character
if(isMongoman) {
var object = gbox.getObject("player","mongoman");
toys.topview.spawn(object,{x:maze.hw-6,y:maze.hh+50,accx:0,accy:0,xpushing:false,ypushing:false});
} else {
var object = gbox.getObject("player","playerghost");
toys.topview.spawn(object,{x:maze.hw-8,y:maze.hh-20,accx:0,accy:0,xpushing:false,ypushing:false});
}
}
// This method is triggered once pr game
maingame.initializeGame = function() {
//
// When the web socket connects
//
var onMessageCallback = function(message) {
// JSON message
if(message['state'] == 'initialize') {
isMongoman = message['isMongoman'];
playerName = message['name'];
// Set up the name
maingame.hud.setWidget("label", {widget:"label", font:"small", value:playerName, dx:240, dy:10, clear:true});
// Reset local score
maingame.hud.setWidget("score",{widget:"label",font:"small",value:0, dx:240, dy:25, clear:true});
// Let's add the object that will draw the maze
gbox.addObject(drawMaze);
} else if(message['state'] == 'dead') {
// Fetch the active mongoman
var mongoman = isMongoman ? gbox.getObject("player", "mongoman") : gbox.getObject("ghosts", "mongoman");
if(mongoman) {
// Stop the game for a time
maingame.bullettimer = 10;
// Kill the character
mongoman.kill();
}
// Destroy groups
gbox.clearGroup("ghosts");
gbox.clearGroup("player");
gbox.purgeGarbage();
// Initialize all state
currentGhosts = {};
newObjects = [];
remotePlayerPositionUpdates = {};
remotePlayersInformationById = {};
isMongoman = false;
updateObject = null;
boardUpdateObjects = [];
// Change level
if(!isMongoman) maingame.gotoLevel(maingame.level+1);
// Close client
if(client) client.close();
// Create client instance
client = new GameCommunication(document.URL, 'game', onMessageCallback);
// Start the client
client.connect(function() {
// Dispatch a message asking to intialize the connection
client.dispatchCommand({type:'initialize'});
});
} else if(message['state'] == 'ghostdead') {
// if(sound) gbox.hitAudio("eatghost");
if(sound) SoundJS.play('eatghost');
// Check if it's a remote ghost and if it is kill it
if(currentGhosts[message['id']] != null) {
currentGhosts[message['id']].kill();
return;
}
// Not in the ghosts list, then it's us
var playerGhost = gbox.getObject("player", "playerghost");
if(playerGhost) {
playerGhost.kill();
}
} else if(message['state'] == "mongowin") {
// Destroy groups
gbox.clearGroup("ghosts");
gbox.clearGroup("player");
gbox.purgeGarbage();
// Initialize all state
currentGhosts = {};
newObjects = [];
remotePlayerPositionUpdates = {};
remotePlayersInformationById = {};
isMongoman = false;
updateObject = null;
boardUpdateObjects = [];
// Change level
if(!isMongoman) maingame.gotoLevel(maingame.level+1);
// Close client
if(client) client.close();
// Create client instance
client = new GameCommunication(document.URL, 'game', onMessageCallback);
// Start the client
client.connect(function() {
// Dispatch a message asking to intialize the connection
client.dispatchCommand({type:'initialize'});
});
} else if(message['b'] != null) {
// Check if we have a ghost for this user and add one if there is none
if(currentGhosts[message.id] == null) {
newObjects.push(message);
}
// Add to list of character updates
boardUpdateObjects.push(message);
}
}
// Initialize all state
currentGhosts = {};
newObjects = [];
remotePlayerPositionUpdates = {};
remotePlayersInformationById = {};
isMongoman = false;
updateObject = null;
boardUpdateObjects = [];
// If client is still connected close it
if(client) {
client.close();
}
// Create client instance
client = new GameCommunication(document.URL, 'game', onMessageCallback);
// Start the client
client.connect(function() {
// Dispatch a message asking to intialize the connection
client.dispatchCommand({type:'initialize'});
});
}
maingame.gameMenu = function(reset) {
return true;
}
maingame.gameEvents = function() {
// If no more pills let's start a new level
if(maingame.pillscount == 0) {
// Go to new level
maingame.gotoLevel(maingame.level + 1);
// Fire ended game message
client.dispatchCommand({type:'mongowin', score:maingame.hud.getNumberValue("score","value")})
}
// If we are counting down the time
if(this.bullettimer > 0) this.bullettimer--;
// If the user changed course send an update to the server
if(updateObject != null) {
// Serialize the update state and send to server
var data = BSON.serialize({'$set': {'pos': updateObject}}, false, true, false)
// Send object
client.dispatchCommand(data.buffer);
}
//
// We have new remote players, add them to the rendering pipeline
//
while(newObjects.length > 0) {
// Remove the ghost
var object = newObjects.pop();
// Check if it's a ghost or a pacman
if(currentGhosts[object.id] == null && object.id > 0 && object.role == 'g' && object.pos.x != 0 && object.pos.y != 0) {
// Create a new ghost id
var id = Object.keys(currentGhosts).length + 1;
// Add remote ghost object
var remotePlayer = createRemoteGhostPlayer({conId:object.id, id:id, x: object.pos.x, y: object.pos.y, tileset:"ghost"+id});
remotePlayerPositionUpdates[object.id] = {pos:null, nextPos:object.pos};
gbox.addObject(remotePlayer);
// Update the ghost
currentGhosts[object.id] = remotePlayer;
} else if(currentGhosts[object.id] == null && object.id > 0 && object.role == 'm' && object.pos.x != 0 && object.pos.y != 0) {
// Add remote mongoman
var remotePlayer = createRemoteMongoManPlayer({conId:object.id, x: object.pos.x, y: object.pos.y});
remotePlayerPositionUpdates[object.id] = {pos:null, nextPos:object.pos};
gbox.addObject(remotePlayer);
// Update the ghost
currentGhosts[object.id] = remotePlayer;
}
}
//
// Update any objects with new positions
//
if(boardUpdateObjects.length > 0) {
// Add a reference
var reference = boardUpdateObjects;
// Null out update as done
boardUpdateObjects = [];
// Process all the board updates
for(var i = 0; i < reference.length; i++) {
var update = reference[i];
// It's a remote player, update position
if(remotePlayerPositionUpdates[update.id] != null) {
// remotePlayerPositionUpdates[update.id].nextPos = update.pos;
var remotePlayer = remotePlayerPositionUpdates[update.id];
if(remotePlayer['pos'] == null) {
remotePlayerPositionUpdates[update.id] = {pos:null, nextPos:update.pos};
} else {
remotePlayer.nextPos = update.pos;
}
} else {
remotePlayerPositionUpdates[update.id] = {pos:null, nextPos:update.pos};
}
}
}
}
// Show the intro screen
maingame.gameTitleIntroAnimation = function(reset) {
if(reset) {
toys.resetToy(this,"rising");
} else {
// Clear the screen
gbox.blitFade(gbox.getBufferContext(),{alpha:1});
// Show the logos
toys.logos.linear(this,"rising",{image:"logo",x:gbox.getScreenHW()-gbox.getImage("logo").hwidth,y:20,sx:gbox.getScreenHW()-gbox.getImage("logo").hwidth,sy:gbox.getScreenH(),speed:1,audioreach:"eatghost"});
}
};
}
//
// Draws the maze for the game
//
var drawMaze = {
id:"bg",
group:"background",
// This action is executed the first time the object is called, so...
initialize:function() {
// We place the camera a bit down, since the full maze doesn't fit the screen.
gbox.setCameraY(2, {w: maze.w, h: maze.h});
},
blit:function() {
// Blit the background
var drawingCanvas = gbox.getCanvas("mazecanvas");
// Clear the entire screen
gbox.blitFade(gbox.getBufferContext(),{alpha: 1});
gbox.blit(gbox.getBufferContext(), drawingCanvas, {dx: 0,dy: 0,dw: drawingCanvas.width, dh:drawingCanvas.height, sourcecamera:true});
}
}
// ----------------------------------------------------------------------------
//
// Map functions
//
// ----------------------------------------------------------------------------
var isTileSolid = function(obj, t) {
return (t!==null)&&
((t<6)||
((t==6)&&(obj.status!="chasing")&&(obj.status!="goin")));
}
// The tilemap used for the game
var tilemap = [
"||T----------------------------------------------------TxxT----------------------------------------------------T||",
"|||| ||xx|| ||||",
"|||| . . . . . . . . . . . . ||xx|| . . . . . . . . . . . . ||||",
"|||| ||xx|| ||||",
"|||| . T------------T . T----------------T . ||xx|| . T----------------T . T------------T . ||||",
"|||| ||xxxxxxxxxx|| ||xxxxxxxxxxxxxx|| ||xx|| ||xxxxxxxxxxxxxx|| ||xxxxxxxxxx|| ||||",
"|||| o ||xxxxxxxxxx|| . ||xxxxxxxxxxxxxx|| . ||xx|| . ||xxxxxxxxxxxxxx|| . ||xxxxxxxxxx|| o ||||",
"|||| ||xxxxxxxxxx|| ||xxxxxxxxxxxxxx|| ||xx|| ||xxxxxxxxxxxxxx|| ||xxxxxxxxxx|| ||||",
"|||| . L------------J . L----------------J . L----J . L----------------J . L------------J . ||||",
"|||| ||||",
"|||| . . . . . . . . . . . . . . . . . . . . . . . . . . ||||",
"|||| ||||",
"|||| . T------------T . T----T . T----------------------------T . T----T . T------------T . ||||",
"|||| ||xxxxxxxxxx|| ||xx|| ||xxxxxxxxxxxxxxxxxxxxxxxxxx|| ||xx|| ||xxxxxxxxxx|| ||||",
"|||| . L------------J . ||xx|| . L------------TxxT------------J . ||xx|| . L------------J . ||||",
"|||| ||xx|| ||xx|| ||xx|| ||||",
"|||| . . . . . . ||xx|| . . . . ||xx|| . . . . ||xx|| . . . . . . ||||",
"|||| ||xx|| ||xx|| ||xx|| ||||",
"||L--------------------T . ||xxL------------T ||xx|| T------------Jxx|| . T--------------------J||",
"L--------------------T|| ||xxxxxxxxxxxxxx|| ||xx|| ||xxxxxxxxxxxxxx|| ||T--------------------J",
" |||| . ||xxT------------J L----J L------------Txx|| . |||| ",
" |||| ||xx|| ||xx|| |||| ",
" |||| . ||xx|| ||xx|| . |||| ",
" |||| ||xx|| ||xx|| |||| ",
" |||| . ||xx|| T---------~~~~~~~~~~---------T ||xx|| . |||| ",
"---------------------J|| ||xx|| || || ||xx|| ||L---------------------",
"-----------------------J . L----J || || L----J . L-----------------------",
" || || ",
" . || || . ",
" || || ",
"-----------------------T . T----T || || T----T . T-----------------------",
"---------------------T|| ||xx|| || || ||xx|| ||T---------------------",
" |||| . ||xx|| L----------------------------J ||xx|| . |||| ",
" |||| ||xx|| ||xx|| |||| ",
" |||| . ||xx|| ||xx|| . |||| ",
" |||| ||xx|| ||xx|| |||| ",
" |||| . ||xx|| T----------------------------T ||xx|| . |||| ",
"T--------------------J|| ||xx|| ||xxxxxxxxxxxxxxxxxxxxxxxxxx|| ||xx|| ||L--------------------T",
"||T--------------------J . L----J L------------TxxT------------J L----J . L--------------------T||",
"|||| ||xx|| ||||",
"|||| . . . . . . . . . . . . ||xx|| . . . . . . . . . . . . ||||",
"|||| ||xx|| ||||",
"|||| . T------------T . T----------------T . ||xx|| . T----------------T . T------------T . ||||",
"|||| ||xxxxxxxxxx|| ||xxxxxxxxxxxxxx|| ||xx|| ||xxxxxxxxxxxxxx|| ||xxxxxxxxxx|| ||||",
"|||| . L--------Txx|| . L----------------J . L----J . L----------------J . ||xxT--------J . ||||",
"|||| ||xx|| ||xx|| ||||",
"|||| o . . ||xx|| . . ||xx|| . . o ||||",
"|||| ||xx|| ||xx|| ||||",
"||L--------T . ||xx|| . T----T . T----------------------------T . T----T . ||xx|| . T--------J||",
"||xxxxxxxx|| ||xx|| ||xx|| ||xxxxxxxxxxxxxxxxxxxxxxxxxx|| ||xx|| ||xx|| ||xxxxxxxx||",
"||T--------J . L----J . ||xx|| . L------------TxxT------------J . ||xx|| . L----J . L--------T||",
"|||| ||xx|| ||xx|| ||xx|| ||||",
"|||| . . . . . . ||xx|| . . . . ||xx|| . . . . ||xx|| . . . . . . ||||",
"|||| ||xx|| ||xx|| ||xx|| ||||",
"|||| . T--------------------JxxL------------T . ||xx|| . T------------JxxL--------------------T . ||||",
"|||| ||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|| ||xx|| ||xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|| ||||",
"|||| . L------------------------------------J . ||xx|| . L------------------------------------J . ||||",
"|||| ||xx|| ||||",
"|||| . . . . . . . . . . . . ||xx|| . . . . . . . . . . . . ||||",
"|||| ||xx|| ||||",
"||L----------------------------------------------------JxxL----------------------------------------------------J||",
]
// The tilemap translation array
var tilemapTranslation = [[null," "],[0,"||"],[1,"--"],[2,"L-"],[3,"-J"],[4,"T-"],[5,"-T"],[6,"~~"],[7,"xx"],[8," ."],[9," o"]];