I wanted to create a save game system for my city building game that did not require the player to input a name for the city. It was also important to allow infinite save games, so I could not just use save slots to solve the problem. With a bit of help, I devised a system that would allow the player to optionally enter a name, and if they didn't the game would determine a default name based on the existing save names.
At first I was just counting all of the existing worlds and then adding that number to "world"
to get the name. However, I was concerned about the edge case where someone would, for example, make 5 worlds, then delete "world4"
, and then the game would suggest the name "world5"
again, and if the player wasn't paying attention, their save would be overwritten.
When the user chooses to start a new game, a TextField appears that is populated by the correct string, which would be "world"
followed by the next unused number.
String startName = this.getFirstUnusuedWorldName(this.getNumWorlds());
this.worldNameField = new TextField(startName, this.skin);
Here is the getNumWorlds()
method:
private int getNumWorlds() {
FileHandle[] files = Gdx.files.local("worlds/").list();
int numDirectories = 0;
for (FileHandle handle : files) {
if (handle.isDirectory()) {
numDirectories++;
}
}
return numDirectories;
}
And here is the getFirstUnusuedWorldName
method:
private String getFirstUnusuedWorldName(int numWorlds) {
FileHandle[] files = Gdx.files.local("worlds/").list();
if (files.length == 0) {
return "world1";
}
ArrayList<String> possibleNames = new ArrayList<String>();
for (int i = 1; i <= numWorlds + 1; i++) { //world names start with 1, need to search 1 past length
possibleNames.add("world" + String.valueOf(i));
}
for (String possibleName : possibleNames) {
boolean containsName = false;
for (FileHandle file : files) {
if (file.name().equals(possibleName)) {
containsName = true;
}
}
if (!containsName) {
return possibleName;
}
}
return "world1";
}
I'm hoping there's a better way to do this.