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

问题描述

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

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");
  • 现在我们要遍历矩阵的 y x 方向
for (let y=0; y<asciiArt.length; y++) {
  for (let x=0; x<asciiArt[y].length; x++) {
     // ...
  }
}
  • 在内部for循环中,我们以正确的颜色在正确的位置绘制矩形
colorMap[asciiArt[y][x]] 
// This is the desired color ('.' --> "black",'#' --> "white")

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...