Sunday, January 30, 2011

Saving Game Time as a Score in Java

I am writing a Sudoku in Java as my CS project. The Sudoku is loaded from a file and then the user is allowed to enter the solution. This is checked each time for repetitions in rows, columns or squares every time the user fills a cell. (Whether all the cells are filled is also determined.)

Getting to the point of this post, I managed to find a way how to find the game time in order to save it as a score if the user wins. This is done through System.currentTimeMillis(). This built-in method returns a long representing the program's current execution time. Hence saving the start time of the game and then subtracting the current execution time on the game's end. Below is a rough and simple pseudocode algorithm showing how this can be done (my pseudocode is closer to Java):
long startTime = System.currentTimeMillis();
.
.
.
saveScore(startTime-System.currentTimeMillis());

But what if the user exits the game and resumes the game later? One needs to save the time to a file for later retrieval. This is a rather easy task, but I had some trouble with implementing it cause I was passing a long to store the time in the "read time from file method". In Java parameters are passed by value and hence the value read from file will be lost if it is passed as argument, since long is not a reference. So I tried returning the long value this time and it did the trick. Also note that it would be safer to use stream files since it prevents the user from editing the file with a text editor such as Notepad, Vim or Notepad++. In order to read this type of file, a piece of code (program/method) using the same programming language and data format should be implemented, hence making it more difficult for average users to mess around with such files.

So here we go with the save and restore game time algorithm:
long startTime = System.currentTimeMillis();
long duration;
.
.
if user resumes last game
    duration = value read from file;
.
.
.
.
.
.
.
.
.
.
.
.
.
.
if user exited the game without solving the sudoku
    write duration+startTime-System.currentTimeMillis() to file;