]> git.plutz.net Git - flarejs/blob - engine.js
proper code commenting ;-)
[flarejs] / engine.js
1 var gamedata = {
2   // associative array for gamedata files
3   load: def => 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   // tile index for pixel position on map
128   this.tileAt = function(x, y) {
129     var r = (y + th / 2) / th; var c = (x - w * tw /2) / tw;
130     var nx = r + c |0; var ny = r - c |0;
131     return ny * w + nx;
132   }
133
134   // center map to pixel position (by setting drawing offsets)
135   this.center = function(x, y) {
136     posx = canvas.canvas.width  / 2 - x;
137     posy = canvas.canvas.height / 2 - y;
138     return this;
139   }
140
141   // draw the entire map, including all mobs
142   // mobs in an array of all heros, enemies, loot, npcs, etc.
143   this.draw = function(mobs) {
144     const bg = this.info.layer.find(l => l.type == "background").data;
145     const ob = this.info.layer.find(l => l.type == "object").data;
146     var x, y, i, mm = [];
147
148     // mobs only have x/y pixel positions, to draw them in order with map tiles
149     // we set up an array with current tile positions of mobs
150     mobs.forEach(m => {
151       let i = this.tileAt(m.position[0], m.position[1]);
152       mm[i] = mobs.filter(m => i == this.tileAt(m.position[0], m.position[1]));
153     });
154     canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height);
155
156     for ( y = 0; y < h; y++ ) for ( x = 0; x < w; x++ ) {
157       i = y * h + x;
158       draw_tile(bg[i], posx + dx[i], posy + dy[i]);
159     }
160     for ( y = 0; y < h; y++ ) for ( x = 0; x < w; x++ ) {
161       i = y * h + x;
162       draw_tile(ob[i], posx + dx[i], posy + dy[i]);
163       if (mm[i]) mm[i].forEach(m => m.draw(posx + m.position[0], posy + m.position[1]));
164     }
165   }
166
167   // draw a single map tile at screen position x/y
168   // tile may be animated, if so defined in tiledef
169   function draw_tile(tile, x, y) {
170     const t = tileset.tile[tile];
171     const f = tileset.animation[tile];
172     x = x |0; y = y |0;
173
174     if (t && f) {
175       frame = ((performance.now() - frametime) / f[0][2] |0) % f.length;
176       canvas.drawImage(gfx[tileset.img], f[frame][0], f[frame][1], t[2], t[3],
177                                                x - t[4], y - t[5], t[2], t[3]);
178     } else if (t) {
179       canvas.drawImage(gfx[tileset.img], t[0], t[1], t[2], t[3],
180                                  x - t[4], y - t[5], t[2], t[3]);
181     }
182   }
183 }
184
185 function Mob(textdef) {
186   // any mobile object, mostly for gfx representation
187   // may be hero, enemy, loot, npc, etc.
188   this.position = [0, 0];
189   const info = gamedata.load(textdef);
190   var direction = 0;
191   var animation = "stance";
192   var previous_animation = "";
193   var frametime = performance.now();
194   gfx.load(info.image)
195
196   // place mob on x/y pixel coordinates
197   // e.g. when spawning, walking, etc.
198   this.place = function(x, y) {
199     this.position[0] = x, this.position[1] = y;
200     return this;
201   }
202
203   // change facing direction of mob
204   this.direct = function(d) { direction = d % 8; return this; }
205
206   // set animation cycle for drawing
207   // play_once animations will automatically fall back
208   // to previous loop after completion
209   this.animate = function(a) {
210     if ( a != animation ) {
211       previous_animation = animation;
212       animation = a;
213       frametime = performance.now();
214     }
215     return this;
216   }
217
218   // draw this mob to screen position x/y
219   this.draw = function(x, y){
220     var f, a = info[animation];
221     var f, frame = ( performance.now() - frametime ) * a.frames / a.duration | 0;
222
223     // determine current animation frame
224     switch(a.type){
225       case "looped":
226         frame = frame % a.frames;
227         break;
228       case "play_once":
229         if ( frame >= a.frames ){
230           animation = previous_animation;
231           previous_animation = "";
232           frametime = performance.now();
233           a = info[animation];
234           frame = 0;
235         }
236         break;
237       case "back_forth":
238         frame = frame % (a.frames * 2 - 2);
239         if ( frame >= a.frames ){
240          frame = a.frames - frame % a.frames - 1;
241         }
242         break;
243       default: break;
244     }
245     f = a.frame[frame][direction];
246
247     canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3],
248                      x - f[4], y - f[5],
249                      f[2], f[3]);
250   }
251
252   // shortcut functions for specific animations
253   this.block  = () => this.animate("block" );
254   this.cast   = () => this.animate("cast"  );
255   this.die    = () => this.animate("die"   );
256   this.hit    = () => this.animate("hit"   );
257   this.run    = () => this.animate("run"   );
258   this.shoot  = () => this.animate("shoot" );
259   this.stance = () => this.animate("stance");
260   this.swing  = () => this.animate("swing" );
261 }
262
263 function Hero(gender = "female", hair = "short"){
264   // Object for player character
265   // unique in single player
266   this.position = [0,0];
267   this.stats = gamedata.load("/engine/stats.txt");
268   const layers = gamedata.load("/engine/hero_layers.txt");
269   var direction = 0, animation = "stance";
270   hair = (gender == "female")?"long":hair;
271
272   // hero consists of multiple mobs, one for each clothing/item overlay
273   var limbs = {
274     head : new Mob("/animations/avatar/"+gender+"/head_"+hair+".txt"),
275     chest: new Mob("/animations/avatar/"+gender+"/cloth_shirt.txt"),
276     hands: new Mob("/animations/avatar/"+gender+"/default_hands.txt"),
277     legs : new Mob("/animations/avatar/"+gender+"/cloth_pants.txt"),
278     feet : new Mob("/animations/avatar/"+gender+"/default_feet.txt"),
279     main : null, // main hand, e.g. melee weapon, magic weapon
280     off  : null  // off hand, e.g. shield, ranged weapon
281   }
282
283   // "dress" the player, i.e. assign clothing/item to limb
284   this.dress = function(limb, item) {
285     limbs[limb] = new Mob("/animations/avatar/"+gender+"/"+item+".txt")
286     limbs[limb].place(this.position[0], this.position[1]).direct(direction);
287     this.animate(animation);
288     return this;
289   }
290
291   // // Wrapper functions for Mob class // //
292
293   // place all mobs beloning to hero (when spawning, walking, teleporting, etc.)
294   this.place   = function(x,y) {
295     this.position[0] = x, this.position[1] = y;
296     for (var limb in limbs) limbs[limb] && limbs[limb].place(x,y);
297     return this;
298   }
299   // change facing direction of hero (i.e. of all mobs)
300   this.direct  = function(d)   {
301     direction = d;
302     for (var limb in limbs) limbs[limb] && limbs[limb].direct(d);
303     return this;
304   }
305   // start animation cycle
306   this.animate = function(anim){
307     animation = anim;
308     for (var limb in limbs) limbs[limb] && limbs[limb].animate(anim);
309     return this;
310   }
311   this.draw    = function(x, y){
312     layers.layer[direction].forEach(limb => limbs[limb] && limbs[limb].draw(x, y));
313     return this;
314   }
315
316   // shortcuts for animation
317   this.block  = () => this.animate("block" );
318   this.cast   = () => this.animate("cast"  );
319   this.die    = () => this.animate("die"   );
320   this.hit    = () => this.animate("hit"   );
321   this.run    = () => this.animate("run"   );
322   this.shoot  = () => this.animate("shoot" );
323   this.stance = () => this.animate("stance");
324   this.swing  = () => this.animate("swing" );
325 }
326
327 function Controls(hero, map){
328   // processes keyboard / touch / mouse
329   // causes according player actions
330   // single player only, conrol will be assigned to server in multi player
331   var kbdmap = {
332        up: 87,    altup: 38,
333      down: 83,  altdown: 40,
334      left: 65,  altleft: 37,
335     right: 68, altright: 39,
336   }
337   var keys = [];
338   var col = map.info.layer.find(l => l.type == "collision").data;
339
340   window.addEventListener("keydown", e => keys[e.keyCode] = true );
341   window.addEventListener("keyup"  , e => keys[e.keyCode] = false);
342   setInterval(() => input(), 33.33)
343
344   // cause player to walk, processes blocked terrain and player speed
345   // x/y are factors of speed and direction
346   //     i.e. +/-1 for diagonal movement
347   //     and  +/-1.4 for horizontal/vertical movement
348   function translate(x, y){
349     var sx = map.info.header.tilewidth  * hero.stats.speed / 33.33;
350     var sy = map.info.header.tileheight * hero.stats.speed / 33.33;
351     var dx = x * sx, hx = hero.position[0];
352     var dy = y * sy, hy = hero.position[1];
353     var f = 2.1;
354
355     if (col[map.tileAt(hx + dx, hy + dy)] == 0 )
356             hero.place(hx + dx, hy + dy);
357     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy + sy / 1.5)] == 0 )
358                              hero.place(hx + dx / f, hy + sy / 1.5);
359     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy - sy / 1.5)] == 0 )
360                              hero.place(hx + dx / f, hy - sy / 1.5);
361     else if ( dx == 0 && col[map.tileAt(hx + sx / 1.5, hy + dy / f)] == 0 )
362                              hero.place(hx + sx / 1.5, hy + dy / f);
363     else if ( dx == 0 && col[map.tileAt(hx - sx / 1.5, hy + dy / f)] == 0 )
364                              hero.place(hx - sx / 1.5, hy + dy / f);
365     else player.stance();
366
367     map.center(hero.position[0], hero.position[1]);
368   }
369
370   // process input and decide on according action
371   function input(){
372     // facing directions, indexed by OR of key press combinations
373     const dir   = [ -1, 0, 4, -1, 2, 1, 3, 2, 6, 7, 5, 6, -1, 0, 4, -1 ];
374     // translation speed and direction, indexed by facing direction of movement
375     const trans = [ [-1.4,0], [-1,-1], [0,-1.4], [1,-1], [1.4,0], [1,1], [0,1.4], [-1,1] ];
376     var k = 0;
377
378     // OR of direction key presses
379     k += (keys[kbdmap.left]  || keys[kbdmap.altleft])  ? 1 : 0;
380     k += (keys[kbdmap.right] || keys[kbdmap.altright]) ? 2 : 0;
381     k += (keys[kbdmap.up]    || keys[kbdmap.altup])    ? 4 : 0;
382     k += (keys[kbdmap.down]  || keys[kbdmap.altdown])  ? 8 : 0;
383
384     if (~dir[k]) {
385       hero.direct(dir[k]).run();
386       translate(trans[dir[k]][0], trans[dir[k]][1]);
387     } else hero.stance();
388   }
389 }
390
391 document.querySelector("body").setAttribute("style", "margin: 0; padding: 0;");
392 canvas = document.createElement("canvas").getContext("2d");
393 canvas.canvas.setAttribute("style", "display: block; border: 0; margin: 0; padding: 0;");
394 document.querySelector("body").appendChild(canvas.canvas);
395
396 canvas.canvas.width  = window.innerWidth;
397 canvas.canvas.height = window.innerHeight;
398 window.addEventListener("resize", function(){
399   canvas.canvas.width  = window.innerWidth;
400   canvas.canvas.height = window.innerHeight;
401 });
402
403 // player = new Mob("animations/enemies/zombie.txt"); player.stats = { speed: 3 };
404 player = new Hero();
405 map = new Map("/maps/arrival.txt");
406 player.place(map.info.header.hero_pos.split(/,/)[0] * map.info.header.tilewidth,
407              map.info.header.hero_pos.split(/,/)[1] * map.info.header.tileheight);
408 player.direct(5).stance();
409
410 map.center(player.position[0], player.position[1]);
411 c = new Controls(player, map);
412
413 setInterval (() => map.draw([player]), 33.33 );