Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (475)
Games in Android Showcase (106)
games submitted by our members
Games in WIP (530)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Displaying a Tile Map help needed  (Read 3760 times)
0 Members and 1 Guest are viewing this topic.
Offline Jhost

Senior Newbie





« Posted 2012-02-14 02:23:06 »

Hello,
I will be hard-coding a map into my code like so:
1  
2  
3  
4  
5  
6  
7  
8  
private char[][] tiles = new char[][] {
        {'x','x','x','x'},
        {'x','.','.','x'},
        {'x','.','.','x'},
        {'x','.','.','x'},
        {'x','.','.','x'},
        {'x','x','x','x'},
    };

I am going to make a 2D top down view (Like Link to the Past) with 16x16 tiles that I created. How can I display this and how can I have multiple areas i.e. a room?
Thanks,
Jhost
Offline UprightPath
« Reply #1 - Posted 2012-02-14 03:02:20 »

Several ways. The most basic way is to have a loop that iterates through your tile array. Inside have something that figures out what type of tile should be painted, then... Paint it.

As for several tile maps? Well, you'd have an event trigger when your player moves off the current map, that switches the current map for the new one.

Offline Jhost

Senior Newbie





« Reply #2 - Posted 2012-02-14 03:11:01 »

Thanks. Would LWJGL be worthwhile using for this game?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline elamre

JGO Coder


Medals: 17
Projects: 1


hitar!


« Reply #3 - Posted 2012-02-14 06:27:08 »

I have written 2 nice classes for this. One which will read external maps (thanks to jgo for this one though!), and one who will create an image from a 2d array.
For different levels i do the following:
Create 3 different external map objects for 3 levels. Have 1 background image. Now as soon as the game starts, youll give your background image the value of an external 2d array, this array is external mab object level 1. As soon as you finish a level, you go give it the value of the second external 2d value. Etc etc etc.
Ill upload it once im on uni today, i think it suits all your needs! Wink

My projects:
Tower Defence!]http://www.java-gaming.org/topics/iconified/25690/view.html]Tower Defence! [lll.......] 30%!
Lightsnakerider! [llllll....] 60%!
Offline theagentd
« Reply #4 - Posted 2012-02-14 10:48:17 »

Hello,
I will be hard-coding a map into my code like so:
1  
2  
3  
4  
5  
6  
7  
8  
private char[][] tiles = new char[][] {
        {'x','x','x','x'},
        {'x','.','.','x'},
        {'x','.','.','x'},
        {'x','.','.','x'},
        {'x','.','.','x'},
        {'x','x','x','x'},
    };

I am going to make a 2D top down view (Like Link to the Past) with 16x16 tiles that I created. How can I display this and how can I have multiple areas i.e. a room?
Thanks,
Jhost
Java2D works fine for a map that small, and probably for anything larger too (depending on the tile size though). There are however some things that are potentially VERY expensive with Java2D. For example, scaling, rotating and transparency are very slow and should be avoided. If you will not be using those then you'll have no problem with just Java2D.

Myomyomyo.
Offline Beamery

Senior Newbie


Medals: 1



« Reply #5 - Posted 2012-02-14 15:29:36 »

Like elamre said, it might be easier to store the map in an external map file and then make a simple parser to interpret the file, if only for readability's sake.  Initializing a 2D array with all the tiles could get pretty messy once you have a large map.
Offline elamre

JGO Coder


Medals: 17
Projects: 1


hitar!


« Reply #6 - Posted 2012-02-14 18:18:13 »

Ok i dont know how much experience you have with programming, so ill just explain it basically. If anything is unclear to you, please say so!

Im using the following class to get data from an text file, and return it as a 2d array:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;

public class MapToArray {

    private final String filename;
   
    //Simple constcructor. Taking the name of your map as argument ( in String) for example: MapToArray("level1.txt")
   MapToArray(String filename) {
        this.filename = filename;
    }

    //This function will return the 2d array of the map, in INT[][]
   public int[][] getArray() throws IOException {
        ArrayList<String> array = new ArrayList<String>();

        int length = getLength();
        int height = getHeigth();
       
        LineNumberReader reader = new LineNumberReader(new FileReader(filename));
        for (int i = 0; i < height; i++) {
            array.add(reader.readLine());
        }

        if (array.size() == 0) {
            System.out.println("Empty map");
        }
        int[][] numbers = new int[length][height];

        int r = 0;
        //Now that we have decided the size of our 2d array, we will fill it in
       for (String s : array) {
            toArray(s, r, numbers);
            r++;
        }

        return numbers;
    }

   
    //Since an array is static, we must find its boundaries. This function will return the amount of characters in the map.
   private int getLength() throws IOException {
        int countChar = 0;
        try {
            LineNumberReader reader = new LineNumberReader(new FileReader(filename));
            String lineRead = reader.readLine();
            int length = 0;
            while (countChar < lineRead.length()) {
                if (!(lineRead.charAt(countChar) == ',')) {
                    length++;
                }
                countChar++;
            }
            reader.close();
            return length;
        } catch (IOException e) {
            throw e;
        }
    }

