2 // associative array for gamedata files
3 load: function(def) { return this[def] ? this[def] : this[def] = new Textfile(def); }
6 // associative array for game graphics
9 this[def] = document.createElement("img");
10 this[def].setAttribute("src", def);
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);
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);
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);
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));
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;
52 // empty data= line starting map data in map files
53 case /^data=$/.test(line):
57 case /^[0-9,]+,$/.test(line):
58 value = line.split(/,/).slice(0,-1);
59 ref.data = ref.data.concat(value);
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));
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));
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;
81 // frame duration from animation file (im millisec)
82 case /^duration=[0-9]+ms$/.test(line):
83 ref["duration"] = line.split(/=|ms$/)[1];
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;
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);
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);
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);
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);
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;
122 canvas.fillStyle = "rgba("+this.info.header.background_color+")";
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;
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;
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++) {
146 if (!this.events[loc]) this.events[loc] = [];
147 this.events[loc].push(ev);
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;
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];
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;
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;
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
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]));
184 canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height);
186 // draw background layer first
187 for ( i = 0; i < h * w; i++ ) draw_tile(bg[i], posx + dx[i], posy + dy[i]);
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]);
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];
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]);
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]);
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);
221 var animation = "stance";
222 var previous_animation = "";
223 var frametime = performance.now();
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;
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]]];
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;
244 // change facing direction of mob
245 this.direct = function(d) { direction = d % 8; return this; }
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;
254 frametime = performance.now();
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;
264 // determine current animation frame
267 frame = frame % a.frames;
270 if ( frame >= a.frames ){
271 animation = previous_animation;
272 previous_animation = "";
273 frametime = performance.now();
279 frame = frame % (a.frames * 2 - 2);
280 if ( frame >= a.frames ){
281 frame = a.frames - frame % a.frames - 1;
286 f = a.frame[frame][direction];
288 canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3],
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" );
304 function Npc(textdef){
305 this.info = gamedata.load(textdef);
306 const avatar = new Mob(this.info.gfx);
308 this.place = function(x, y) {
313 this.draw = function(x, y) {
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;
328 // hero consists of multiple mobs, one for each clothing/item overlay
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
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);
347 // // Wrapper functions for Mob class // //
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);
355 // change facing direction of hero (i.e. of all mobs)
356 this.direct = function(d) {
358 for (var limb in limbs) limbs[limb] && limbs[limb].direct(d);
361 // start animation cycle
362 this.animate = function(anim){
364 for (var limb in limbs) limbs[limb] && limbs[limb].animate(anim);
367 this.draw = function(x, y){
368 layers.layer[direction].forEach(limb => limbs[limb] && limbs[limb].draw(x, y));
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" );
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
389 down: 83, altdown: 40,
390 left: 65, altleft: 37,
391 right: 68, altright: 39,
395 window.addEventListener("keydown", e => keys[e.keyCode] = true );
396 window.addEventListener("keyup" , e => keys[e.keyCode] = false);
397 setInterval(() => input(), 33.33)
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];
409 const col = map.info.layer.find(l => l.type == "collision").data;
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();
423 map.center(hero.position[0], hero.position[1]);
424 events(hero.position[0], hero.position[1]);
427 function events(x, y) {
428 const i = map.tileAt(x,y); var ev;
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) );
440 // process input and decide on according action
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] ];
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;
455 hero.direct(dir[k]).run();
456 translate(trans[dir[k]][0], trans[dir[k]][1]);
457 } else hero.stance();
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);
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;
473 // player = new Mob("animations/enemies/zombie.txt"); player.stats = { speed: 3 };
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();
480 map.center(player.position[0], player.position[1]);
481 c = new Controls(player);
483 setInterval (() => map.draw([player]), 33.33 );