Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 37

Thread: Read ASCII art map and store the information in 2D array (int[][] or char[][])

  1. #1
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Hi, I've written some code to do this, but it's not working as I expect and am at a loss on how to fix it.

    This is what the ASCII map looks like:
    ###################
    #.................#
    #......G........E.#
    #.................#
    #..E..............#
    #..........G......#
    #.................#
    #.................#
    ###################

    Here's how I've tried to store the information in a 2D array:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
     
    public class Map {
     
    	public void importMap() throws IOException{
    		BufferedReader br = new BufferedReader(new FileReader("map.txt"));
    		String line;
     
    		while ((line = br.readLine()) != null){
    			for (char ch: line.toCharArray()){
    				final int M = 19;
    				final int N = 9;
    				char [][] matrix = new char[M][N];
    				for (int r = 0; r < M; r++){
    					for (int c = 0; c < N; c++){
    						matrix[r][c] = ch;
    					}
    				System.out.println(Arrays.deepToString(matrix));
    				}
    		br.close();
    			}
    		}
    	}
     
    	public static void main(String[] args) throws IOException{
    		Map r = new Map();
    		r.importMap();
     
    	}
    }


    But it's not printing out what I'm expecting. It's printing out:

    [[#, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #], [

    What is printed is much larger than what I've copy and pasted but I can't post it all here.

    The error I get is:

    Exception in thread "main" java.io.IOException: Stream closed
    	at java.io.BufferedReader.ensureOpen(Unknown Source)
    	at java.io.BufferedReader.readLine(Unknown Source)
    	at java.io.BufferedReader.readLine(Unknown Source)
    	at Map.importMap(Map.java:26)
    	at Map.main(Map.java:44)

    Thanks for the help!


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    What are M and N? Give your variables better names.

    Is there a chance you have the boundaries of the nested for loops backwards? Better variable naming might help you keep it straight.

  3. #3
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    I've renamed the variables M and N to columns and rows respectively. I think that's what they should be as you can see from the ASCII map there are 19 columns and 9 rows.

    I've also tried printing out specific places in the array using:

    System.out.println(matrix[7][7]);

    But whatever numbers I put in the "matrix[][]" it always prints out different variations of the "#" with a different number of spaces in between the lines. Looking at the ASCII map, shouldn't [7][7] print out a "."?

    Here is my updated code:
     
     
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
     
    public class Map {
     
    	public void importMap() throws IOException{
    		BufferedReader br = new BufferedReader(new FileReader("map.txt"));
    		String line;
     
    		while ((line = br.readLine()) != null){
    			for (char ch: line.toCharArray()){
    				final int columns = 19;
    				final int rows = 9;
    				char [][] matrix = new char[columns][rows];
    				for (int r = 0; r < columns; r++){
    					for (int c = 0; c < rows; c++){
    						matrix[r][c] = ch;
    					}
    				System.out.println(matrix[7][7]);
    				}
    		br.close();
    			}
    		}
    	}
     
    	public static void main(String[] args) throws IOException{
    		Map r = new Map();
    		r.importMap();
     
    	}
    }

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    You're making it harder than it is, and I think you're closing the buffered reader inside the while loop. Your code indentation is inconsistent, so it's hard to tell at a glance.

    Define the matrix before reading the data from the file. I used a constructor, like:
        // default constructor
        public Map()
        {
            matrix = new char[ROWS][COLUMNS];
     
        } // end default constructor
    with the necessary variables defined beforehand. Then reading the file can be as simple as:
            int i = 0;
            while ((line = br.readLine()) != null)
            {
                // convert each line read to a char array
                matrix[i++] = line.toCharArray();
            }
            br.close();

  5. #5
    Member Ganeprog's Avatar
    Join Date
    Jan 2014
    Location
    Chennai,India
    Posts
    80
    My Mood
    Love
    Thanks
    3
    Thanked 6 Times in 6 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    hi greg,

    You declared the matrix in 2 dimension array but what is the below line represent. Please explain.

    matrix[i++] = line.toCharArray();

    Is it a 2 dimension matrix?????. I work out this it show first line. I dont know how it is working.

    Thanks,

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Some find it more intuitive to think of multi-dimensional arrays in Java as "arrays of arrays." If you think of it that way, matrix[x][y] is an array of x rows each holding an array of y columns, and y doesn't have to be the same for each row. From that perspective, each row of the matrix[][] can be assigned a matrix of y columns:

    matrix[i] = someString.toCharArray(); // where the resulting char[] array has 1 row and 1 column

    Hope this helps. It can be a bit mind bending at first. Try it and see.

  7. #7
    Member Ganeprog's Avatar
    Join Date
    Jan 2014
    Location
    Chennai,India
    Posts
    80
    My Mood
    Love
    Thanks
    3
    Thanked 6 Times in 6 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Ya correct its bit tricky. But sorry could you please explain with simple example. I like this way i am eager to learn this.

    Thanks in advance.

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    PMd you the OP's original code modified to use the suggested approach.

  9. #9
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Hi, I'm struggling a bit with this. I've tried what you said, but I keep getting errors. Here's the code I've got:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
    public class Map {
     
    	public Map(){
    		matrix = new char[ROWS][COLUMNS];
    	}
     
    	public void importMap() throws IOException{
     
    		BufferedReader br = new BufferedReader(new FileReader("map.txt"));
    		String line;	
     
                    int i = 0;
                    while ((line = br.readLine()) != null)
                    {
                          // convert each line read to a char array
                          matrix[i++] = line.toCharArray();
                    }
                    br.close();
    	}
     
    	public static void main(String[] args) throws IOException{
    		Map r = new Map();
    		r.importMap();
     
    	}
    }

    There is an error on the matrix constructor saying that it cannot be resolved to a variable. There is the same error on the "[ROWS][COLUMNS]". I think it could be perhaps because I'm not using the constructor correctly but I'm not sure.

    Thanks for all the help so far!

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    The error messages should be clear: variables need to be declared before use. For instance variables, you might do something like:
    public class Map
    {
        // instance variables
        private final int ROWS = 9;
        private final int COLUMNS = 19;
        private char[][] matrix;
     
        // default constructor
        // etc . . .

  11. #11
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Right, I think I've got it working!

    If you don't mind, could you just have one last look to check I've satisfied the requirements:
    ///Create a class Map that:
    ///Reads one of the sample ASCII-art map files (your code should be able to load any map written in the same format).
    ///Stores the map information in a 2D array (int[][] or char[][]).
    Here's the code, and I've added a print statement to check that it works, which I think it does:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
     
     
    public class Map {
     
    	private final int ROWS = 9;
    	private final int COLUMNS = 19;
    	private char[][] matrix;
     
    	public Map(){
    		matrix = new char[ROWS][COLUMNS];
    	}
     
    	public void importMap() throws IOException{
     
    		BufferedReader br = new BufferedReader(new FileReader("map.txt"));
    		String line;	
     
            int i = 0;
            while ((line = br.readLine()) != null)
            {
                // convert each line read to a char array
                matrix[i++] = line.toCharArray();
            }
            System.out.println(Arrays.deepToString(matrix));
            br.close();
    	}
     
    	public static void main(String[] args) throws IOException{
    		Map r = new Map();
    		r.importMap();
     
    	}
    }

    and what's printed as a result it:
    [[#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #], [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #], [#, ., ., ., ., ., ., G, ., ., ., ., ., ., ., ., E, ., #], [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #], [#, ., ., E, ., ., ., ., ., ., ., ., ., ., ., ., ., ., #], [#, ., ., ., ., ., ., ., ., ., ., G, ., ., ., ., ., ., #], [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #], [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #], [#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]]

    Thanks for helping, you've really talked me through it and helped me to understand it!

  12. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Looks okay to me. The only "requirements" I'm aware of are in your thread title, so you may want to go back to the actual assignment and make sure you've done everything that was asked for. Sometimes we lose sight of the bigger problem when we're focused on the minor challenges along the way.

  13. #13
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    I have just realised that I had overlooked something.

    I need to be able to use any map that is written in the same form as the one I posted, so whilst that one was 9 rows by 19 columns they won't all be like that.
    Therefore I need to be able to get the number of rows and columns from the text file. I assume this will prevent me from using the code:
    private final int ROWS = 9;
    private final int COLUMNS = 19;

    I've written some code to read the number of lines but I don't know where to put it to set ROWS = 9.

    The code is:
    BufferedReader br = new BufferedReader(new FileReader("map.txt"));
    		String line;	
    		int lines = 0;
            int i = 0;
            while ((line = br.readLine()) != null){
            lines++;
            }
            System.out.println(lines);
    	}

    I'm also stumped on how to count the characters per line, but I thought it would be a good idea to count total characters in the file and divide by number of ROWS?

    --- Update ---

    I've figured it out! Here's the code in case anyone wants to see how:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
     
    ///Create a class Map that:
    ///Reads one of the sample ASCII-art map files (your code should be able to load any map written in the same format).
    ///Stores the map information in a 2D array (int[][] or char[][]).
     
    public class Map {
     
    	public int ROWS;
    	public int COLUMNS;
    	private char[][] matrix;
     
    	public Map() throws IOException{
    		BufferedReader kr = new BufferedReader(new FileReader("map.txt"));
    		String line;	
    		int ROWS = 0;
            int COLUMNS = 0;   
            while ((line = kr.readLine()) != null){
    	        ROWS++;
    	        COLUMNS += line.length();
            }
    		matrix = new char[ROWS][COLUMNS];
    	}
     
    	public void importMap() throws IOException{
     
    		BufferedReader br = new BufferedReader(new FileReader("map.txt"));
    		String line;	
     
            int i = 0;
            while ((line = br.readLine()) != null)
            {
                // convert each line read to a char array
                matrix[i++] = line.toCharArray();
            }
            System.out.println(Arrays.deepToString(matrix));
            System.out.println(matrix[4][16]);
            br.close();
    	}
     
    	public static void main(String[] args) throws IOException{
    		Map r = new Map();
    		r.importMap();
     
    	}
    }

    One last problem - the actual text file that will be used has two lines at the top, the name of the map and the number of pieces of gold it contains. How would I go about storing them in a variable and then ignoring the first two lines when creating the 2D array?

    Thanks!

  14. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Good job figuring all of that out. Good thing you went back and re-read the assignment.

    Process those 2 lines first, either while you're counting lines or separately using two readLine() statements.

    Here are some other points you might find interesting:

    - in your current code, COLUMNS is completely unnecessary. matrix can be initialized as:

    matrix = new char[ROWS][]; // yes, with a blank column size!

    - the statement:

    matrix[i++] = line.toCharArray();

    assigns the row that has been read to the designated matrix[] row, and it doesn't matter how long or how many columns it has.

  15. #15
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    I took your advice and removed the COLUMNS bit as it was causing me a few issues and your way of doing it was much better!

    I was wondering if you could help me out with a few things. I've moved on to the next stage of the assignment and I understand how to do nearly all of it, but I can't do the first bit so I can't progress.

    Here's what I need to do:
    1.Create a class Map that:
    Reads one of the sample ASCII-art map files (your code should be able to load any map written in the same format).
    Stores the map information in a 2D array (int[][] or char[][]).
     
    2.Create a class GameLogic that:
    Uses Map to load a map from file.
    Randomly positions a player within a map (on a non-wall space).

    I've done number 1 now, but don't understand the first bit of number 2. How do I use my Map class to load a map in the GameLogic class?

  16. #16
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    You just need to widen your thinking a bit. You can leave your main() method in Map - it's a useful for test - but now you'll create a new class GameLogic that acts on a Map instance. GameLogic's constructor will create an instance of Map and will then create a player somewhere in the map object's game space. I don't know if you're expected to create a Player class (wouldn't hurt) or another class with a main() method to create the GameLogic instance, but those are approaches you could take.

  17. #17
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Quote Originally Posted by GregBrannon View Post
    You just need to widen your thinking a bit. You can leave your main() method in Map - it's a useful for test - but now you'll create a new class GameLogic that acts on a Map instance. GameLogic's constructor will create an instance of Map and will then create a player somewhere in the map object's game space. I don't know if you're expected to create a Player class (wouldn't hurt) or another class with a main() method to create the GameLogic instance, but those are approaches you could take.
    I've managed to create an instance of the Map class in the GameLogic class and was just wondering if you could offer me some advice on implementing the player in the game. I'm not sure if the player should enter the array, because if the player entered the array it would overwrite whatever was in it before it so when the player moved off the spot in the game, it would be blank when it should be what it was before the player was there. So I was wondering the best way of implementing it?

    Thanks!

  18. #18
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Your thinking is very good, because you're thinking ahead, considering what might be happening next and how what you're doing now could complicate that. Reviewing what you were told to do, "Randomly position a player within a map (on a non-wall space)," I don't know if you can answer the questions you've asked. There isn't enough info given.

    If you did write a Player class, then a Player attribute would be its position in the game space, the x/y coordinate in the game. Printing the player instance's location in the game doesn't necessarily have to overwrite the existing game array. Yes, that would probably be easiest, but it's not the only way. A couple of options:

    1. The game array and an array of player locations could be separate and added together before printing. Kind of complicated, but easy for the computer.

    2. The player object could save the character it replaced when it was added to the game array. When the player moves, the location it is leaving would be filled with the saved character, the character in the location it is moving to would be saved, and then the player character would be placed in the new location. Less complicated than #1.

    I don't know the answers, but I'm impressed that you've asked the questions.

  19. #19
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Hi, I was wondering if you could help me with something else. I've done loads more since the last question and I've got a problem taking user input. I've got quite a few methods such as move, which allows the player to move around the board, pickup, which allows the player to collect gold, exit, to exit the game etc. I've set the methods up so that if the input matches a certain string, then what is in the method is carried out. So when I've been testing the move method my main has looked like this:
    		GameLogic g = new GameLogic();
    		g.positionPlayer();
    		while (true){
    			g.move(playerInput());

    What I can't work out how to do is have it so whatever the player enters is checked against all the methods to see if it matches the string in the exit, move, pickup method. How can I do this?

    Thanks!

  20. #20
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    I don't understand what you're asking. Can you give a couple examples? Show player input, how the matching logic works, what might happen as a result, then the details of what you're finding difficult.

  21. #21
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Here's the code:
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Random;
    import java.util.Scanner;
    import java.util.Scanner;
     
     
    public class GameLogic {
     
    	private int playerX;
    	private int playerY;
    	private int playerGOLD;
    	private char wall = '#';
    	private char gold = 'G';
    	private char exit = 'E';
    	private char floor = '.';
     
    	public GameLogic(){
    		Map theMap = new Map();
    		theMap.importMap();
    	}
     
    	public void positionPlayer(){
     
     
    		Random random = new Random();
    		int randomROW = random.nextInt(Map.theROWS);
    		int randomCOLUMN = random.nextInt(Map.theCOLUMNS);
     
    		if(Map.matrix[randomROW][randomCOLUMN] != wall){
    			playerX = randomROW;
    			playerY = randomCOLUMN;
    			System.out.println(playerX);
    			System.out.println(playerY);
    			System.out.println(Map.matrix[playerX][playerY]);
    			return;
    		}else{
    			positionPlayer();
    		}
     
    	}
     
    	public static String playerInput(){
    		Scanner input = new Scanner(System.in);
    		String answer = input.nextLine();
    		return answer;
    	}
     
    	public void hello(String answer){
    		if("HELLO".equals(answer)){
    			System.out.println("GOLD " + Map.theGOLD);
    		}
    	}
     
    	public void pickUp(String answer){
    		if("PICKUP".equals("answer")){
    			if(Map.matrix[playerX][playerY] == gold){
    				System.out.println(Map.matrix[playerX][playerY]);
    				playerGOLD += 1;
    				Map.matrix[playerX][playerY] = floor;
    				System.out.println("SUCCESS, GOLD COINS:" +  Map.theGOLD);
    				System.out.println(Map.matrix[playerX][playerY]);
     
    			}else{
    				System.out.println("FAIL");
    			}	
    		}
    	}
     
    	public void theExit(){
    		if(playerGOLD == Map.theGOLD & Map.matrix[playerX][playerY] == exit){
    			System.out.println("Congratulations you've won the game!");
    		}
    	}
     
    	public void look(String answer){
    		if("LOOK".equals(answer)){
    			System.out.println("LOOKREPLY");
    		}
    	}
     
    	public void move(String answer){			///need to remember to add SUCCESS but can't be bothered now.
    		if("MOVE W".equals(answer)){
    			if(Map.matrix[playerX][playerY - 1] != wall){
    				playerY -= 1;
    				System.out.println(Map.matrix[playerX][playerY]);
    			}else{
    				System.out.println("FAIL");
    			}
    		}else if("MOVE E".equals(answer)){
    			if(Map.matrix[playerX][playerY] != wall){
    				playerY += 1;
    				System.out.println(Map.matrix[playerX][playerY]);
    			}else{
    				System.out.println("FAIL");
    			}
    		}else if("MOVE S".equals(answer)){
    			if(Map.matrix[playerX + 1][playerY] != wall){
    				playerX += 1;
    				System.out.println(Map.matrix[playerX][playerY]);
    			}else{
    				System.out.println("FAIL");
    			}
    		}else if("MOVE N".equals(answer)){
    			if(Map.matrix[playerX - 1][playerY] != wall){
    				playerX -= 1;
    				System.out.println(Map.matrix[playerX][playerY]);
    			}else{
    				System.out.println("FAIL");
    			}
     
    		}
     
    		System.out.println(playerX + "," + playerY);
    	}
     
     
     
    	public static void main(String[] args) throws IOException{
    		Map r = new Map();
    		r.importMap();
    		for (int i=0; i<Map.theROWS; i++) {
    		     for (int j=0; j<Map.theCOLUMNS; j++)
    		         {
    		         System.out.print( Map.matrix[i][j]);
    		         System.out.print(" ");
    		         }
    		     System.out.println("");
    		     }
    		GameLogic g = new GameLogic();
    		g.positionPlayer();
    		while (true){
    			g.hello(playerInput());
     
    		}
    	}
    }

    Basically, as that code is currently set up, if I type in "HELLO" it will print back "GOLD 2" and that's because in the main i've got:

    g.hello(playerInput());

    But if I enter "MOVE N" nothing happens because I haven't got
    g.move(playerInput());
    in the main.

    What I want to be able to do is for the player to be able to enter HELLO or MOVE N or PICKUP or anything that's in one of the methods and the program to carry out the associated action.

  22. #22
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    I'll call that a command line parser that you will build to pre-process the user's input before sending it to the appropriate methods or taking other actions.

    Start by defining all user inputs by number of words and then the first words. For example 'QUIT' might be one of the single-word commands, and 'MOVE UP 1' might be 3-word command to move up a certain number of 'squares.' You can tell how many words have been entered by splitting the input to a String[] array and then using the length of the result.

    On paper, build a table of all possible user commands (or something similar), and the action that should be taken (call method xyz() with parameters 2 and 3, etc.) when the command is entered. Then write the logic to process the user input according to the logic table you've constructed. Include logic that lets the user know that an invalid command has been entered.

  23. #23
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    I'm confused about the use of the String[] array. It seems like an overly complex way to do it. There's very few possible commands and they are:
    HELLO
    MOVE N
    MOVE S
    MOVE E
    MOVE W
    PICKUP
    LOOK
    EXIT
    QUIT

    And I've already written all the logic to carry out the method. I'm just confused on how to link it.

  24. #24
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Okay, there are multiple ways.

    Get the player's input, and run it through a cascade of 'if' statements or a switch. Instead of actually taking the action in the body of the winning 'if', you could call the method that takes the action:
    if ( playerInput.equals( "LOOK" )
    {
        // or call the method look(), but the 'if' logic in the method
        // would not be required
        System.out.println( "LOOKREPLY" );
    }
    else if ( etc., etc., etc. )
    {
     
    {

  25. #25
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Read ASCII art map and store the information in 2D array (int[][] or char[][])

    Thanks I've got it working!

    One more question. I've got the grid printing like:
    # # # # # # # # # # # # # # # # # # # 
    # . . . . . . . . . . . . . . . . . # 
    # . . . . . . G . . . . . . . . E . # 
    # . . . . . . . . . . . . . . . . . # 
    # . . E . . . . . . . . . . . . . . # 
    # . . . . . . . . . . G . . . . . . # 
    # . . . . . . . . . . . . . . . . . # 
    # . . . . . . . . . . . . . . . . . # 
    # # # # # # # # # # # # # # # # # # #

    and I need to be able to see the player on the grid by putting a "p" wherever they're standing. However, it needs to be able to return to what it was originally when the player leaves that coordinate. What's the best way to do this? I've tried to somehow print the character "p" over the coordinate in the array without overwriting it but I haven't had any success.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 3
    Last Post: March 23rd, 2013, 07:20 PM
  2. Get int value from char, char pulled from String
    By Andrew Red in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 4th, 2013, 10:04 AM
  3. How to store char variable in an array
    By ashboi in forum Java Theory & Questions
    Replies: 1
    Last Post: November 9th, 2012, 12:48 PM
  4. Read in file and store in 2D array start of The Game of Life
    By shipwills in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 2nd, 2011, 09:52 AM
  5. Read A File and Store Values into a 2-Dimensional Integer Array?
    By Kimimaru in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 9th, 2011, 09:13 PM