如何通过处理库绘制游戏地图?



我要为我正在制作的游戏创建一个地图,我不知道该怎么做。有人能给我一些指导或提示吗?谢谢你!(我使用的库是Processing)

这是我的想法:

写一个txt文件来表示地图,例如:

AAAAAAA
A     A
A  B  A
A     A
AAAAAAA
//A represents trees; B represents the player; space represents grass

每个字母代表一个20*20像素的贴图(png图片)。我不知道如何实现这样的事情。

我尝试使用loadImage()来加载每个瓷砖,但我只能把它们一个接一个地放在特定位置(编码很多…),这是非常低效的…

编辑:

感谢大家的评论!我得到了一些想法,但卡住了如何获得每行的字符索引。

我在网上搜索了很多,发现indexOf()会找到索引,但只有第一个。

例如,对上面的txt文件使用index = line.indexOf("A");,它只会找到第一个"A"在每一行。有什么方法可以解决这个问题吗?

您可以在文本文件中读取,并使用当前读取的字符数线乘以纹理的宽度作为loadImage()的X坐标读取的行数乘以纹理的高度作为Y坐标。遍历txt文件中的所有字符像这样:

PImage imgTree = loadImage("treeTexture.jpg");
PImage imgPlayer = loadImage("playerTexture.jpg");
PImage imgGrass = loadImage("grassTexture.jpg");
PImage imgMissing = loadImage("missingTexture.jpg");
PImage currentTexture;
String[] lines = loadStrings("map.txt");
for (int i = 0 ; i < lines.length; i++) //Looping through all lines. i stores the current line index
{
for (int j = 0; j < lines[i].length; j++) //Looping through all characters. j stores the current character index
{
if (lines[i].charAt(j) == "A")  //A switch statement would be more efficent but I am not sure how processing works so I just wrote this as an example
{
currentTexture = imgTree;
}
else if (lines[i].charAt(j) == "B")
{
currentTexture = imgPlayer;
}
else if (lines[i].charAt(j) == " ")
{
currentTexture = imgGrass;
}
else //For safety reasons
{
currentTexture = imgMissing;
}
image(currentTexture, j * currentTexture.width, i * currentTexture.height); 
}
}

我不完全确定如何处理工作,我没有测试这个代码,所以请使用相应的。还要记住,根据处理的工作方式,读取的数据也可能在末尾包含不可见的行结束字符(n)。如果是这种情况,那么像这样改变你的内循环:

for (int j = 0; j < lines[i].length - 1; j++)

最新更新