-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
660 lines (604 loc) · 24.2 KB
/
Copy pathscript.js
File metadata and controls
660 lines (604 loc) · 24.2 KB
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
var canvas, ctx, window_x, element ={type:0, i:0 }, ANIM;
function docSetup(){
canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
window_x = 0,
element ={type:0, i:0 }
}
function timestamp() {
return window.performance && window.performance.now ? window.performance.now() : new Date().getTime();
}
function getItem(item){
if(localStorage)
return localStorage.getItem(item);
else
return null;
}
function setItem(item, val){
if(localStorage){
localStorage.setItem(item, val);
}
}
var scoreTable = JSON.parse(getItem("table")) || [];
scoreTable.get = function(){
this.sort(function(a,b) {
return b[2] - a[2];
});
var n, content = "";
for(n = 0; n < scoreTable.length; n++){
content += "<tr><td>" + scoreTable[n][0] + "</td>" + "<td>" + scoreTable[n][1] + "</td>" + "<td>" + scoreTable[n][2] + "</td></tr>";
}
return content;
};
scoreTable.add = function(name, data){
var date = new Date(), time = date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
this.push([time, name, data]);
setItem("table", JSON.stringify(this));
};
window.onload = function(){
document.getElementById("records").innerHTML = scoreTable.get();
}
var mapManager = {
mapData: null,
tLayer: null,
xCount: 0, //20
yCount: 0, //6
imgLoadCount: 0, // количество загруженных изображений
imgLoaded: false, // изображения не загружены
jsonLoaded: false, // json не загружен
tSize: {x: 32, y: 32},
mapSize: {x: 300, y: 20},
view: {x: 0, y: 0, w: 9600, h: 650},
tilesets: [],
//!!!
// ajax-загрузка карты
loadMap: function (path) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
mapManager.parseMap(request.responseText);
}
};
request.open("GET", path, true);
request.send();
},
parseMap: function (tilesJSON) {
this.mapData = JSON.parse(tilesJSON); //разобрать JSON
this.xCount = this.mapData.width; // соэранение ширины
this.yCount = this.mapData.height; // сохранение высоты
this.tSize.x = this.mapData.tilewidth; // сохранение размера блока
this.tSize.y = this.mapData.tileheight; // сохранение размера блока
this.mapSize.x = this.xCount * this.tSize.x; // вычисление размера карты
this.mapSize.y = this.yCount * this.tSize.y;
for (var i = 0; i < this.mapData.tilesets.length; i++) {
var img = new Image(); // создаем переменную для хранения изображений
img.onload = function () { // при загрузке изображения
mapManager.imgLoadCount++;
if (mapManager.imgLoadCount === mapManager.mapData.tilesets.length) {
mapManager.imgLoaded = true; // загружены все изображения
}
};
img.src = this.mapData.tilesets[i].image; // задание пути к изображению
var t = this.mapData.tilesets[i]; //забираем tileset из карты
var ts = { // создаем свой объект tileset
firstgid: t.firstgid, // с него начинается нумерация в data
image: img,
name: t.name, // имя элемента рисунка
xCount: Math.floor(t.imagewidth / mapManager.tSize.x), // горизонталь
yCount: Math.floor(t.imageheight / mapManager.tSize.y) // вертикаль
}; // конец объявления ts
this.tilesets.push(ts); // сохраняем tileset в массив
} // окончание цикла for
this.jsonLoaded = true; // когда разобран весь json
},
draw: function (ctx) { // отрисовка карты в контексте
// если карта не загружена, то повторить прорисовку через 100 мс
if (!mapManager.imgLoaded || !mapManager.jsonLoaded) {
setTimeout(function () {
mapManager.draw(ctx);
}, 100);
} else {
var layerCount = 0;
if (this.tLayer === null) {// проверка, что tLayer настроен
for (var id = 0; id < this.mapData.layers.length; id++) {
// проходим по всем layer карты
var layer = this.mapData.layers[id];
if (layer.type === "tilelayer") {
this.tLayer = layer;
//break; !!!
}
}
}
for (var i = 0; i < this.tLayer.data.length; i++) { // проходим по всей карте !!!
if (this.tLayer.data[i] !== 0) { // если данных нет, то пропускаем
var tile = this.getTile(this.tLayer.data[i]); // получение блока по индексу
var pX = (i % this.xCount) * this.tSize.x; // вычисляем x в пикселях
var pY = Math.floor(i / this.xCount) * this.tSize.y;
// не рисуем за пределами видимой зоны
if (!this.isVisible(pX, pY, this.tSize.x, this.tSize.y))
continue;
// сдвигаем видимую зону
pX -= this.view.x;
pY -= this.view.y;
ctx.drawImage(tile.img, tile.px, tile.py, this.tSize.x, this.tSize.y, pX - window_x, pY, this.tSize.x, this.tSize.y); //
//отрисовка в контексте
}
}
}
},
getTile: function (tileIndex) { // индекс блока
var tile = {
img: null, // изображение tileset
px: 0, py: 0 // координаты блока в tileset
};
var tileset = this.getTileset(tileIndex);
tile.img = tileset.image; // изображение искомого tileset
var id = tileIndex - tileset.firstgid; // индекс блока в tileset
// блок прямоугольный, остаток от деления на xCount дает х в tileset
var x = id % tileset.xCount;
var y = Math.floor(id / tileset.xCount);
tile.px = x * mapManager.tSize.x;
tile.py = y * mapManager.tSize.y;
return tile; // возвращаем тайл для отображения
},
getTileset: function (tileIndex) { // получение блока по индексу
for (var i = mapManager.tilesets.length - 1; i >= 0; i--) {
// в каждом tilesets[i].firstgid записано число, с которого начинается нумерация блоков
if (mapManager.tilesets[i].firstgid <= tileIndex) {
// если индекс первого блока меньше , либо равен искомому, значит этот tileset и нужен
return mapManager.tilesets[i];
}
}
return null;
},
isVisible: function (x, y, width, height) {
// не рисуем за пределами видимой зоны
return !(x + width < this.view.x || y + height < this.y || x > this.view.x + this.view.w || y > this.view.y + this.view.h);
},
parseEntities: function () { // разбор слоя типа objectgroup
if (!mapManager.imgLoaded || !mapManager.jsonLoaded) {
setTimeout(function () {
mapManager.parseEntities();
}, 100);
} else
for (var j = 0; j < this.mapData.layers.length; j++) // просмотр всех слоев
if (this.mapData.layers[j].type === 'objectgroup') {
var entities = this.mapData.layers[j]; // слой с объектами следует разобрать
for (var i = 0; i < entities.objects.length; i++) {
var e = entities.objects[i];
try {
var obj = Object.create(gameManager.factory[e.type]);
obj.name = e.name;
obj.pos_x = e.x;
obj.pos_y = e.y;
obj.size_x = e.width;
obj.size_y = e.height;
if (obj.name === 'Player') {
obj.dirSprite = '3_2';
gameManager.initPlayer(obj);
}
gameManager.entities.push(obj);
} catch (ex) {
console.log("Error while creating: [" + e.gid + "]" + e.type + " " + ex);
}
}
}
},
getTilesetIdx: function (x, y) {
// получить блок по координатам на карте
var wX = x;
var wY = y;
var idx = Math.floor(wY / this.tSize.y) * this.xCount + Math.floor(wX / this.tSize.x);
return this.tLayer.data[idx];
}
};
var spriteManager = {
image: new Image(),
sprites: [],
imgLoaded: false,
jsonLoaded: false,
loadAtlas: function (atlasJson, atlasImg) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
spriteManager.parseAtlas(request.responseText);
}
};
request.open("GET", atlasJson, true);
request.send();
this.loadImg(atlasImg);
},
loadImg: function (imgName) { // загрузка изображения
this.image.onload = function () {
spriteManager.imgLoaded = true;
};
this.image.src = imgName;
},
parseAtlas: function (atlasJSON) { // разбор атласа с обеъектами
var atlas = JSON.parse(atlasJSON);
for (var name in atlas.frames) { // проход по всем именам в frames
var frame = atlas.frames[name].frame; // получение спрайта и сохранение в frame
this.sprites.push({name: name, x:frame.x, y: frame.y, w: frame.w, h: frame.h}); // сохранение характеристик frame в виде объекта
}
this.jsonLoaded = true; // атлас разобран
},
drawSprite: function (ctx, name, x, y) {
// если изображение не загружено, то повторить запрос через 100 мс
if (!this.imgLoaded || !this.jsonLoaded) {
setTimeout(function () {
spriteManager.drawSprite(ctx, name, x, y);
}, 100);
} else {
var sprite = this.getSprite(name); // получить спрайт по имени
if (!mapManager.isVisible(x, y, sprite.w, sprite.h))
return; // не рисуем за пределами видимой зоны
x -= mapManager.view.x;
y -= mapManager.view.y;
// отображаем спрайт на холсте
ctx.drawImage(this.image, sprite.x, sprite.y, sprite.w, sprite.h, x-window_x, y, sprite.w, sprite.h);
// }
}
},
getSprite: function (name) { // получить спрайт по имени
for (var i = 0; i < this.sprites.length; i++) {
var s = this.sprites[i];
if (s.name === name)
return s;
}
return null; // не нашли спрайт
}
};
var eventsManager = {
bind: [], // сопоставление клавиш действиям
action: [], // действия
setup: function () { // настройка сопоставления
this.bind[87] = 'up'; // a - двигаться влево
this.bind[83] = 'down'; // d - двигаться вправо
document.body.addEventListener("keydown", this.onKeyDown);
document.body.addEventListener("keyup", this.onKeyUp);
},
onKeyDown: function (event) {
var action = eventsManager.bind[event.keyCode];
if (action) {
if (action) // проверка на action === true
eventsManager.action[action] = true; // выполняем действие
}
},
onKeyUp: function (event) {
var action = eventsManager.bind[event.keyCode];
if (action)
eventsManager.action[action] = false; // отменили действие
}
};
var physicManager = {
update: function (obj) {
if (obj.move_x === 0 && obj.move_y === 0)
return "stop"; // скорости движения нулевые
var newX = obj.pos_x + Math.floor(obj.move_x * obj.speed_x);
var newY = obj.pos_y + Math.floor(obj.move_y * obj.speed);
var e = this.entityAtXY(obj, newX, newY); // объект на пути
if (e !== null && obj.onTouchEntity) // если есть конфликт
obj.onTouchEntity(e); // разбор конфликта внутри объекта
//Если есть препятствие
if (e === null) { // перемещаем объект на свободное место
obj.pos_x = newX;
obj.pos_y = newY;
} else
return "break"; // дальше двигаться нельзя
//!!!!!!!
switch (obj.move_y) {
case -1: // двигаемся влево
return "up";
break;
case 1: // двигаемся вправо
return "down";
break;
}
},
entityAtXY: function (obj, x, y) { // поиск объекта по координатам
for (var i = 0; i < gameManager.entities.length; i++) {
var e = gameManager.entities[i]; // рассматриваем все объекты на карте
if (e.name !== obj.name) { // имя не совпадает
if (x + obj.size_x < e.pos_x || // не пересекаются
y + obj.size_y < e.pos_y ||
x > e.pos_x + e.size_x ||
y > e.pos_y + e.size_y)
continue;
return e; // найден объект
}
}
return null; // объект не найден
}
};
var soundManager = {
src_array: ['music/car.mp3','music/tank.mp3','music/break.mp3','music/winner.mp3','music/fuel.wav', 'music/levelup.wav'],
Audio: new Audio(),
Music: new Audio(),
done: false,
init: function(){
if(!this.done){
this.Music.src = "music/background.wav";
this.Music.loop = true;
this.Music.volume = 0.3;
this.done = true;
}
},
playBG: function(x){
if(x)
this.Music.play();
else
this.Music.pause();
},
playSound: function(x){
console.log(x);
this.Audio.pause();
this.Audio.src = this.src_array[x - 1];
this.Audio.play();
},
stopAll: function(){
this.Audio.pause();
this.Music.pause();
}
};
var Entity = {
pos_x: 0, pos_y: 0, // позиция объекта
size_x: 0, size_y: 0, // размеры объекта
extend: function (extendProto) { // расширение сущности
var object = Object.create(this); // создание нового объекта
for (var property in extendProto) { // для всех свойств нового объекта
if (this.hasOwnProperty(property) || typeof object[property] === 'undefined') {
// если свойства отсутствуют в родительском объекте, то добавляем
object[property] = extendProto[property];
}
}
return object;
}
};
var Fuel = Entity.extend({
dirSprite: "7",
draw: function (ctx) {
spriteManager.drawSprite(ctx, this.dirSprite, this.pos_x, this.pos_y);
},
kill: function () {
gameManager.kill(this);
},
update: function () {
}
});
var Object1 = Entity.extend({
move_x: 0,
move_y: 0,
draw: function (ctx) {// прорисовка объекта
}
});
var Object2 = Entity.extend({
dirSprite: "5",
draw: function (ctx) {
spriteManager.drawSprite(ctx, this.dirSprite, this.pos_x, this.pos_y);
},
kill: function () {
gameManager.kill(this);
},
update: function () {
}
});
var Lv = Entity.extend({
dirSprite: "6",
draw: function (ctx) {
spriteManager.drawSprite(ctx, this.dirSprite, this.pos_x, this.pos_y);
},
kill: function () {
gameManager.kill(this);
},
update: function () {
}
});
var Border = Entity.extend({
move_x: 0,
move_y: 0,
draw: function (ctx) {// прорисовка объекта
}
});
var Finish = Entity.extend({
move_x: 0,
move_y: 0,
draw: function (ctx) {// прорисовка объекта
}
});
var Player = Entity.extend({
move_x: 0, move_y: 0,
direction: 1,
deltaSprite: 1000,
dirSprite: "3_1",
speed: 5,
speed_x: 5,
draw: function (ctx) {
if(element.type===0){
this.deltaSprite++;
if(this.deltaSprite % 10 == 0){
this.dirSprite= "3_1";
if(this.deltaSprite % 20 == 0){
this.dirSprite= "3_2";
}
}
}
spriteManager.drawSprite(ctx, this.dirSprite, this.pos_x, this.pos_y);
},
update: function () {
physicManager.update(this);
},
onTouchEntity: function (obj) {
if (obj.name.match(/fuel/)) {
obj.kill();
this.pos_x+=this.speed;
gameManager.score++;
soundManager.playSound(5);
document.getElementById("score").innerHTML = "Счёт: " + gameManager.score;
}
if (obj.name.match(/finish/)) {
this.kill();
if(gameManager.curr_level < gameManager.max_level){
gameManager.levelUp();
}else if(gameManager.curr_level == gameManager.max_level){
gameManager.gameEnd(false);
}
}
if (obj.name.match(/lv/)) {
obj.kill();
this.pos_x+=this.speed;
if(element.type===1){
this.dirSprite="2",element.type=2, this.speed=5,this.speed_x=5, this.size_x= 96, this.size_y= 64;
soundManager.playSound(1);
}else{
this.dirSprite="3_3", element.type=1, this.speed=8,this.speed_x=8, this.size_x= 96, this.size_y= 32,element.type=1;
soundManager.playSound(2);
}
}
if (obj.name.match(/object1/)) {
this.kill();
this.speed=0;
gameManager.gameEnd(true);
}
if (obj.name.match(/object2/)) {
if(element.type===0 || element.type===1){
this.kill();
this.speed=0;
soundManager.stopAll();
gameManager.gameEnd(true);
}
if(element.type===2){
obj.kill();
this.pos_x+=this.speed;
}
}
if (obj.name.match(/border/)) {
this.kill();
this.speed=0;
soundManager.stopAll();
gameManager.gameEnd(true);
}
},
//Исправить на те firstgid, что будут в конечной мапе
onTouchMap: function (obj) {
},
kill: function () {
gameManager.kill(this);
}}
);
var gameManager = { // менеджер игры
factory: null, // фабрика объектов на карте
entities: null, // объекты на карте
player: null, // указатель на объект игрока
nickname: "",
score : 0,
curr_level: 1, max_level: 3,
laterKill: [],
initPlayer: function (obj) { // инициализация игрока
this.player = obj;
},
update: function () { // обновление информации
if (this.player === null)
return;
this.player.move_x = 1;
this.player.move_y = 0;
window_x += this.player.speed;
if (eventsManager.action["up"]) {
this.player.move_y = -1;
}
if (eventsManager.action["down"]) {
this.player.move_y = 1;
}
//обновление информации по всем объектам на карте
this.entities.forEach(function (e) {
try {
e.update();
} catch(ex) {}
});
for(var i = 0; i < this.laterKill.length; i++) {
var idx = this.entities.indexOf(this.laterKill[i]);
if(idx > -1)
this.entities.splice(idx, 1); // удаление из массива 1 объекта
}
if (this.laterKill.length > 0) // очистка массива laterKill
this.laterKill.length = 0;
mapManager.draw(ctx);
this.draw(ctx);
},
draw: function (ctx) {
for (var e = 0; e < this.entities.length; e++) {
this.entities[e].draw(ctx);
}
},
loadAll: function () {
soundManager.init();
spriteManager.loadAtlas("atlas.json", "spritesheet.png"); // загрузка атласа
gameManager.factory['Player'] = Player; // инициализация фабрики
gameManager.factory['finish'] = Finish;
gameManager.factory['object1'] = Object1;
gameManager.factory['object2'] = Object2;
gameManager.factory['lv'] = Lv;
gameManager.factory['fuel'] =Fuel;
gameManager.factory['border'] =Border;
mapManager.loadMap("maps/" + gameManager.curr_level + ".json"); // загрузка карты
mapManager.parseEntities(); // разбор сущностей карты
mapManager.draw(ctx); // отобразить карту
eventsManager.setup(); // настройка событий
},
play: function () {
docSetup();
player = null;
gameManager.entities = [];
gameManager.factory = {};
document.getElementById("lvl").innerHTML = "Уровень: " + gameManager.curr_level + "/" + gameManager.max_level;
if(this.nickname.length == 0)
this.nickname = document.getElementById("nick").value;
if(this.nickname.length > 0){
document.getElementById('myModal').style.display = 'none';
document.getElementById('nick').style.display = 'none';
document.getElementById('start').style.display = 'none';
gameManager.loadAll();
soundManager.playBG(true);
updateWorld();
}
},
kill: function (obj) {
this.laterKill.push(obj);
},
gameEnd: function(gameover){
document.getElementById('myModal').style.display = 'block';
document.getElementById('menu').style.display = 'block';
document.getElementById('winner').style.display = 'block';
document.getElementById('score').innerHTML = 'Счёт: 0';
if(gameover){
document.getElementById('winner').innerHTML = 'Вы проиграли';
soundManager.playBG(false);
soundManager.playSound(3);
}else{
scoreTable.add(gameManager.nickname, gameManager.score);
soundManager.playBG(false);
soundManager.playSound(4);
document.getElementById("records").innerHTML = scoreTable.get();
document.getElementById('winner').innerHTML = 'Вы выиграли! Собрано золота ' + gameManager.score;
window.cancelAnimationFrame(ANIM);
}
gameManager.curr_level = 1;
gameManager.score = 0;
},
levelUp: function(){
soundManager.playSound(6);
this.curr_level++;
this.play();
}
};
var step = 1/60, dt = 0, now, last = timestamp();
function updateWorld() {
now = timestamp();
dt = dt + Math.min(1, (now - last) / 1000);
while (dt > step) {
dt = dt - step;
ctx.clearRect(0, 0, 1195, 800);
gameManager.update();
}
last = now;
ANIM = requestAnimationFrame(updateWorld, canvas);
}