【问题标题】:How to read level plans for Javascript game? [closed]如何阅读 Javascript 游戏的关卡计划? [关闭]
【发布时间】:2020-09-09 13:52:50
【问题描述】:

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

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

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

【问题讨论】:

  • 我不太清楚你所说的“作业”是什么意思。
  • 对不起,“作业”一词可能不适用,但请务必阅读答案。它提供了有关如何提出此类问题的建议。
  • 好的,我一定会的。

标签: javascript function html5-canvas decode


【解决方案1】:

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

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);  
  }
}
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

一些解释

  • 我们正在使用 .split("\n") 在新行 Characters 处拆分 asciiArt
const asciiArt = `
......................
..##################..
..#................#..
..#...###....###...#..
..#...###....###...#..
..#................#..
..#................#..
..###################.
......................`.split("\n");
  • 现在我们正在遍历矩阵的 yx 方向
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")

【讨论】:

  • 这很有帮助。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
相关资源
最近更新 更多