0

I am currently working on a basic chess program that allows the user to save the current game and come back later and pick up from where they left off. The only problem is I do not know how to save a 2d array to a disk file. I am confused even more by the fact that the set of code needs to write each value individually and not output anything if the value is "null". I have looked around and cannot find anything that really answers my question. I am fairly new at coding so i apologize if this is a basic question. My current set of code is:

Path file = Paths.get("fileName");
Files.write(file, lines, Charset.forName("UTF-8"));

PrintWriter save = new PrintWriter(new FileOutputStream(("fileName")));
Path.close();
Steave
  • 29
  • 5

1 Answers1

1

In a first instance: an array in Java is always an Object; so you can simply use Java serialization in order to read/write the whole array in one shot. In other words: you tell Java to turn your whole array in a stream of bytes; and then you write those bytes to a file. And later on, you read that back. And you dont have to worry about empty slots at all.

All you need to do for that: make sure that the class of which you have a two-dim array there is Serializable.

As said, that is the "easy" solution. For learning, you can of course implement your own strategy. And the key there is: there is no "default" way of writing array data in Java. You have to write code that takes a one/two/whatever dim array; creates a representation out of that ... writes that to file. And then your code is able to reverse that operation. Some pseudo code to give you an idea:

np = compute number of pieces currently found on the board 
write np
for col = a to h
  for row = 1 to 8
     if board(row/col) is not empty
       write col, row, piece on that slot

The point is: the above code defines a mapping from a in-memory board to something that can be written into a file. And that can be reversed, too.

But honestly, you are going down the wrong path. You don't want to save a board (or two dim-array) at all.

Instead, consider what a board represents ... nothing else but a specific result of a series of actions.

When you buy a book on cheese, and you see discussions about matches, do they just draw single boards?! Nope, then you typically look at a sequence of all the moves; and some of the boards inbetween.

Long story short: one potential "base" element of your design could be a move class; that simply represents one move.

And now, a chess game becomes a List<Move> (list of Move objects). And just by making Move serializiable, you can easily read/write that whole history into files.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248