X-Git-Url: http://git.plutz.net/?a=blobdiff_plain;f=engine.js;h=cca0717553e14c084fd11dffa96a8b2d8aa7fb3b;hb=f01d5a0d558f4d6037f5a6d3770d12571cc60fa9;hp=c70679c9c0b842d7c2ba3753ed632827b70b3c2a;hpb=bd3599378029b37a5d613407f640a2bc89f7f060;p=flarejs diff --git a/engine.js b/engine.js index c70679c..cca0717 100644 --- a/engine.js +++ b/engine.js @@ -1,99 +1,483 @@ +var gamedata = { + // associative array for gamedata files + load: function(def) { return this[def] ? this[def] : this[def] = new Textfile(def); } +} +var gfx = { + // associative array for game graphics + load: function(def) { + if (!this[def]) { + this[def] = document.createElement("img"); + this[def].setAttribute("src", def); + } + return this[def]; + } +}; +var map; + +function Textfile(txtfile) { + // fetch and parse gamedata file into structured object + var lines, fetch = new XMLHttpRequest(); + fetch.open("GET", txtfile, false); + fetch.send(); + + var line, key, value, ref = this, section; + for (line of fetch.responseText.split('\n')) switch(true) { + // section headers that always become array elements + case /^\[(npc|event|layer|dialog)\]$/.test(line): + section = line.split(/[\]\[]/)[1]; ref = {}; + if (!this[section]) this[section] = [ref]; + else if ( Array.isArray(this[section])) this[section].push(ref); + break; + // general section headers (may or may not be unique) + case /^\[.*\]$/.test(line): + section = line.split(/[\]\[]/)[1]; ref = {}; + if (!this[section]) this[section] = ref; + else if (!Array.isArray(this[section])) this[section] = [this[section],ref]; + else if ( Array.isArray(this[section])) this[section].push(ref); + break; + // frame definition from animation files + // frame=#frame,direction,srcX,srcY,width,height,dstX,dstY + case /^frame=[0-9]+,[0-7](,[0-9-]+){6}$/.test(line): + key = line.split(/[=,]/).slice(1,3); value = line.split(/,/).slice(-6); + if (!ref.frame) ref.frame = []; + if (!ref.frame[key[0]]) ref.frame[key[0]] = []; + ref.frame[key[0]][key[1]] = value.map(x => parseInt(x)); + break; + // order of gfx draw from engine/hero_layers.txt + // layer=direction,list,of,limbs,... + case /^layer=[0-9]+,/.test(line): + key = line.split(/[=,]/)[1]; value = line.split(/,/).slice(1); + if (!ref.layer) ref.layer = []; ref.layer[key] = value; + break; + // empty data= line starting map data in map files + case /^data=$/.test(line): + ref.data = []; + break; + // map data array + case /^[0-9,]+,$/.test(line): + value = line.split(/,/).slice(0,-1); + ref.data = ref.data.concat(value); + break; + // map data array (last line) + case /^[0-9,]+$/.test(line): + value = line.split(/,/); + ref.data = ref.data.concat(value); + ref.data = ref.data.map(x => parseInt(x)); + break; + // tile description from tiledef file + // tile=#tile,srcX,srcY,width,height,dstX,dstY + case /^tile=[0-9]+,/.test(line): + key = line.split(/[=,]/)[1]; value = line.split(/,/).slice(1); + if (!ref.tile) ref.tile = []; ref.tile[key] = value.map(x => parseInt(x)); + break; + // animated tile from tiledef file + // animation=#tile;(srcX,srcY,duration;)... + case /^animation=[0-9]+;.*;$/.test(line): + key = line.split(/[=;]/)[1]; value = line.split(/;/).slice(1,-1); + value = value.map(x => x.split(/,/)); + value.forEach(x => x[2] = parseInt(x[2])); + if (!ref.animation) ref.animation = []; ref.animation[key] = value; + break; + // frame duration from animation file (im millisec) + case /^duration=[0-9]+ms$/.test(line): + ref["duration"] = line.split(/=|ms$/)[1]; + break; + // frame duration from animation file (in whole seconds) + case /^duration=[0-9]+s$/.test(line): + ref["duration"] = line.split(/=|s$/)[1] * 1000; + break; + // numeric array types + case /^(location|hero_pos|render_size|render_offset)=[0-9,-]+$/.test(line): + key = line.split(/[=]/)[0]; value = line.split(/[=]/)[1].split(/,/); + ref[key] = value.map(m => m * 1); + break; + // general numeric value (key=#) + case /^[^#].*=[0-9]+$/.test(line): + key = line.split(/[=]/)[0]; value = line.split(/=/).slice(1) * 1; + if (!ref[key]) ref[key] = value; + else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value]; + else if ( Array.isArray(ref[key])) ref[key].push(value); + break; + // general key=value (non-numeric or non-scalar) + case /^[^#].*=.+$/.test(line): + key = line.split(/[=]/)[0]; value = line.split(/=/).slice(1).join("="); + if (!ref[key]) ref[key] = value; + else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value]; + else if ( Array.isArray(ref[key])) ref[key].push(value); + break; + } +} + +function Map(textdef) { + // object for map operations (drawing coorinate transformation, etc.) + this.info = gamedata.load(textdef); + const tileset = gamedata.load(this.info.header.tileset); + const frametime = performance.now(); + gfx.load(tileset.img); + + const h = this.info.header.height, w = this.info.header.width; + const th = this.info.header.tileheight, tw = this.info.header.tilewidth; + var posx = canvas.canvas.width / 2, posy = canvas.canvas.height / 2 - h * th/2; + + canvas.fillStyle = "rgba("+this.info.header.background_color+")"; + + // precalculated tile positions + // assign x/y coordinates to each tile index + // looks dumb but is faster than on the fly isometric calculations + const dx = [], dy = []; + for ( let y = 0; y < h; y++ ) for ( let x = 0; x < w; x++ ) { + dx[y * w + x] = (w + x - y) * tw / 2; + dy[y * w + x] = (x + y) * th / 2; + } + + const npcs = []; + if (this.info.npc) for (let def of this.info.npc) { + let loc = def.location[1] * w + def.location[0]; + npcs[loc] = new Npc(def.filename) + npcs[loc].place(dx[loc], dy[loc]); + this.info.layer.find(l => l.type == "collision").data[loc] = 1; + } + + this.events = []; + for (let ev of this.info.event) { + for (let x = ev.location[0]; x < ev.location[0] + ev.location[2]; x++) + for (let y = ev.location[1]; y < ev.location[1] + ev.location[3]; y++) { + let loc = y * w + x; + if (!this.events[loc]) this.events[loc] = []; + this.events[loc].push(ev); + } + } + + // tile index for pixel position on map + this.tileAt = function(x, y) { + var r = (y + th / 2) / th; var c = (x - w * tw /2) / tw; + var nx = r + c |0; var ny = r - c |0; + return ny * w + nx; + } + + // vice versa the pixel coordinates of a given map tile + this.positionOf = (tl, ty = -1) => (~ty) ? [dx[ty * w + tl], dy[ty * w + tl]] : [ dx[tl], dy[tl] ]; + this.xOf = (tl, ty = -1) => (~ty) ? dx[ty * w + tl] : dx[tl]; + this.yOf = (tl, ty = -1) => (~ty) ? dy[ty * w + tl] : dy[tl]; + + // center map to pixel position (by setting drawing offsets) + this.center = function(x, y) { + posx = canvas.canvas.width / 2 - x; + posy = canvas.canvas.height / 2 - y; + return this; + } + + // draw the entire map, including all mobs + // mobs in an array of all heros, enemies, loot, npcs, etc. + this.draw = function(mobs) { + const bg = this.info.layer.find(l => l.type == "background").data; + const ob = this.info.layer.find(l => l.type == "object").data; + var i, mm = []; + + // mobs only have x/y pixel positions, + // to draw them in order with map tiles we set up + // an array with current tile positions of mobs + mobs.forEach(m => { + let i = this.tileAt(m.position[0], m.position[1]); + mm[i] = mobs.filter(m => i == this.tileAt(m.position[0], m.position[1])); + }); + canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height); + + // draw background layer first + for ( i = 0; i < h * w; i++ ) draw_tile(bg[i], posx + dx[i], posy + dy[i]); + + // draw object layer and mobs + for ( i = 0; i < h * w; i++ ) { + draw_tile(ob[i], posx + dx[i], posy + dy[i]); + if (mm[i]) mm[i].forEach(m => m.draw(posx + m.position[0], posy + m.position[1])); + if (npcs[i]) npcs[i].draw(posx + dx[i], posy + dy[i]); + } + } + + // draw a single map tile at screen position x/y + // tile may be animated, if so defined in tiledef + function draw_tile(tile, x, y) { + const t = tileset.tile[tile]; + const f = tileset.animation[tile]; + x = x |0; y = y |0; + + if (t && f) { + frame = ((performance.now() - frametime) / f[0][2] |0) % f.length; + canvas.drawImage(gfx[tileset.img], f[frame][0], f[frame][1], t[2], t[3], + x - t[4], y - t[5], t[2], t[3]); + } else if (t) { + canvas.drawImage(gfx[tileset.img], t[0], t[1], t[2], t[3], + x - t[4], y - t[5], t[2], t[3]); + } + } +} + function Mob(textdef) { - this.direction = 0; + // any mobile object, mostly for gfx representation + // may be hero, enemy, loot, npc, etc. this.position = [0, 0]; - this.info = gamedata[textdef]; - this.animation = "stance"; - this.previous_animation = ""; - this.frametime = performance.now(); - this.image = document.querySelector("img[src='"+ this.info.image +"']"); - if (!this.image) { - this.image = document.createElement("img"); - this.image.setAttribute("src", this.info.image); - this.image.setAttribute("style", "display: none;"); - document.querySelector("body").appendChild(this.image); - } - - this.place = function(x, y) { this.position = [x, y]; return this; } - this.direct = function(d) { this.direction = d % 8; return this; } + const info = gamedata.load(textdef); + var direction = 0; + var animation = "stance"; + var previous_animation = ""; + var frametime = performance.now(); + gfx.load(info.image) + + // some simplified npc files do not define animation frames + // render size and offset are given instead, and we + // assume, that we can just loop horizontally over the image + if (!info[animation].frame){ + info[animation].frame = []; + let rs = info.render_size, ro = info.render_offset; + + for (let i = 0; i < info[animation].frames; i++ ) + info[animation].frame[i] = [[ i * rs[0], 0, rs[0], rs[1], ro[0], ro[1]]]; + } + + // place mob on x/y pixel coordinates + // e.g. when spawning, walking, etc. + this.place = function(x, y) { + this.position[0] = x, this.position[1] = y; + return this; + } + + // change facing direction of mob + this.direct = function(d) { direction = d % 8; return this; } + + // set animation cycle for drawing + // play_once animations will automatically fall back + // to previous loop after completion this.animate = function(a) { - this.previous_animation = this.animation; - this.animation = a; - this.frametime = performance.now(); + if ( a != animation ) { + previous_animation = animation; + animation = a; + frametime = performance.now(); + } return this; } - this.draw = function(){ - var f, a = this.info[this.animation]; - var frame = ( performance.now() - this.frametime ) * a.frames.length / a.duration | 0; + // draw this mob to screen position x/y + this.draw = function(x, y){ + var f, a = info[animation]; + var f, frame = ( performance.now() - frametime ) * a.frames / a.duration | 0; + // determine current animation frame switch(a.type){ case "looped": - frame = frame % a.frames.length; + frame = frame % a.frames; break; case "play_once": - if ( frame >= a.frames.length ){ - this.animation = this.previous_animation; - this.previous_animation = ""; - this.frametime = performance.now(); - a = this.info[this.animation]; + if ( frame >= a.frames ){ + animation = previous_animation; + previous_animation = ""; + frametime = performance.now(); + a = info[animation]; frame = 0; } break; case "back_forth": - frame = frame % (a.frames.length * 2 - 2); - if ( frame >= a.frames.length ){ - frame = a.frames.length - frame % a.frames.length - 1; + frame = frame % (a.frames * 2 - 2); + if ( frame >= a.frames ){ + frame = a.frames - frame % a.frames - 1; } break; default: break; } - f = a.frames[frame][this.direction]; + f = a.frame[frame][direction]; - canvas.drawImage(this.image, f[0], f[1], f[2], f[3], - this.position[0] - f[4], this.position[1] - f[5], + canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3], + x - f[4], y - f[5], f[2], f[3]); + } + + // shortcut functions for specific animations + this.block = () => this.animate("block" ); + this.cast = () => this.animate("cast" ); + this.die = () => this.animate("die" ); + this.hit = () => this.animate("hit" ); + this.run = () => this.animate("run" ); + this.shoot = () => this.animate("shoot" ); + this.stance = () => this.animate("stance"); + this.swing = () => this.animate("swing" ); +} - // var fetch = new XMLHttpRequest(); - // fetch.open("GET", textdef, false); fetch.send(); - // this.description = fetch.responseText.split('\n'); +function Npc(textdef){ + this.info = gamedata.load(textdef); + const avatar = new Mob(this.info.gfx); + + this.place = function(x, y) { + avatar.place(x,y); + return this; + } + + this.draw = function(x, y) { + avatar.draw(x, y); + return this; } } -function Player(gender = "female", hair = "short"){ - this.x=0; this.y=0; this.direction=0; - this.limbs = { - head : (gender == "female")?new Mob("/animations/avatar/female/head_long.txt") - :new Mob("/animations/avatar/male/head_"+hair+".txt"), - chest: new Mob("/animations/avatar/"+gender+"/default_chest.txt"), +function Hero(gender = "female", hair = "short"){ + // Object for player character + // unique in single player + this.position = [0,0]; + this.stats = gamedata.load("/engine/stats.txt"); + const layers = gamedata.load("/engine/hero_layers.txt"); + var direction = 0, animation = "stance"; + hair = (gender == "female")?"long":hair; + + // hero consists of multiple mobs, one for each clothing/item overlay + var limbs = { + head : new Mob("/animations/avatar/"+gender+"/head_"+hair+".txt"), + chest: new Mob("/animations/avatar/"+gender+"/cloth_shirt.txt"), hands: new Mob("/animations/avatar/"+gender+"/default_hands.txt"), - legs : new Mob("/animations/avatar/"+gender+"/default_legs.txt"), + legs : new Mob("/animations/avatar/"+gender+"/cloth_pants.txt"), feet : new Mob("/animations/avatar/"+gender+"/default_feet.txt"), - main : new Mob("/animations/avatar/"+gender+"/dagger.txt"), - off : new Mob("/animations/avatar/"+gender+"/shield.txt") + main : null, // main hand, e.g. melee weapon, magic weapon + off : null // off hand, e.g. shield, ranged weapon } + // "dress" the player, i.e. assign clothing/item to limb + this.dress = function(limb, item) { + limbs[limb] = new Mob("/animations/avatar/"+gender+"/"+item+".txt") + limbs[limb].place(this.position[0], this.position[1]).direct(direction); + this.animate(animation); + return this; + } + + // // Wrapper functions for Mob class // // + + // place all mobs beloning to hero (when spawning, walking, teleporting, etc.) this.place = function(x,y) { - this.x = x; this.y = y; - for (var limb in this.limbs) this.limbs[limb].place(x,y); + this.position[0] = x, this.position[1] = y; + for (var limb in limbs) limbs[limb] && limbs[limb].place(x,y); return this; } + // change facing direction of hero (i.e. of all mobs) this.direct = function(d) { - this.direction = d; - for (var limb in this.limbs) this.limbs[limb].direct(d); + direction = d; + for (var limb in limbs) limbs[limb] && limbs[limb].direct(d); return this; } + // start animation cycle this.animate = function(anim){ - for (var limb in this.limbs) this.limbs[limb].animate(anim); + animation = anim; + for (var limb in limbs) limbs[limb] && limbs[limb].animate(anim); return this; } - this.draw = function(){ - gamedata["/engine/hero_layers.txt"].layers[this.direction].forEach(limb => this.limbs[limb].draw()); + this.draw = function(x, y){ + layers.layer[direction].forEach(limb => limbs[limb] && limbs[limb].draw(x, y)); return this; } + + // shortcuts for animation + this.block = () => this.animate("block" ); + this.cast = () => this.animate("cast" ); + this.die = () => this.animate("die" ); + this.hit = () => this.animate("hit" ); + this.run = () => this.animate("run" ); + this.shoot = () => this.animate("shoot" ); + this.stance = () => this.animate("stance"); + this.swing = () => this.animate("swing" ); } -canvas = document.getElementById("view").getContext("2d"); -// player = new Mob("/animations/avatar/male/clothes.txt"); -player = new Player().place(240, 160).direct(5); +function Controls(hero){ + // processes keyboard / touch / mouse + // causes according player actions + // single player only, conrol will be assigned to server in multi player + var kbdmap = { + up: 87, altup: 38, + down: 83, altdown: 40, + left: 65, altleft: 37, + right: 68, altright: 39, + } + var keys = []; + + window.addEventListener("keydown", e => keys[e.keyCode] = true ); + window.addEventListener("keyup" , e => keys[e.keyCode] = false); + setInterval(() => input(), 33.33) + + // cause player to walk, processes blocked terrain and player speed + // x/y are factors of speed and direction + // i.e. +/-1 for diagonal movement + // and +/-1.4 for horizontal/vertical movement + function translate(x, y){ + var sx = map.info.header.tilewidth * hero.stats.speed / 33.33; + var sy = map.info.header.tileheight * hero.stats.speed / 33.33; + var dx = x * sx, hx = hero.position[0]; + var dy = y * sy, hy = hero.position[1]; + var f = 2.1; + const col = map.info.layer.find(l => l.type == "collision").data; + + if (col[map.tileAt(hx + dx, hy + dy)] == 0 ) + hero.place(hx + dx, hy + dy); + else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy + sy / 1.5)] == 0 ) + hero.place(hx + dx / f, hy + sy / 1.5); + else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy - sy / 1.5)] == 0 ) + hero.place(hx + dx / f, hy - sy / 1.5); + else if ( dx == 0 && col[map.tileAt(hx + sx / 1.5, hy + dy / f)] == 0 ) + hero.place(hx + sx / 1.5, hy + dy / f); + else if ( dx == 0 && col[map.tileAt(hx - sx / 1.5, hy + dy / f)] == 0 ) + hero.place(hx - sx / 1.5, hy + dy / f); + else player.stance(); + + map.center(hero.position[0], hero.position[1]); + events(hero.position[0], hero.position[1]); + } + + function events(x, y) { + const i = map.tileAt(x,y); var ev; + if (map.events[i]) { + // intermap + if ( ev = map.events[i].find(e => (e.activate == "on_trigger" && e.intermap)) ){ + ev = ev.intermap.split(/[,]/); + map = new Map(ev[0]); + hero.place( map.xOf(ev[1] * 1, ev[2] * 1), map.yOf(ev[1] * 1, ev[2] * 1) ); + map.center( map.xOf(ev[1] * 1, ev[2] * 1), map.yOf(ev[1] * 1, ev[2] * 1) ); + } + } + } + + // process input and decide on according action + function input(){ + // facing directions, indexed by OR of key press combinations + const dir = [ -1, 0, 4, -1, 2, 1, 3, 2, 6, 7, 5, 6, -1, 0, 4, -1 ]; + // translation speed and direction, indexed by facing direction of movement + const trans = [ [-1.4,0], [-1,-1], [0,-1.4], [1,-1], [1.4,0], [1,1], [0,1.4], [-1,1] ]; + var k = 0; + + // OR of direction key presses + k += (keys[kbdmap.left] || keys[kbdmap.altleft]) ? 1 : 0; + k += (keys[kbdmap.right] || keys[kbdmap.altright]) ? 2 : 0; + k += (keys[kbdmap.up] || keys[kbdmap.altup]) ? 4 : 0; + k += (keys[kbdmap.down] || keys[kbdmap.altdown]) ? 8 : 0; + + if (~dir[k]) { + hero.direct(dir[k]).run(); + translate(trans[dir[k]][0], trans[dir[k]][1]); + } else hero.stance(); + } +} + +document.querySelector("body").setAttribute("style", "margin: 0; padding: 0;"); +canvas = document.createElement("canvas").getContext("2d"); +canvas.canvas.setAttribute("style", "display: block; border: 0; margin: 0; padding: 0;"); +document.querySelector("body").appendChild(canvas.canvas); + +canvas.canvas.width = window.innerWidth; +canvas.canvas.height = window.innerHeight; +window.addEventListener("resize", function(){ + canvas.canvas.width = window.innerWidth; + canvas.canvas.height = window.innerHeight; +}); + +// player = new Mob("animations/enemies/zombie.txt"); player.stats = { speed: 3 }; +player = new Hero(); +map = new Map("/maps/arrival.txt"); +player.place(map.xOf(map.info.header.hero_pos[0], map.info.header.hero_pos[1]), + map.yOf(map.info.header.hero_pos[0], map.info.header.hero_pos[1])); +player.direct(6).stance(); + +map.center(player.position[0], player.position[1]); +c = new Controls(player); -setInterval( function() { canvas.clearRect(0,0, 480, 320); player.draw(); }, 50); +setInterval (() => map.draw([player]), 33.33 );