如何阅读 Javascript 游戏的关卡计划?

How to read level plans for Javascript game?

我知道有办法做到这一点,但我不记得怎么做了。我查看了我所有旧的 javascript 项目,但我无法在任何地方找到它。这是我需要的:我有一个变量(如下所示),我希望能够让 canvas 将其解释为图像。

let simpleLevelPlan = `
......................
..##################..
..#................#..
..#...###....###...#..
..#...###....###...#..
..#................#..
..#................#..
..###################..
......................`;

基本上我希望将其解释为每个主题标签符号 (#) 是一个黑色方块,句点 (.) 是一个白色方块,以便形成一个图像。我已经尝试了很多东西,但我遇到的问题是我无法将其拆分成将由循环读取的片段。提前致谢!

这是一种基本(简单)的方法,可以按照您想要的方向实现目标。

const asciiArt = `
......................
..##################..
..#................#..
..#...###....###...#..
..#...###....###...#..
..#................#..
..#................#..
..###################.
......................`.split("\n");

const colorMap = {
  "." : "black",
  "#" : "white"
}

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = canvas.height = 300;

for (let y=0; y<asciiArt.length; y++) {
  for (let x=0; x<asciiArt[y].length; x++) {
    let sizeX = canvas.width / asciiArt[y].length,
        sizeY = canvas.height / asciiArt.length;
    let pixelX = sizeX * x,
        pixelY = sizeY * y;
    ctx.fillStyle = colorMap[asciiArt[y][x]] || "white";
    ctx.fillRect(pixelX, pixelY, 30, 30);  
  }
}
<canvas id="canvas"></canvas>


一些解释:

  • 我们使用 .split("\n")
  • 在换行字符处拆分 asciiArt
const asciiArt = `
......................
..##################..
..#................#..
..#...###....###...#..
..#...###....###...#..
..#................#..
..#................#..
..###################.
......................`.split("\n");
  • 现在我们遍历矩阵的 yx 方向
for (let y=0; y<asciiArt.length; y++) {
  for (let x=0; x<asciiArt[y].length; x++) {
     // ...
  }
}
  • 在内部 for-loop 我们在正确的位置用正确的颜色绘制矩形
colorMap[asciiArt[y][x]] 
// This is the desired color ('.' --> "black", '#' --> "white")