]> git.plutz.net Git - flarejs/blob - engine.js
npc loading
[flarejs] / engine.js
1 var gamedata = {
2   // associative array for gamedata files
3   load: function(def) { return this[def] ? this[def] : this[def] = new Textfile(def); }
4 }
5 var gfx = {
6   // associative array for game graphics
7   load: function(def) {
8     if (!this[def]) {
9       this[def] = document.createElement("img");
10       this[def].setAttribute("src", def);
11     }
12     return this[def];
13   }
14 };
15
16 function Textfile(txtfile) {
17   // fetch and parse gamedata file into structured object
18   var lines, fetch = new XMLHttpRequest();
19   fetch.open("GET", txtfile, false);
20   fetch.send();
21
22   var line, key, value, ref = this, section;
23   for (line of fetch.responseText.split('\n')) switch(true) {
24     // section headers that always become array elements
25     case /^\[(npc|event|layer|dialog)\]$/.test(line):
26       section = line.split(/[\]\[]/)[1]; ref = {};
27       if                     (!this[section]) this[section] = [ref];
28       else if ( Array.isArray(this[section])) this[section].push(ref);
29       break;
30     // general section headers (may or may not be unique)
31     case /^\[.*\]$/.test(line):
32       section = line.split(/[\]\[]/)[1]; ref = {};
33       if                     (!this[section]) this[section] = ref;
34       else if (!Array.isArray(this[section])) this[section] = [this[section],ref];
35       else if ( Array.isArray(this[section])) this[section].push(ref);
36       break;
37     // frame definition from animation files
38     // frame=#frame,direction,srcX,srcY,width,height,dstX,dstY
39     case /^frame=[0-9]+,[0-7](,[0-9-]+){6}$/.test(line):
40       key = line.split(/[=,]/).slice(1,3);  value = line.split(/,/).slice(-6);
41       if (!ref.frame) ref.frame = [];
42       if (!ref.frame[key[0]]) ref.frame[key[0]] = [];
43       ref.frame[key[0]][key[1]] = value.map(x => parseInt(x));
44       break;
45     // order of gfx draw from engine/hero_layers.txt
46     // layer=direction,list,of,limbs,...
47     case /^layer=[0-9]+,/.test(line):
48       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
49       if (!ref.layer) ref.layer = []; ref.layer[key] = value;
50       break;
51     // empty data= line starting map data in map files
52     case /^data=$/.test(line):
53       ref.data = [];
54       break;
55     // map data array
56     case /^[0-9,]+,$/.test(line):
57       value = line.split(/,/).slice(0,-1);
58       ref.data = ref.data.concat(value);
59       break;
60     // map data array (last line)
61     case /^[0-9,]+$/.test(line):
62       value = line.split(/,/);
63       ref.data = ref.data.concat(value);
64       ref.data = ref.data.map(x => parseInt(x));
65       break;
66     // tile description from tiledef file
67     // tile=#tile,srcX,srcY,width,height,dstX,dstY
68     case /^tile=[0-9]+,/.test(line):
69       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
70       if (!ref.tile) ref.tile = []; ref.tile[key] = value.map(x => parseInt(x));
71       break;
72     // animated tile from tiledef file
73     // animation=#tile;(srcX,srcY,duration;)...
74     case /^animation=[0-9]+;.*;$/.test(line):
75       key = line.split(/[=;]/)[1];  value = line.split(/;/).slice(1,-1);
76       value = value.map(x => x.split(/,/));
77       value.forEach(x => x[2] = parseInt(x[2]));
78       if (!ref.animation) ref.animation = []; ref.animation[key] = value;
79       break;
80     // frame duration from animation file (im millisec)
81     case /^duration=[0-9]+ms$/.test(line):
82       ref["duration"] = line.split(/=|ms$/)[1];
83       break;
84     // frame duration from animation file (in whole seconds)
85     case /^duration=[0-9]+s$/.test(line):
86       ref["duration"] = line.split(/=|s$/)[1] * 1000;
87       break;
88     // general numeric value (key=#)
89     case /^[^#].*=[0-9]+$/.test(line):
90       key = line.split(/[=]/)[0];  value = line.split(/=/).slice(1) * 1;
91       if                     (!ref[key]) ref[key] = value;
92       else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value];
93       else if ( Array.isArray(ref[key])) ref[key].push(value);
94       break;
95     // general key=value (non-numeric or non-scalar)
96     case /^[^#].*=.+$/.test(line):
97       key = line.split(/[=]/)[0];  value = line.split(/=/).slice(1).join("=");
98       if                     (!ref[key]) ref[key] = value;
99       else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value];
100       else if ( Array.isArray(ref[key])) ref[key].push(value);
101       break;
102   }
103 }
104
105 function Map(textdef) {
106   // object for map operations (drawing coorinate transformation, etc.)
107   this.info = gamedata.load(textdef);
108   const tileset = gamedata.load(this.info.header.tileset);
109   const frametime = performance.now();
110   gfx.load(tileset.img);
111
112   const  h = this.info.header.height,      w = this.info.header.width;
113   const th = this.info.header.tileheight, tw = this.info.header.tilewidth;
114   var posx = canvas.canvas.width / 2, posy = canvas.canvas.height / 2 - h * th/2;
115
116   canvas.fillStyle = "rgba("+this.info.header.background_color+")";
117
118   // precalculated tile positions
119   // assign x/y coordinates to each tile index
120   // looks dumb but is faster than on the fly isometric calculations
121   const dx = [], dy = [];
122   for ( let y = 0; y < h; y++ ) for ( let x = 0; x < w; x++ ) {
123     dx[y * w + x] = (w + x - y) * tw / 2;
124     dy[y * w + x] = (x + y) * th / 2;
125   }
126
127   const npcs = [];
128   for (let def of this.info.npc) {
129     let npc = new Npc(def.filename)
130     let loc = def.location.split(',')[1] * 1 * w + def.location.split(',')[0] * 1;
131     npc.place(dx[loc], dy[loc]);
132     npcs[loc] = npc;
133     this.info.layer.find(l => l.type == "collision").data[loc] = 1;
134   }
135
136   // tile index for pixel position on map
137   this.tileAt = function(x, y) {
138     var r = (y + th / 2) / th; var c = (x - w * tw /2) / tw;
139     var nx = r + c |0; var ny = r - c |0;
140     return ny * w + nx;
141   }
142
143   // vice versa the pixel coordinates of a given map tile
144   this.positionOf = tile => [dx[tile], dy[tile]];
145   this.xOf = tile => dx[tile];
146   this.yOf = tile => dy[tile];
147
148   // center map to pixel position (by setting drawing offsets)
149   this.center = function(x, y) {
150     posx = canvas.canvas.width  / 2 - x;
151     posy = canvas.canvas.height / 2 - y;
152     return this;
153   }
154
155   // draw the entire map, including all mobs
156   // mobs in an array of all heros, enemies, loot, npcs, etc.
157   this.draw = function(mobs) {
158     const bg = this.info.layer.find(l => l.type == "background").data;
159     const ob = this.info.layer.find(l => l.type == "object").data;
160     var i, mm = [];
161
162     // mobs only have x/y pixel positions,
163     // to draw them in order with map tiles we set up
164     // an array with current tile positions of mobs
165     mobs.forEach(m => {
166       let i = this.tileAt(m.position[0], m.position[1]);
167       mm[i] = mobs.filter(m => i == this.tileAt(m.position[0], m.position[1]));
168     });
169     canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height);
170
171     // draw background layer first
172     for ( i = 0; i < h * w; i++ ) draw_tile(bg[i], posx + dx[i], posy + dy[i]);
173
174     // draw object layer and mobs
175     for ( i = 0; i < h * w; i++ ) {
176       draw_tile(ob[i], posx + dx[i], posy + dy[i]);
177       if (mm[i]) mm[i].forEach(m => m.draw(posx + m.position[0], posy + m.position[1]));
178       if (npcs[i]) npcs[i].draw(posx + dx[i], posy + dy[i]);
179     }
180   }
181
182   // draw a single map tile at screen position x/y
183   // tile may be animated, if so defined in tiledef
184   function draw_tile(tile, x, y) {
185     const t = tileset.tile[tile];
186     const f = tileset.animation[tile];
187     x = x |0; y = y |0;
188
189     if (t && f) {
190       frame = ((performance.now() - frametime) / f[0][2] |0) % f.length;
191       canvas.drawImage(gfx[tileset.img], f[frame][0], f[frame][1], t[2], t[3],
192                                                x - t[4], y - t[5], t[2], t[3]);
193     } else if (t) {
194       canvas.drawImage(gfx[tileset.img], t[0], t[1], t[2], t[3],
195                                  x - t[4], y - t[5], t[2], t[3]);
196     }
197   }
198 }
199
200 function Mob(textdef) {
201   // any mobile object, mostly for gfx representation
202   // may be hero, enemy, loot, npc, etc.
203   this.position = [0, 0];
204   const info = gamedata.load(textdef);
205   var direction = 0;
206   var animation = "stance";
207   var previous_animation = "";
208   var frametime = performance.now();
209   gfx.load(info.image)
210
211   // some simplified npc files do not define animation frames
212   // render size and offset are given instead, and we
213   // assume, that we can just loop horizontally over the image
214   if (!info[animation].frame){
215     info[animation].frame = [];
216     let rs = info.render_size.split(/,/);   rs = [ rs[0] * 1, rs[1] * 1 ];
217     let ro = info.render_offset.split(/,/); ro = [ ro[0] * 1, ro[1] * 1 ];
218
219     for (let i = 0; i < info[animation].frames; i++ )
220       info[animation].frame[i] = [[ i * rs[0], 0, rs[0], rs[1], ro[0], ro[1]]];
221   }
222
223   // place mob on x/y pixel coordinates
224   // e.g. when spawning, walking, etc.
225   this.place = function(x, y) {
226     this.position[0] = x, this.position[1] = y;
227     return this;
228   }
229
230   // change facing direction of mob
231   this.direct = function(d) { direction = d % 8; return this; }
232
233   // set animation cycle for drawing
234   // play_once animations will automatically fall back
235   // to previous loop after completion
236   this.animate = function(a) {
237     if ( a != animation ) {
238       previous_animation = animation;
239       animation = a;
240       frametime = performance.now();
241     }
242     return this;
243   }
244
245   // draw this mob to screen position x/y
246   this.draw = function(x, y){
247     var f, a = info[animation];
248     var f, frame = ( performance.now() - frametime ) * a.frames / a.duration | 0;
249
250     // determine current animation frame
251     switch(a.type){
252       case "looped":
253         frame = frame % a.frames;
254         break;
255       case "play_once":
256         if ( frame >= a.frames ){
257           animation = previous_animation;
258           previous_animation = "";
259           frametime = performance.now();
260           a = info[animation];
261           frame = 0;
262         }
263         break;
264       case "back_forth":
265         frame = frame % (a.frames * 2 - 2);
266         if ( frame >= a.frames ){
267          frame = a.frames - frame % a.frames - 1;
268         }
269         break;
270       default: break;
271     }
272     f = a.frame[frame][direction];
273
274     canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3],
275                      x - f[4], y - f[5],
276                      f[2], f[3]);
277   }
278
279   // shortcut functions for specific animations
280   this.block  = () => this.animate("block" );
281   this.cast   = () => this.animate("cast"  );
282   this.die    = () => this.animate("die"   );
283   this.hit    = () => this.animate("hit"   );
284   this.run    = () => this.animate("run"   );
285   this.shoot  = () => this.animate("shoot" );
286   this.stance = () => this.animate("stance");
287   this.swing  = () => this.animate("swing" );
288 }
289
290 function Npc(textdef){
291   this.info = gamedata.load(textdef);
292   const avatar = new Mob(this.info.gfx);
293
294   this.place = function(x, y) {
295     avatar.place(x,y);
296     return this;
297   }
298
299   this.draw = function(x, y) {
300     avatar.draw(x, y);
301     return this;
302   }
303 }
304
305 function Hero(gender = "female", hair = "short"){
306   // Object for player character
307   // unique in single player
308   this.position = [0,0];
309   this.stats = gamedata.load("/engine/stats.txt");
310   const layers = gamedata.load("/engine/hero_layers.txt");
311   var direction = 0, animation = "stance";
312   hair = (gender == "female")?"long":hair;
313
314   // hero consists of multiple mobs, one for each clothing/item overlay
315   var limbs = {
316     head : new Mob("/animations/avatar/"+gender+"/head_"+hair+".txt"),
317     chest: new Mob("/animations/avatar/"+gender+"/cloth_shirt.txt"),
318     hands: new Mob("/animations/avatar/"+gender+"/default_hands.txt"),
319     legs : new Mob("/animations/avatar/"+gender+"/cloth_pants.txt"),
320     feet : new Mob("/animations/avatar/"+gender+"/default_feet.txt"),
321     main : null, // main hand, e.g. melee weapon, magic weapon
322     off  : null  // off hand, e.g. shield, ranged weapon
323   }
324
325   // "dress" the player, i.e. assign clothing/item to limb
326   this.dress = function(limb, item) {
327     limbs[limb] = new Mob("/animations/avatar/"+gender+"/"+item+".txt")
328     limbs[limb].place(this.position[0], this.position[1]).direct(direction);
329     this.animate(animation);
330     return this;
331   }
332
333   // // Wrapper functions for Mob class // //
334
335   // place all mobs beloning to hero (when spawning, walking, teleporting, etc.)
336   this.place   = function(x,y) {
337     this.position[0] = x, this.position[1] = y;
338     for (var limb in limbs) limbs[limb] && limbs[limb].place(x,y);
339     return this;
340   }
341   // change facing direction of hero (i.e. of all mobs)
342   this.direct  = function(d)   {
343     direction = d;
344     for (var limb in limbs) limbs[limb] && limbs[limb].direct(d);
345     return this;
346   }
347   // start animation cycle
348   this.animate = function(anim){
349     animation = anim;
350     for (var limb in limbs) limbs[limb] && limbs[limb].animate(anim);
351     return this;
352   }
353   this.draw    = function(x, y){
354     layers.layer[direction].forEach(limb => limbs[limb] && limbs[limb].draw(x, y));
355     return this;
356   }
357
358   // shortcuts for animation
359   this.block  = () => this.animate("block" );
360   this.cast   = () => this.animate("cast"  );
361   this.die    = () => this.animate("die"   );
362   this.hit    = () => this.animate("hit"   );
363   this.run    = () => this.animate("run"   );
364   this.shoot  = () => this.animate("shoot" );
365   this.stance = () => this.animate("stance");
366   this.swing  = () => this.animate("swing" );
367 }
368
369 function Controls(hero, map){
370   // processes keyboard / touch / mouse
371   // causes according player actions
372   // single player only, conrol will be assigned to server in multi player
373   var kbdmap = {
374        up: 87,    altup: 38,
375      down: 83,  altdown: 40,
376      left: 65,  altleft: 37,
377     right: 68, altright: 39,
378   }
379   var keys = [];
380   var col = map.info.layer.find(l => l.type == "collision").data;
381
382   window.addEventListener("keydown", e => keys[e.keyCode] = true );
383   window.addEventListener("keyup"  , e => keys[e.keyCode] = false);
384   setInterval(() => input(), 33.33)
385
386   // cause player to walk, processes blocked terrain and player speed
387   // x/y are factors of speed and direction
388   //     i.e. +/-1 for diagonal movement
389   //     and  +/-1.4 for horizontal/vertical movement
390   function translate(x, y){
391     var sx = map.info.header.tilewidth  * hero.stats.speed / 33.33;
392     var sy = map.info.header.tileheight * hero.stats.speed / 33.33;
393     var dx = x * sx, hx = hero.position[0];
394     var dy = y * sy, hy = hero.position[1];
395     var f = 2.1;
396
397     if (col[map.tileAt(hx + dx, hy + dy)] == 0 )
398             hero.place(hx + dx, hy + dy);
399     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy + sy / 1.5)] == 0 )
400                              hero.place(hx + dx / f, hy + sy / 1.5);
401     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy - sy / 1.5)] == 0 )
402                              hero.place(hx + dx / f, hy - sy / 1.5);
403     else if ( dx == 0 && col[map.tileAt(hx + sx / 1.5, hy + dy / f)] == 0 )
404                              hero.place(hx + sx / 1.5, hy + dy / f);
405     else if ( dx == 0 && col[map.tileAt(hx - sx / 1.5, hy + dy / f)] == 0 )
406                              hero.place(hx - sx / 1.5, hy + dy / f);
407     else player.stance();
408
409     map.center(hero.position[0], hero.position[1]);
410   }
411
412   // process input and decide on according action
413   function input(){
414     // facing directions, indexed by OR of key press combinations
415     const dir   = [ -1, 0, 4, -1, 2, 1, 3, 2, 6, 7, 5, 6, -1, 0, 4, -1 ];
416     // translation speed and direction, indexed by facing direction of movement
417     const trans = [ [-1.4,0], [-1,-1], [0,-1.4], [1,-1], [1.4,0], [1,1], [0,1.4], [-1,1] ];
418     var k = 0;
419
420     // OR of direction key presses
421     k += (keys[kbdmap.left]  || keys[kbdmap.altleft])  ? 1 : 0;
422     k += (keys[kbdmap.right] || keys[kbdmap.altright]) ? 2 : 0;
423     k += (keys[kbdmap.up]    || keys[kbdmap.altup])    ? 4 : 0;
424     k += (keys[kbdmap.down]  || keys[kbdmap.altdown])  ? 8 : 0;
425
426     if (~dir[k]) {
427       hero.direct(dir[k]).run();
428       translate(trans[dir[k]][0], trans[dir[k]][1]);
429     } else hero.stance();
430   }
431 }
432
433 document.querySelector("body").setAttribute("style", "margin: 0; padding: 0;");
434 canvas = document.createElement("canvas").getContext("2d");
435 canvas.canvas.setAttribute("style", "display: block; border: 0; margin: 0; padding: 0;");
436 document.querySelector("body").appendChild(canvas.canvas);
437
438 canvas.canvas.width  = window.innerWidth;
439 canvas.canvas.height = window.innerHeight;
440 window.addEventListener("resize", function(){
441   canvas.canvas.width  = window.innerWidth;
442   canvas.canvas.height = window.innerHeight;
443 });
444
445 // player = new Mob("animations/enemies/zombie.txt"); player.stats = { speed: 3 };
446 player = new Hero();
447 map = new Map("/maps/arrival.txt");
448 player.place(map.xOf(map.info.header.hero_pos.split(',')[1] * 1 * map.info.header.width + map.info.header.hero_pos.split(',')[0] * 1),
449              map.yOf(map.info.header.hero_pos.split(',')[1] * 1 * map.info.header.width + map.info.header.hero_pos.split(',')[0] * 1));
450 player.direct(6).stance();
451
452 map.center(player.position[0], player.position[1]);
453 c = new Controls(player, map);
454
455 setInterval (() => map.draw([player]), 33.33 );