let self = this; map.forEach(((line, y) => { for (let x = 0; x < line.length; x++) { this.grid.set(new Vector(x, y), elementFromChar(legend, line[x])); } }).bind(self));
this._stastics = {}; this.clearstastics(); }
Terminal Animation
最最早的时候,我当时在nodejs中实现了这个游戏,试图在终端中不断打印刷新来生成动画。
你知道的,终端的IO效率非常低,世界一大,非常之卡,那是第一个UI实现。一个古老的终端动画思路。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
drawTerminal() { process.stdout.clearScreenDown(); let element let line = ''; for (let y = 0; y < this.grid.height; y++) { for (let x = 0; x < this.grid.width; x++) { element = this.grid.get(new Vector(x, y)); line += (charFromElement(element) || " "); if (x == this.grid.width-1) { line += '\n'; } } } process.stdout.write(line); process.stdout.cursorTo(0, 0); }
drawTerminal() { process.stdout.clearScreenDown(); let line = ''; for (let y = 0; y < this.grid.height; y++) { for (let x = 0; x < this.grid.width; x++) { let element = this.grid.get(new Vector(x, y)); let color = this._canvasLegend[charFromElement(element)]; if (!color) { line += "\x1b[107m \x1b[0m"; } else { let colorC = terminalColors[color]; line += (colorC + " " + "\x1b[0m"); } } line += '\n'; } process.stdout.write(line); process.stdout.cursorTo(0, 0); }
drawDom() { this._canvas.innerHTML = ''; for (let y = 0; y < this.grid.height; y++) { for (let x = 0; x < this.grid.width; x++) { element = this.grid.get(new Vector(x, y)); let color = this._canvasLegend[charFromElement(element)]; let e = document.createElement('div'); e.style.width = size + 'px'; e.style.height = size + 'px'; e.style.backgroundColor = color; this._canvas.appendChild(e); } } }
当然,也可以生成一堆html然后每次刷新只插入一次。妄图效率能高一些。
1 2 3 4 5 6 7 8 9 10 11 12 13
drawDom() { let html = ''; let size = this._size; this._canvas.innerHTML = ''; for (let y = 0; y < this.grid.height; y++) { for (let x = 0; x < this.grid.width; x++) { let element = this.grid.get(new Vector(x, y)); let color = this._canvasLegend[charFromElement(element)]; html += `<div style='background-color:${color};width:${size}px;height:${size}px;float:left'></div>` } } this._canvas.innerHTML = html; }
聪明的我留给读者又一个练习,给每种单位一个图片,让最后渲染效果不是色块而是图片。
Canvas Animation
接下来欢迎来到canvas的世界。
使用canvas很简单,准备画布,然后给出js指令告诉canvas如何绘图。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
drawCanvas() { let element; this._ctx.save(); for (let y = 0; y < this.grid.height; y++) { for (let x = 0; x < this.grid.width; x++) { element = this.grid.get(new Vector(x, y)); this._ctx.fillStyle = this._canvasLegend[charFromElement(element)]; this._ctx.fillRect(x * this._size, y * this._size, this._size, this._size); // deadly slow if so. //this._ctx.beginPath(); //this._ctx.arc(x * this._size, y * this._size, this.size / 2, 0, Math.PI * 2); //this._ctx.fill(); this._ctx.fillStyle = 'white'; } } this._ctx.restore(); }