【发布时间】:2016-08-19 04:47:07
【问题描述】:
为了一个学校项目,我不得不用 Java 编写一个小游戏。 游戏是 RushHour,你可以在这里看到它的一个例子:http://www.thinkfun.com/play-online/rush-hour/。
我的老师现在要求我允许我的代码读取外部文件,以便游戏的初始状态不再在我的 main 中硬编码,并且可以自定义游戏的参数(棋盘的大小,游戏中的汽车数量...)
这是我的第一个 JSON 文件,它设置了一款经典游戏。
{
"ClassicBoard" :
{
"height" : "6",
"width" : "6",
"exit":
{
"row" : "2",
"column" : "5"
}
},
"ListOfCars" :
{
"car2" :
{
"char" : "2",
"size" : "3",
"orientation" : "vertical",
"currentPosition":
{
"row" : "2",
"column": "2"
}
},
"car3" :
{
"char" : "3",
"size" : "3",
"orientation" : "vertical",
"currentPosition":
{
"row" : "2",
"column": "4"
}
}
},
"redCar":
{
"char" : "1",
"size" : "2",
"orientation" : "horizontal",
"currentPosition":
{
"row" : "2",
"column": "0"
}
}
}
我试图找到如何读取文件并重用它的输出来创建 RushHourGame 对象。这是构造函数。
public RushHourGame(Board board, List <Car> cars, Car redCar) throws RushHourException
{
this.board = board;
this.redCar = redCar;
if(((redCar.getOrientation() == Orientation.HORIZONTAL)
&& (board.getExit().getRow() != redCar.getCurrentPosition().getRow()))
|| (((redCar.getOrientation() == Orientation.VERTICAL)
&& (board.getExit().getColumn() != redCar.getCurrentPosition().getColumn()))))
{
throw new RushHourException("Car must be aligned with the exit, "
+ "a default game has been created");
}
board.put(redCar);
for (Car putCars : cars)
{
board.put(putCars);
}
}
我尝试使用 BufferedReader,像这样。
public static String readFile(String filename)
{
String result ="";
try
{
BufferedReader br = new BufferedReader (new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
line = br.readLine();
}
result = sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
但我不知道如何使用它来解析我的 JSON 文件。有人可以帮助我吗?
【问题讨论】:
标签: java json parsing buffer reader