    //This will return the height of the map (the amount of lines)
   private int getHeigth() throws IOException {
        try {
            LineNumberReader reader = new LineNumberReader(new FileReader(filename));
            @SuppressWarnings("unused")
         String lineRead;
            while ((lineRead = reader.readLine()) != null) {
            }
            int height = reader.getLineNumber();
            reader.close();
            return height;
        } catch (IOException e) {
            throw e;
        }
    }

    //This function will fill an entire row with the numbers from String s.
   private void toArray(String s, int row, int[][] numbers) {
        String match = ",";
        String[] veld = s.split(match);
       
        for(int i = 0; i<veld.length;i++)
           veld[i] = veld[i].replaceAll(" ","");
       
        for (int i = 0; i < veld.length; i++) {
            try {
                numbers[i][row] = Integer.parseInt(veld[i]);
            } catch (NumberFormatException e) {
                System.out.println("Not a valid map!");
            }
        }
    }
}


Ok so now we have a class which will take the map location as input, and returns the 2d array as output. Note this is NOT necessary, but it makes everything a lot easier to manage, reuse and saves up precious source code space.

so this is how we can use it:
1  
2  
3  
int[][] array_map1;
MapToArray map1 = new mapToArray("level 1.dat");
array_map1 = map1.getArray();

where level1.dat contains the following:
1  
2  
3  
4  
5  
1,1,1,1,1,
1,0,0,0,1,
1,0,2,0,1,
1,0,0,0,1,
1,1,1,1,1,

Where 1 are the walls, 2 is a table for example. Now you have the array, whats next?
You want to draw everything on the screen. For this im not quite sure what you exactly need at this point. A class which loads the images of a tilesheet? ill just give you a simplefied version of my code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
package nl.elmar.grafics;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import nl.elmar.items.Coin;
import nl.elmar.items.Key;
import nl.elmar.items.Sword;
import nl.elmar.other.Common;



public class ArrayToGraf {
   
   Image image;
   //ignore this part
  Sprite sprite = new Sprite("terrainSheet.png", 1, 15, false);
   int x,y,temp=0;
   //nothing here yet
  public ArrayToGraf(){
   }
   //This function will return an BufferedImage with all the tiles drawn on it
  public BufferedImage getMap(int[][] map){
      BufferedImage bufferedImage = new BufferedImage(map.length*4, (map[0].length)*15, BufferedImage.TYPE_INT_BGR);
      Graphics2D g2d = bufferedImage.createGraphics();
      g2d.setColor(Color.green);
      g2d.fillRect(0, 0, map.length*4, (map[0].length)*15);
     
      for(int heigth = 0; heigth<map[0].length; heigth++){
         for(int length = 0; length<map.length; length++){
            x=0;
            temp = map[length][heigth];
            while(temp>=10){
               x++;
               temp-=10;
            }
            y=temp;
            g2d.drawImage(sprite.getImage(x, y), length*15, heigth*15, null);
         }
      }
      g2d.finalize();
      g2d.dispose();
      return bufferedImage;
   }
}

Now my code is probably using methods which you dont have. Im using a sprite sheet, which is much easier for me.
How you can do it, with the map i gave as example, is:
1  
2  
3  
4  
//Add the following 2 lines as variables in your class
private Image wall = Toolkit.getDefaultToolkit().getImage("Map/Wall.png");
 private Image table = Toolkit.getDefaultToolkit().getImage("Map/Table.png");
 private Image floor = Toolkit.getDefaultToolkit().getImage("Map/Floor.png");

Now the computer knows what a wall looks like, and what a table looks like. But he doesnt know where to place them. So we change the for loop given in my previous class.
change this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
         for(int length = 0; length<map.length; length++){
            x=0;
            temp = map[length][heigth];
            while(temp>=10){
               x++;
               temp-=10;
            }
            y=temp;
            g2d.drawImage(sprite.getImage(x, y), length*15, heigth*15, null);
         }

to this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
         for(int length = 0; length<map.length; length++)
                                      switch(map[length][heigth]){
            case 0:
               g2d.drawImage(floor, length*15, heigth*15, null);
                                                        break;
            case 1:
               g2d.drawImage(wall, length*15, heigth*15, null);
               break;
            case 2:
               g2d.drawImage(table, length*15, heigth*15, null);
               break;
            }
                                   }


