I am making a simple game with a save and load. So far, I have the save game working and it saves all the objects positions to a .dat file. Each line has 3 coordinates (x, y, z) split by a colon. Example:
23.762622833251953:3.887784719467163
22.5:0.5:18.5 23.5:0.5:20.5 26.5:0.5:5.5 28.5:0.5:21.5 30.5:0.5:4.5 33.5:0.5开发者_StackOverflow:19.5 35.5:0.5:4.5 38.5:0.5:15.5 39.5:0.5:3.5 41.5:0.5:9.5
The very first line is coordinates to the first-person view of the player. This is easy enough to implement since I pass each coordinate into an array, so the x-position is the first element [0] and the z coordinate is the second element [1]. The y coordinate is always the same, even for blocks, so I didn't bother saving it, but I did for the blocks for some reason.
Here is the method to save a game:
public void saveGame()
{
File file = new File("quickSave.dat");
try {
FileWriter writer = new FileWriter(file);
writer.write(env.getCameraX()+":"+env.getCameraZ()+"\n");
for (int row = 0; row < map.length; row++)
{
for (int col = 0; col < map[row].length; col++)
{
if (map[row][col] != null) {
EnvObject block = map[row][col];
writer.write(block.getX()+":"+block.getY()+":"+block.getZ()+"\n");
}
}
}
writer.close();
JOptionPane.showMessageDialog(null, "Game saved");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
The problem is reading each line from the file and then passing those coordinates into the object. I only implemented passing coordinates into the players perspective, which was easy because I was working with only 2 elements.
I was thinking of making another array with 2 dimensions (taking out the y-coordinate, the middle one), and each element is one line from the file, but how do I do this? Or is this another, more elegant way?
Here is my load game method so far:
public void loadGame() {
File file = new File("quickSave.dat");
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
String[] elements = line.split(":");
env.setCameraXYZ(new Float(elements[0]), 0.5,
new Float(elements[1]));
JOptionPane.showMessageDialog(null, "Game loaded");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
How about using serialization? Store your state variables into an ObjectOutputStream
and load them from an ObjectInputStream
. Let the JVM handle all this low level bookkeeping for you, unless you really do need a format that is human-readable and editable.
BufferedReader.readLine()
will help you. You'll need to split the read-in line with String.split()
, and the convert each returned string into a float with Float.parseFloat()
or new Float(someString)
.
I think that's what you're asking anyway
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
String[] coords = line.split(":");
EnvObject block = new EnvObject(Float.parseFloat(coords[0],
Float.parseFloat(coords[1],
Float.parseFloat(coords[2]
);
someArray.add(block);
}
精彩评论