java - 如何通过 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() 会找到索引,但只有第一个。
例如,index = line.indexOf("A");
用于上面的 txt 文件,它只会找到每行中第一个“A”的索引。有什么方法可以解决这个问题吗?
解决方案
您可以读取 txt 文件并使用当前行中读取的字符数乘以纹理的宽度作为 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++)
推荐阅读
- json - 将对象转换为数组
- asp.net-core - 使用 Windows 身份验证的自定义状态代码页
- python - 将图像添加到 tkinter 网格但未显示
- angular - ng2-charts - Tolltip color dont match line color
- c++ - 未能在 SFINAE 中将概念类型识别为 bool
- r - 那么,Carets jumpBackward 究竟是如何工作的呢?
- python - 使用 Python 中的入住和退房日期计算每天的预订数量
- c# - 将 DataGrid 行号绑定到属性
- reactjs - React useHistory,对象的类型为“未知”
- firebase - flutter build apk --release 在运行flutter build apk时失败-调试工作正常