如何在CSS,HTML和Vue3中创建金字塔?

xwbd5t1u  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(189)

我已经有一个动态创建的金字塔。它看起来像这样(这是一个state.pyramidlevel = 3),因为它有3层:

使用以下代码:

<div class="overflow-auto">
   <div id="zoomable" class="">
      <div v-html.domProps="state.pyramid" style="width: max-content; height: 100vh;"></div>
   </div>
</div>

function createPyramid() {

    const height = state.pyramidlevel;

    let pyramidstr = '';

    // Start with 1 asterisk in the first row
    let numAsterisks = 2;

    for (let row = 0; row < height; row++) {
        let rowStr = '';

        // Add spaces to center the pyramid
        for (let space = 0; space < height - row - 1; space++) {
            rowStr += '';
        }

        // Add div for this row
        for (let star = 0; star < numAsterisks; star++) {
            rowStr += `
            <div 
            style="
                text-align:center;
                margin:3px; 
                width: 150px; 
                height: 30px; 
                border: 1px solid black; 
                background-color: rgb(255, 255, 255);">

                Vacant
            </div>`;
        }

        // Add this row to the pyramid
        pyramidstr += `<div
        
        style="
            display: flex; 
            place-content: center;
        "
        
        >${rowStr}</div>`;

        // Double the number of asterisks for the next row
        numAsterisks *= 2;
    }

    state.pyramid = pyramidstr;

}

现在,这就是我头疼的地方:
我希望我的金字塔是,1:2,这意味着,每一块砖应该在每两块砖下面的中间:与state.pyramidlevel = 2类似:

.____.            .____.
     |____|            |____|
.____.    .____.   .____.  .____.
|____|    |____|   |____|  |____|

等等......
我真的需要帮助。我已经忙了三天了。谢谢。

wwtsj6pe

wwtsj6pe1#

我不认为当你在每一层加倍积木时这会起作用,因为积木很快就会彼此远离而被感知为堆叠的,即。

o               o
   o       o       o       o
 o   o   o   o   o   o   o   o
o o o o o o o o o o o o o o o o

已经有两座金字塔了。想象一下再加两层...
简单堆叠很容易:
x一个一个一个一个x一个一个二个一个x一个一个三个一个
由于它的增长方式,您可以使用简单的水平边距来调整块之间的空间。
随着行大小翻倍,空间呈指数增长。使用容器对我来说似乎更容易:

function createPyramid(height) {
  let pyramidstr = [];

  for (let row = 0; row < height; row++) {
    pyramidstr.push('<div class="pyramid-level">')
    const blockWidth = (1 << (height - row - 1)) * 20;
    for (let star = 0; star < 1<<(row+1); star++) {
      pyramidstr.push(`
          <div class="pyramid-block-container" style="width: ${blockWidth}px">
            <div class="pyramid-block"></div>
          </div>`
      );
    }
    pyramidstr.push(`</div>`);
  }
  return pyramidstr.join('');
}

document.getElementById('pyramid-root').innerHTML = createPyramid(4)
.pyramid-level {
  display: flex;
  place-content: center;
}

.pyramid-block {
  width: 15px;
  height: 15px;
  border: 1px solid black;
  background-color: purple;
}
.pyramid-block-container{
  justify-content: center;
  display: flex;
}
<div id="pyramid-root"></div>

不出所料,看起来摇摇晃晃的,对吧?
很有趣,希望能有所帮助。

相关问题