【问题标题】:How to draw a spruce-shape triangle in JavaScript?如何在 JavaScript 中绘制云杉形状的三角形?
【发布时间】:2021-08-16 12:48:11
【问题描述】:

如何在 JavaScript 中绘制这样的三角形?

      *
     ***
    *****
   *******
  *********
 ***********
*************

如果你能解释一下它是如何工作的,那就太好了。

到目前为止,我有这个代码:

let lines = 7;
let str = ' ';
for (let i = 0; i < lines; i++) {
  str += '*';
  console.log(str);
}

【问题讨论】:

标签: javascript algorithm drawing shapes ascii-art


【解决方案1】:

以 ASCII 艺术风格绘制云杉林

先指定图片的尺寸,再指定云杉树的顶点坐标。

云杉林:

      *                *                                                        
     ***       *      ***        *                                        *     
    *****     ***    *****      ***         *                            ***    
   *******   *****  *******    *****       ***                  *       *****   
  ********* ****************  *******     *****        *       ***     *******  
 *************************************   *******      ***     *****   ********* 
*************************************** *********    *****   ******* ***********
**************************************************  ******* ********************
********************************************************************************

Try it online!

function spruceForest(width, height) {
  let forest = {
    plot: [],
    addSpruce: function(x, y) {
      for (let i = 0; i < height - y; i++)
        for (let j = -i; j <= i; j++)
          if (x + j >= 0 && x + j < width)
            this.plot[y + i][x + j] = 1;
      return this;
    },
    output: function() {
      for (let i = 0; i < height; i++) {
        let row = this.plot[i];
        let line = '';
        for (let j = 0; j < width; j++)
          line += row[j] == 1 ? '*' : ' ';
        console.log(line);
      }
    }
  }; // populate an empty plot
  for (let i = 0; i < height; i++) {
    forest.plot[i] = [];
    for (let j = 0; j < width; j++)
      forest.plot[i][j] = '';
  }
  return forest;
}

spruceForest(80, 9) // draw a spruce forest in ASCII-art style
  .addSpruce(6, 0).addSpruce(15, 1).addSpruce(23, 0)
  .addSpruce(33, 1).addSpruce(44, 2).addSpruce(55, 4)
  .addSpruce(64, 3).addSpruce(74, 1).output();

受此答案启发:Draw an ASCII spruce forest in Java

【讨论】:

    【解决方案2】:

    这段代码应该可以工作:

    // You can specify line number
    function drawTriangle(lines = 7) {
      for (let i = 0; i < lines * 2; i+=2) {
        const str = " ".repeat((lines * 2 - i) / 2) // Put spaces before '*'
                      + "*".repeat(i + 1);          // Put '*' after spaces
        console.log(str);
      }
    }
    
    drawTriangle();  // 7 lines
    drawTriangle(9);
    drawTriangle(20);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      相关资源
      最近更新 更多