]> git.plutz.net Git - flarejs/blob - engine.js
allow player graphics to be null
[flarejs] / engine.js
1 var gamedata = {
2   load: def => this[def] ? this[def] : this[def] = new Textfile(def)
3 }
4 var gfx = {
5   load: function(def) {
6     if (!this[def]) {
7       this[def] = document.createElement("img");
8       this[def].setAttribute("src", def);
9     }
10     return this[def];
11   }
12 };
13
14 function Textfile(txtfile) {
15   var lines, fetch = new XMLHttpRequest();
16   fetch.open("GET", txtfile, false);
17   fetch.send();
18
19   var line, key, value, ref = this, section;
20   for (line of fetch.responseText.split('\n')) switch(true) {
21     case /^\[.*\]$/.test(line):
22       section = line.split(/[\]\[]/)[1]; ref = {};
23       if                     (!this[section]) this[section] = ref;
24       else if (!Array.isArray(this[section])) this[section] = [this[section],ref];
25       else if ( Array.isArray(this[section])) this[section].push(ref);
26       break;
27     case /^frame=[0-9]+,[0-7](,[0-9-]+){6}$/.test(line):
28       key = line.split(/[=,]/).slice(1,3);  value = line.split(/,/).slice(-6);
29       if (!ref.frame) ref.frame = [];
30       if (!ref.frame[key[0]]) ref.frame[key[0]] = [];
31       ref.frame[key[0]][key[1]] = value.map(x => parseInt(x));
32       break;
33     case /^layer=[0-9]+,/.test(line):
34       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
35       if (!ref.layer) ref.layer = []; ref.layer[key] = value;
36       break;
37     case /^data=$/.test(line):
38       ref.data = [];
39       break;
40     case /^[0-9,]+,$/.test(line):
41       value = line.split(/,/).slice(0,-1);
42       ref.data = ref.data.concat(value);
43       break;
44     case /^[0-9,]+$/.test(line):
45       value = line.split(/,/);
46       ref.data = ref.data.concat(value);
47       ref.data = ref.data.map(x => parseInt(x));
48       break;
49     case /^tile=[0-9]+,/.test(line):
50       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
51       if (!ref.tile) ref.tile = []; ref.tile[key] = value.map(x => parseInt(x));
52       break;
53     case /^animation=[0-9]+;.*;$/.test(line):
54       key = line.split(/[=;]/)[1];  value = line.split(/;/).slice(1,-1);
55       value = value.map(x => x.split(/,/));
56       value.forEach(x => x[2] = parseInt(x[2]));
57       if (!ref.animation) ref.animation = []; ref.animation[key] = value;
58       break;
59     case /^duration=[0-9]+ms$/.test(line):
60       ref["duration"] = line.split(/=|ms$/)[1];
61       break;
62     case /^duration=[0-9]+s$/.test(line):
63       ref["duration"] = line.split(/=|s$/)[1] * 1000;
64       break;
65     case /^[^#].*=[0-9]+$/.test(line):
66       key = line.split(/[=]/)[0];  value = line.split(/=/).slice(1) * 1;
67       if                     (!ref[key]) ref[key] = value;
68       else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value];
69       else if ( Array.isArray(ref[key])) ref[key].push(value);
70       break;
71     case /^[^#].*=.+$/.test(line):
72       key = line.split(/[=]/)[0];  value = line.split(/=/).slice(1).join("=");
73       if                     (!ref[key]) ref[key] = value;
74       else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value];
75       else if ( Array.isArray(ref[key])) ref[key].push(value);
76       break;
77   }
78 }
79
80 function Map(textdef) {
81   this.info = gamedata.load(textdef);
82   const tileset = gamedata.load(this.info.header.tileset);
83   const frametime = performance.now();
84   gfx.load(tileset.img);
85
86   const  h = this.info.header.height,      w = this.info.header.width;
87   const th = this.info.header.tileheight, tw = this.info.header.tilewidth;
88   var posx = canvas.canvas.width / 2, posy = canvas.canvas.height / 2 - h * th/2;
89
90   const dx = [], dy = [];  // precalculated tile positions
91   for ( let y = 0; y < h; y++ ) for ( let x = 0; x < w; x++ ) {
92     dx[y * w + x] = (w + x - y) * tw / 2;
93     dy[y * w + x] = (x + y) * th / 2;
94   }
95
96   canvas.fillStyle = "rgba("+this.info.header.background_color+")";
97
98   this.tileAt = function(x, y) {
99     var r = (y + th / 2) / th; var c = (x - w * tw /2) / tw;
100     var nx = r + c |0; var ny = r - c |0;
101     return ny * w + nx;
102   }
103
104   this.center = function(x, y) {
105     posx = canvas.canvas.width  / 2 - x;
106     posy = canvas.canvas.height / 2 - y;
107     return this;
108   }
109
110   this.draw = function(mobs) {
111     const bg = this.info.layer.find(l => l.type == "background").data;
112     const ob = this.info.layer.find(l => l.type == "object").data;
113     var x, y, i, mm = [];
114
115     mobs.forEach(m => {
116       let i = this.tileAt(m.position[0], m.position[1]);
117       mm[i] = mobs.filter(m => i == this.tileAt(m.position[0], m.position[1]));
118     });
119     canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height);
120
121     for ( y = 0; y < h; y++ ) for ( x = 0; x < w; x++ ) {
122       i = y * h + x;
123       draw_tile(bg[i], posx + dx[i], posy + dy[i]);
124     }
125     for ( y = 0; y < h; y++ ) for ( x = 0; x < w; x++ ) {
126       i = y * h + x;
127       draw_tile(ob[i], posx + dx[i], posy + dy[i]);
128       if (mm[i]) mm[i].forEach(m => m.draw(posx + m.position[0], posy + m.position[1]));
129     }
130   }
131
132   function draw_tile(tile, x, y) {
133     const t = tileset.tile[tile];
134     const f = tileset.animation[tile];
135     x = x |0; y = y |0;
136
137     if (t && f) {
138       frame = ((performance.now() - frametime) / f[0][2] |0) % f.length;
139       canvas.drawImage(gfx[tileset.img], f[frame][0], f[frame][1], t[2], t[3],
140                                                x - t[4], y - t[5], t[2], t[3]);
141     } else if (t) {
142       canvas.drawImage(gfx[tileset.img], t[0], t[1], t[2], t[3],
143                                  x - t[4], y - t[5], t[2], t[3]);
144     }
145   }
146 }
147
148 function Mob(textdef) {
149   this.position = [0, 0];
150   const info = gamedata.load(textdef);
151   var direction = 0;
152   var animation = "stance";
153   var previous_animation = "";
154   var frametime = performance.now();
155   gfx.load(info.image)
156
157   this.place = function(x, y) {
158     this.position[0] = x, this.position[1] = y;
159     return this;
160   }
161   this.direct = function(d) { direction = d % 8; return this; }
162   this.animate = function(a) {
163     if ( a != animation ) {
164       previous_animation = animation;
165       animation = a;
166       frametime = performance.now();
167     }
168     return this;
169   }
170
171   this.draw = function(x, y){
172     var f, a = info[animation];
173     var f, frame = ( performance.now() - frametime ) * a.frames / a.duration | 0;
174
175     switch(a.type){
176       case "looped":
177         frame = frame % a.frames;
178         break;
179       case "play_once":
180         if ( frame >= a.frames ){
181           animation = previous_animation;
182           previous_animation = "";
183           frametime = performance.now();
184           a = info[animation];
185           frame = 0;
186         }
187         break;
188       case "back_forth":
189         frame = frame % (a.frames * 2 - 2);
190         if ( frame >= a.frames ){
191          frame = a.frames - frame % a.frames - 1;
192         }
193         break;
194       default: break;
195     }
196     f = a.frame[frame][direction];
197
198     canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3],
199                      x - f[4], y - f[5],
200                      f[2], f[3]);
201   }
202
203   this.block  = () => this.animate("block" );
204   this.cast   = () => this.animate("cast"  );
205   this.die    = () => this.animate("die"   );
206   this.hit    = () => this.animate("hit"   );
207   this.run    = () => this.animate("run"   );
208   this.shoot  = () => this.animate("shoot" );
209   this.stance = () => this.animate("stance");
210   this.swing  = () => this.animate("swing" );
211 }
212
213 function Hero(gender = "female", hair = "short"){
214   this.position = [0,0];
215   this.stats = gamedata.load("/engine/stats.txt");
216   const layers = gamedata.load("/engine/hero_layers.txt");
217   var direction = 0, animation = "stance";
218   hair = (gender == "female")?"long":hair;
219
220   var limbs = {
221     head : new Mob("/animations/avatar/"+gender+"/head_"+hair+".txt"),
222     chest: new Mob("/animations/avatar/"+gender+"/cloth_shirt.txt"),
223     hands: new Mob("/animations/avatar/"+gender+"/default_hands.txt"),
224     legs : new Mob("/animations/avatar/"+gender+"/cloth_pants.txt"),
225     feet : new Mob("/animations/avatar/"+gender+"/default_feet.txt"),
226     main : null,// new Mob("/animations/avatar/"+gender+"/default_hands.txt"),
227     off  : null // new Mob("/animations/avatar/"+gender+"/default_hands.txt")
228   }
229
230   this.dress = function(limb, item) {
231     limbs[limb] = new Mob("/animations/avatar/"+gender+"/"+item+".txt")
232     limbs[limb].place(this.position[0], this.position[1]).direct(direction);
233     this.animate(animation);
234     return this;
235   }
236
237   this.place   = function(x,y) {
238     this.position[0] = x, this.position[1] = y;
239     for (var limb in limbs) limbs[limb] && limbs[limb].place(x,y);
240     return this;
241   }
242   this.direct  = function(d)   {
243     direction = d;
244     for (var limb in limbs) limbs[limb] && limbs[limb].direct(d);
245     return this;
246   }
247   this.animate = function(anim){
248     animation = anim;
249     for (var limb in limbs) limbs[limb] && limbs[limb].animate(anim);
250     return this;
251   }
252   this.draw    = function(x, y){
253     layers.layer[direction].forEach(limb => limbs[limb] && limbs[limb].draw(x, y));
254     return this;
255   }
256
257   this.block  = () => this.animate("block" );
258   this.cast   = () => this.animate("cast"  );
259   this.die    = () => this.animate("die"   );
260   this.hit    = () => this.animate("hit"   );
261   this.run    = () => this.animate("run"   );
262   this.shoot  = () => this.animate("shoot" );
263   this.stance = () => this.animate("stance");
264   this.swing  = () => this.animate("swing" );
265 }
266
267 function Controls(hero, map){
268   var kbdmap = {
269        up: 87,    altup: 38,
270      down: 83,  altdown: 40,
271      left: 65,  altleft: 37,
272     right: 68, altright: 39,
273   }
274   var keys = [];
275   var col = map.info.layer.find(l => l.type == "collision").data;
276
277   window.addEventListener("keydown", e => keys[e.keyCode] = true );
278   window.addEventListener("keyup"  , e => keys[e.keyCode] = false);
279   setInterval(() => input(), 33.33)
280
281   function translate(x, y){
282     var sx = map.info.header.tilewidth  * hero.stats.speed / 33.33;
283     var sy = map.info.header.tileheight * hero.stats.speed / 33.33;
284     var dx = x * sx, hx = hero.position[0];
285     var dy = y * sy, hy = hero.position[1];
286     var f = 2.1;
287
288     if (col[map.tileAt(hx + dx, hy + dy)] == 0 )
289             hero.place(hx + dx, hy + dy);
290     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy + sy / 1.5)] == 0 )
291                              hero.place(hx + dx / f, hy + sy / 1.5);
292     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy - sy / 1.5)] == 0 )
293                              hero.place(hx + dx / f, hy - sy / 1.5);
294     else if ( dx == 0 && col[map.tileAt(hx + sx / 1.5, hy + dy / f)] == 0 )
295                              hero.place(hx + sx / 1.5, hy + dy / f);
296     else if ( dx == 0 && col[map.tileAt(hx - sx / 1.5, hy + dy / f)] == 0 )
297                              hero.place(hx - sx / 1.5, hy + dy / f);
298     else player.stance();
299
300     map.center(hero.position[0], hero.position[1]);
301   }
302
303   function input(){
304     const dir   = [ -1, 0, 4, -1, 2, 1, 3, 2, 6, 7, 5, 6, -1, 0, 4, -1 ];
305     const trans = [ [-1.4,0], [-1,-1], [0,-1.4], [1,-1], [1.4,0], [1,1], [0,1.4], [-1,1] ];
306     var k = 0;
307
308     k += (keys[kbdmap.left]  || keys[kbdmap.altleft])  ? 1 : 0;
309     k += (keys[kbdmap.right] || keys[kbdmap.altright]) ? 2 : 0;
310     k += (keys[kbdmap.up]    || keys[kbdmap.altup])    ? 4 : 0;
311     k += (keys[kbdmap.down]  || keys[kbdmap.altdown])  ? 8 : 0;
312
313     if (~dir[k]) {
314       hero.direct(dir[k]).run();
315       translate(trans[dir[k]][0], trans[dir[k]][1]);
316     } else hero.stance();
317   }
318 }
319
320 document.querySelector("body").setAttribute("style", "margin: 0; padding: 0;");
321 canvas = document.createElement("canvas").getContext("2d");
322 canvas.canvas.setAttribute("style", "display: block; border: 0; margin: 0; padding: 0;");
323 document.querySelector("body").appendChild(canvas.canvas);
324
325 canvas.canvas.width  = window.innerWidth;
326 canvas.canvas.height = window.innerHeight;
327 window.addEventListener("resize", function(){
328   canvas.canvas.width  = window.innerWidth;
329   canvas.canvas.height = window.innerHeight;
330 });
331
332 // player = new Mob("animations/enemies/zombie.txt"); player.stats = { speed: 3 };
333 player = new Hero();
334 map = new Map("/maps/arrival.txt");
335 player.place(map.info.header.hero_pos.split(/,/)[0] * map.info.header.tilewidth,
336              map.info.header.hero_pos.split(/,/)[1] * map.info.header.tileheight);
337 player.direct(5).stance();
338
339 map.center(player.position[0], player.position[1]);
340 c = new Controls(player, map);
341
342 setInterval (() => map.draw([player]), 33.33 );