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