For some odd reason when I attempt to move my character in the game, the array swapping for “movement” will not work and when I try to print the current position of the character for the first two moves in the game, nothing shows. It’s just acting odd in general. Could someone explain to me possibly what I’m doing wrong or at least how I can do it better? Thank.
Code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Adventure {
private Scanner in_file;
private int x_size, y_size, px, py, dx, dy;
private char[][] level;
private boolean game;
public Adventure() {
x_size = y_size = 20;
level = new char[x_size][y_size];
px = py = 1;
dx = dy = 0;
game = true;
}
public static void main(String []args) {
Adventure adv = new Adventure();
adv.load_game();
adv.main_game();
System.out.println("ADVENTURE");
}
public void load_game() {
try {
in_file = new Scanner(new File("level.txt"));
} catch (FileNotFoundException e) {
System.err.println("ERROR: Level could not be loaded!");
System.exit(1);
}
for (int i = 0; i < level.length; i++ ) {
for (int j = 0; j < level[i].length; j++) {
if (in_file.hasNextInt()) {
int nextInt = in_file.nextInt();
if (nextInt == 0)
level[i][j] = '-';
else if (nextInt == 1)
level[i][j] = '#';
}
}
}
in_file.close();
}
public void new_game() {
}
public void main_game() {
Scanner key = new Scanner(System.in);
Adventure adv_move = new Adventure();
level[px][py] = 'Q';
while (game) {
for (int i = 0; i < level.length; i++) {
for (int j = 0; j < level[i].length; j++) {
System.out.print(level[i][j]);
}
System.out.println();
}
System.out.println();
System.out.print("Enter a letter choice to move ->");
String temp = key.nextLine();
if (temp.equals("w")) {
dx = -1;
dy = 0;
}
else if (temp.equals("a")) {
dy = -1;
dx = 0;
}
else if (temp.equals("s")) {
dx = 1;
dy = 0;
}
else if (temp.equals("d")) {
dy = 1;
dx = 0;
}
else
dx = dy = 0;
System.out.println();
adv_move.move_check();
}
}
public void move_check() { //DYSFUNCTIONAL ARRAY!!!!
System.out.println(level[px][py]);
// System.out.println(level[px+dx][py+dy]);
if (level[px+dx][py+dy] != '#') {
level[px][py] = '-';
px += dx;
py += dy;
level[px][py] = 'Q';
}
else
System.out.print("Move invalid.\n");
}
public void save_game() {
}
}
The issue you’re having is that in the
main_game()method, you are creating a newAdventureobject and callingmove_check()on that, which doesn’t have any of your level data, which you loaded into theadvvariable inmain(). Therefore it is always referencing an empty char array and giving you unintended results.Removing the new object declaration and just calling
move_check()itself should get you back on track.