Why *15? you would ask. Well this is the size of each tile of yours. Im using 15 myself, but change to your liking!
So how to totally implement it?
This is how i have done it:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
..... your main drawing class here...
int[][] array_map1;
MapToArray map1;
Image bckground_1;
ArrayToGraf draw = new ArrayToGraf();
Constructor(){

map1 = new mapToArray("level 1.dat");
array_map1 = map1.getArray();
bckground_1 = draw.getMap(array_map1.getArray());
}

Yes this could be smaller:
1  
background = draw.getMap(map1.getArray(), objects1.getArray());

Now all you have to do is draw your image, its as simple as that! Smiley

Any problems ? ask me!

dont forget to give me a medal for my hard work of explaining! Cheesy

My projects:
Tower Defence!]http://www.java-gaming.org/topics/iconified/25690/view.html]Tower Defence! [lll.......] 30%!
Lightsnakerider! [llllll....] 60%!
Offline Jhost

Senior Newbie





« Reply #7 - Posted 2012-02-15 01:38:41 »

Thanks a bunch man, I loved the explaining it helps rather than just giving out code! Just one more question, what do you mean by draw it? I'm sorry but I'm a bit of a noob in Java Game Development. There's a medal for you  Wink . I was wondering if you would add me in skype? PM me for it and thanks again.
Offline UprightPath
« Reply #8 - Posted 2012-02-15 01:42:35 »

Thanks a bunch man, I loved the explaining it helps rather than just giving out code! Just one more question, what do you mean by draw it? I'm sorry but I'm a bit of a noob in Java Game Development. If I could give you rep I would  Wink . I was wondering if you would add me in skype? PM me for it and thanks again.

That's what the 'appreciate' button is for. :3

However, by draw he means you have to draw the image to the screen. Mr. Kevglass of this site has a rather helpful explanation of how to do that here: http://cokeandcode.com/index.html?page=tutorials/spaceinvaders101

Offline Jhost

Senior Newbie





« Reply #9 - Posted 2012-02-15 01:47:19 »

Just out of question, as I have found a rather interesting MapEditor ( http://sites.google.com/site/juddman/ )that saves as text files, would this be useful and could I use the code to convert this to a 2D array?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline elamre

JGO Coder


Medals: 17
Projects: 1


hitar!


« Reply #10 - Posted 2012-02-15 17:17:48 »

No problems at all, i find that doing both is the most effective. Sometimes people just give explanation, without a sample code. This is really frustrating if you are still not able to finish it. And only code doesnt help anybody either.
Im glad that i finally could help somebody, instead of just asking help on the forums and profit from it (which really isnt my intention btw).
Sure pm is on its way. It only seems that our timezones are totally different (as in, your day starts when im asleep, and when im posting you seem to be asleep :p ).

And yes you could basicly use everything. Youll just have to find an algorithm to convert the array to the map.
You could also use Tiled, with some modifications to the array to image code. The Text to 2dArray should suit for almost everything, and shouldnt require a lot of changes for use with other programs like the one you listed. Btw did you succeed in drawing it? otherwise check these small tutorials out:
http://zetcode.com/tutorials/javagamestutorial/
I loved those, and that is what i started with.

Also uprightPath, why are they using a singleton? isnt it just much easier to make a static class with static variable? does the same thing, but then easier (and better, according to our java teacher at uni)

My projects:
Tower Defence!]http://www.java-gaming.org/topics/iconified/25690/view.html]Tower Defence! [lll.......] 30%!
Lightsnakerider! [llllll....] 60%!
Offline Jhost

Senior Newbie





« Reply #11 - Posted 2012-02-16 00:39:12 »

I added you on skype. Maybe we could work together on a game. I really think you would be good at making videos on making a java 2d game like the one I have described here from scratch. I know I would watch them!
Offline v0rtex

Senior Newbie





« Reply #12 - Posted 2012-02-19 20:29:24 »

+ rep elamre. Really awesome tutorial. Thanks for your help and the tutorial!
Offline elamre

JGO Coder


Medals: 17
Projects: 1


hitar!


« Reply #13 - Posted 2012-02-19 20:32:00 »

Thanks im working on a more detailed tutorial, with better code Smiley

My projects:
Tower Defence!]http://www.java-gaming.org/topics/iconified/25690/view.html]Tower Defence! [lll.......] 30%!
Lightsnakerider! [llllll....] 60%!
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

pw (11 views)
2014-07-24 01:59:36

Riven (9 views)
2014-07-23 21:16:32

Riven (11 views)
2014-07-23 21:07:15

Riven (12 views)
2014-07-23 20:56:16

ctomni231 (42 views)
2014-07-18 06:55:21

Zero Volt (38 views)
2014-07-17 23:47:54

danieldean (32 views)
2014-07-17 23:41:23

MustardPeter (34 views)
2014-07-16 23:30:00

Cero (49 views)
2014-07-16 00:42:17

Riven (50 views)
2014-07-14 18:02:53
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!