I had to program a little game in Java for a project for school. The game is RushHour, and you can see an example of it here: http://www.thinkfun.com/play-online/rush-hour/.
My teachers ask me now to allow my code to read an external file so that the initial state of the game is no longer hard coded in my main, and that the parameters of the game can be customized (the size of the board, the number of the cars in the game...)
Here's my first JSON file, which sets a classic game.
{
"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"
}
}
}
I'm trying to find how to read the file and to reuse it's output for creating a RushHourGame object. Here's the constructor.
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);
}
}
I tried to use a BufferedReader, like this.
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;
}
But I am not sur how to use it for parsing my JSON file. Somebody can help me?