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

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


let simpleLevelPlan = `

......................

..##################..

..#................#..

..#...###....###...#..

..#...###....###...#..

..#................#..

..#................#..

..###################..

......................`;

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


暮色呼如
浏览 97回答 1
1回答

蓝山帝景

这是一种基本(简单)的方法,可以按照您想要的方向实现某些目标。const asciiArt = `........................##################....#................#....#...###....###...#....#...###....###...#....#................#....#................#....###################.......................`.split("\n");const colorMap = {&nbsp; "." : "black",&nbsp; "#" : "white"}const canvas = document.getElementById("canvas");const ctx = canvas.getContext("2d");canvas.width = canvas.height = 300;for (let y=0; y<asciiArt.length; y++) {&nbsp; for (let x=0; x<asciiArt[y].length; x++) {&nbsp; &nbsp; let sizeX = canvas.width / asciiArt[y].length,&nbsp; &nbsp; &nbsp; &nbsp; sizeY = canvas.height / asciiArt.length;&nbsp; &nbsp; let pixelX = sizeX * x,&nbsp; &nbsp; &nbsp; &nbsp; pixelY = sizeY * y;&nbsp; &nbsp; ctx.fillStyle = colorMap[asciiArt[y][x]] || "white";&nbsp; &nbsp; ctx.fillRect(pixelX, pixelY, 30, 30);&nbsp;&nbsp;&nbsp; }}<canvas id="canvas"></canvas>一些解释:我们在新行字符处拆分 asciiArt 使用.split("\n")const asciiArt = `........................##################....#................#....#...###....###...#....#...###....###...#....#................#....#................#....###################.......................`.split("\n");现在我们遍历矩阵的y和x方向for (let y=0; y<asciiArt.length; y++) {&nbsp; for (let x=0; x<asciiArt[y].length; x++) {&nbsp; &nbsp; &nbsp;// ...&nbsp; }}在内部 for 循环中,我们在正确的位置用正确的颜色绘制矩形colorMap[asciiArt[y][x]]&nbsp;// This is the desired color ('.' --> "black", '#' --> "white")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript