I am trying to create a game, where a player can move around the games map pulled from a text file. It has 2 stores of the map, originalmap
and playermap
. originalmap
is used to reference the original state of the map, so that the player can move over tiles that have a special nature. playermap
is what the player sees, and the changes, such as moving and spawning the player itself happens in playermap
. Below is the code where both originalmap
and playermap
is created. Both maps are 2d arraylists.
class map {
//properties of the map.
private List<List<Character>> originalmap = new ArrayList<List<Character>>();
private List<List<Character>> playermap = new ArrayList<List<Character>>();
//read a map file. Existence is checked when entering filepath, so no need to code any catches.
private void createmap() {
try {
File mapFile = new File(this.filepath);
Scanner textfile = new Scanner(mapFile);
//read the entire mapfile, line by line. For every line, a mapLine converts the line into a list of characters, which is appended to the map variable.
this.mapname = textfile.nextLine().replace("name ", "");
String line2 = textfile.nextLine();
this.goldreq = Integer.parseInt(Character.toString(line2.charAt(line2.length()-1)));
while (textfile.hasNextLine()) {
String line = textfile.nextLine();
List<Character> mapLine = new ArrayList<Character>();
for (int i = 0; i<line.length();i++) {
mapLine.add(line.charAt(i));
}
this.originalmap.add(mapLine);
this.playermap.add(mapLine);
}
textfile.close();
} catch (FileNotFoundException error) {
assert true;
}
}
The issue is when I try to spawn a player, it appears that the player spawns on both the originalmap
and the playermap
. I am at a loss as to why. Below is the code where the player is spawned.
public void spawnPlayer() {
Random rand = new Random();
while (true) {
int spawnx = rand.nextInt(playermap.get(0).size());
int spawny = rand.nextInt(playermap.size());
char spawnchar = playermap.get(spawny).get(spawnx);
if (spawnchar!= '#'||spawnchar != 'G'||spawnchar != 'B') {
this.playergold = 0;
this.playerposy = spawny;
this.playerposx = spawnx;
this.playermap.get(spawny).set(spawnx,'P');
break;
}
}
}
}
N/B: these functions are called one after another (createmap, and then spawnplayer) in the default method of the class.
I tried to print the maps, expecting to see originalmap to be unchanged and playermap to be changed. Both maps were changed, without me changing originalmap after spawning the player.
> originalmap = new ArrayList
– Rhian Kansara Dec 16 '22 at 14:27>(); private List
> playermap = new ArrayList
>();` - i believe that answers the other questions as well