]> git.plutz.net Git - flarejs/blob - engine.js
movement functions
[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.frametime = performance.now();
82   this.info = gamedata.load(textdef);
83   this.tileset = gamedata.load(this.info.header.tileset);
84   gfx.load(this.tileset.img);
85
86   var  h = this.info.header.height,      w = this.info.header.width;
87   var 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   canvas.fillStyle = "rgba("+this.info.header.background_color+")";
91
92   this.tileAt = function(x, y) {
93     nx = (y + th / 2) / th + (x - w * tw / 2) / tw |0;
94     ny = (y + th / 2) / th - (x - w * tw / 2) / tw |0;
95     return ny * w + nx;
96   }
97
98   this.center = function(x, y) {
99     posx = canvas.canvas.width  / 2 - x;
100     posy = canvas.canvas.height / 2 - y;
101     return this;
102   }
103
104   this.draw = function(mobs) {
105     var x, y, dx, dy, i;
106     var bg = this.info.layer.find(l => l.type == "background").data;
107     var ob = this.info.layer.find(l => l.type == "object").data;
108     var mm = [];
109     mobs.forEach(m => {
110       i = this.tileAt(m.position[0], m.position[1]);
111       mm[i] = mobs.filter(m => i == this.tileAt(m.position[0], m.position[1]));
112     });
113     canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height);
114
115     for ( y = 0; y < h; y++ ) for ( x = 0; x < w; x++ ) {
116       i = y * h + x;
117       dx = posx + (w + x - y) * tw /2;
118       dy = posy + (x + y) * th / 2;
119       this.draw_tile(bg[i], dx, dy);
120     }
121     for ( y = 0; y < h; y++ ) for ( x = 0; x < w; x++ ) {
122       i = y * h + x;
123       dx = posx + (w + x - y) * tw /2;
124       dy = posy + (x + y) * th / 2;
125       this.draw_tile(ob[i], dx, dy);
126       if (mm[i]) mm[i].forEach(m => m.draw(m.position[0] + posx, m.position[1] + posy));
127     }
128   }
129
130   this.draw_tile = function(tile, x, y) {
131     x = x |0; y = y |0;
132     var t = this.tileset.tile[tile];
133     var f = this.tileset.animation[tile];
134
135     if (t && f) {
136       frame = ((performance.now() - this.frametime) / f[0][2] |0) % f.length;
137       canvas.drawImage(gfx[this.tileset.img], f[frame][0], f[frame][1], t[2], t[3],
138                                                     x - t[4], y - t[5], t[2], t[3]);
139     } else if (t) {
140       canvas.drawImage(gfx[this.tileset.img], t[0], t[1], t[2], t[3],
141                                       x - t[4], y - t[5], t[2], t[3]);
142     }
143   }
144 }
145
146 function Mob(textdef) {
147   this.position = [0, 0];
148   var info = gamedata.load(textdef);
149   var direction = 0;
150   var animation = "stance";
151   var previous_animation = "";
152   var frametime = performance.now();
153   gfx.load(info.image)
154
155   this.place = function(x, y) { this.position = [x, y]; return this; }
156   this.direct = function(d) { direction = d % 8; return this; }
157   this.animate = function(a) {
158     if ( a != animation ) {
159       previous_animation = animation;
160       animation = a;
161       frametime = performance.now();
162     }
163     return this;
164   }
165
166   this.draw = function(x, y){
167     var f, a = info[animation];
168     var frame = ( performance.now() - frametime ) * a.frames / a.duration | 0;
169
170     switch(a.type){
171       case "looped":
172         frame = frame % a.frames;
173         break;
174       case "play_once":
175         if ( frame >= a.frames ){
176           animation = previous_animation;
177           previous_animation = "";
178           frametime = performance.now();
179           a = info[animation];
180           frame = 0;
181         }
182         break;
183       case "back_forth":
184         frame = frame % (a.frames * 2 - 2);
185         if ( frame >= a.frames ){
186          frame = a.frames - frame % a.frames - 1;
187         }
188         break;
189       default: break;
190     }
191     f = a.frame[frame][direction];
192
193     canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3],
194                      x - f[4], y - f[5],
195                      f[2], f[3]);
196   }
197
198   this.block  = () => this.animate("block" );
199   this.cast   = () => this.animate("cast"  );
200   this.die    = () => this.animate("die"   );
201   this.hit    = () => this.animate("hit"   );
202   this.run    = () => this.animate("run"   );
203   this.shoot  = () => this.animate("shoot" );
204   this.stance = () => this.animate("stance");
205   this.swing  = () => this.animate("swing" );
206 }
207
208 function Hero(gender = "female", hair = "short"){
209   this.position = [0,0];
210   this.stats = gamedata.load("/engine/stats.txt");
211   var layers = gamedata.load("/engine/hero_layers.txt");
212   var hair = (gender == "female")?"long":hair;
213   var direction = 0, animation = "stance";
214
215   limbs = {
216     head : new Mob("/animations/avatar/"+gender+"/head_"+hair+".txt"),
217     chest: new Mob("/animations/avatar/"+gender+"/default_chest.txt"),
218     hands: new Mob("/animations/avatar/"+gender+"/default_hands.txt"),
219     legs : new Mob("/animations/avatar/"+gender+"/default_legs.txt"),
220     feet : new Mob("/animations/avatar/"+gender+"/default_feet.txt"),
221     main : new Mob("/animations/avatar/"+gender+"/dagger.txt"),
222     off  : new Mob("/animations/avatar/"+gender+"/shield.txt")
223   }
224
225   this.dress = function(limb, item) {
226     limbs[limb] = new Mob("/animations/avatar/"+gender+"/"+item+".txt")
227     limbs[limb].place(this.position[0], this.position[1]).direct(direction);
228     this.animate(animation);
229     return this;
230   }
231
232   this.place   = function(x,y) {
233     this.position = [x,y];
234     for (var limb in limbs) limbs[limb].place(x,y);
235     return this;
236   }
237   this.direct  = function(d)   {
238     direction = d;
239     for (var limb in limbs) limbs[limb].direct(d);
240     return this;
241   }
242   this.animate = function(anim){
243     animation = anim;
244     for (var limb in limbs) limbs[limb].animate(anim);
245     return this;
246   }
247   this.draw    = function(x, y){
248     layers.layer[direction].forEach(limb => limbs[limb].draw(x, y));
249     return this;
250   }
251
252   this.block  = () => this.animate("block" );
253   this.cast   = () => this.animate("cast"  );
254   this.die    = () => this.animate("die"   );
255   this.hit    = () => this.animate("hit"   );
256   this.run    = () => this.animate("run"   );
257   this.shoot  = () => this.animate("shoot" );
258   this.stance = () => this.animate("stance");
259   this.swing  = () => this.animate("swing" );
260 }
261
262 function Controls(hero, map){
263   var kbdmap = {
264        up: 87,    altup: 38,
265      down: 83,  altdown: 40,
266      left: 65,  altleft: 37,
267     right: 68, altright: 39,
268   }
269   var keys = [];
270   var col = map.info.layer.find(l => l.type == "collision").data;
271
272   window.addEventListener("keydown", e => keys[e.keyCode] = true );
273   window.addEventListener("keyup"  , e => keys[e.keyCode] = false);
274   setInterval(() => input(), 33.33)
275
276   function translate(x, y){
277     var sx = map.info.header.tilewidth  * hero.stats.speed / 33.33;
278     var sy = map.info.header.tileheight * hero.stats.speed / 33.33;
279     var dx = x * sx, hx = hero.position[0];
280     var dy = y * sy, hy = hero.position[1];
281     var f = 2.1;
282
283     if (col[map.tileAt(hx + dx, hy + dy)] == 0 )
284             hero.place(hx + dx, hy + dy);
285     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy + sy / 1.5)] == 0 )
286                              hero.place(hx + dx / f, hy + sy / 1.5);
287     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy - sy / 1.5)] == 0 )
288                              hero.place(hx + dx / f, hy - sy / 1.5);
289     else if ( dx == 0 && col[map.tileAt(hx + sx / 1.5, hy + dy / f)] == 0 )
290                              hero.place(hx + sx / 1.5, hy + dy / f);
291     else if ( dx == 0 && col[map.tileAt(hx - sx / 1.5, hy + dy / f)] == 0 )
292                              hero.place(hx - sx / 1.5, hy + dy / f);
293     else player.stance();
294
295     map.center(hero.position[0], hero.position[1]);
296   }
297
298   function input(){
299     const dir   = [ -1, 0, 4, -1, 2, 1, 3, 2, 6, 7, 5, 6, -1, 0, 4, -1 ];
300     const trans = [ [-1.4,0], [-1,-1], [0,-1.4], [1,-1], [1.4,0], [1,1], [0,1.4], [-1,1] ];
301     var k = 0;
302
303     k += (keys[kbdmap.left]  || keys[kbdmap.altleft])  ? 1 : 0;
304     k += (keys[kbdmap.right] || keys[kbdmap.altright]) ? 2 : 0;
305     k += (keys[kbdmap.up]    || keys[kbdmap.altup])    ? 4 : 0;
306     k += (keys[kbdmap.down]  || keys[kbdmap.altdown])  ? 8 : 0;
307
308     if (~dir[k]) {
309       hero.direct(dir[k]).run();
310       translate(trans[dir[k]][0], trans[dir[k]][1]);
311     } else hero.stance();
312   }
313 }
314
315 document.querySelector("body").setAttribute("style", "margin: 0; padding: 0;");
316 canvas = document.createElement("canvas").getContext("2d");
317 canvas.canvas.setAttribute("style", "display: block; border: 0; margin: 0; padding: 0;");
318 document.querySelector("body").appendChild(canvas.canvas);
319
320 canvas.canvas.width  = window.innerWidth;
321 canvas.canvas.height = window.innerHeight;
322 window.addEventListener("resize", function(){
323   canvas.canvas.width  = window.innerWidth;
324   canvas.canvas.height = window.innerHeight;
325 });
326
327 player = new Hero();
328 map = new Map("/maps/arrival.txt");
329 player.place(map.info.header.hero_pos.split(/,/)[0] * map.info.header.tilewidth,
330              map.info.header.hero_pos.split(/,/)[1] * map.info.header.tileheight);
331 player.direct(5).stance();
332
333 map.center(player.position[0], player.position[1]);
334 c = new Controls(player, map);
335
336 setInterval (() => map.draw([player]), 16.66 );