2
\$\begingroup\$

So I just learned the basics of Java and was ready to try to create a protoype game in the style of Civ. So a tile&turn based game.

I created an enum for the different tiles:

public enum TerrainTile{

 WATER(1), GRASSLAND(1), HILL(2), FORREST(2), BLANK(99);

private final int id;
private final int moveCost;
private boolean hidden = true;


private TerrainTile(int moveCost) {
    this.id = this.ordinal();
    this.moveCost = moveCost;
}

I made a JFrame:

public class MainFrame extends JFrame {

private MapPanel pnlMap;

public MainFrame(Terrain map) {

    setTitle("MyGame");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    getContentPane().setPreferredSize(new Dimension(500, 500));

    pnlMap = new MapPanel(map);
    pnlMap.setPreferredSize(new Dimension(500, 500));
    add(pnlMap);

    pack();
    setLocationRelativeTo(null);

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {

            BufferedImage mapImg = null;
            try {
                mapImg = ImageIO.read(MainFrame.class.getClassLoader().getResourceAsStream("frames/resources/map2.png"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Terrain map = new Terrain(mapImg);
            System.out.println("Terrain created:");
            map.printTerrain();


            JFrame frame = new MainFrame(map);
            frame.setVisible(true); 

        }       

And a JPanel for the map:

public class MapPanel extends JPanel {

private final Terrain map;

public MapPanel(Terrain map) {
    this.map = map;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

}

when I wasn't sure where to save the textures for the tiles. Should I just read out the array of the map and do a switch statement to define inside the MapPanel class which texture to draw or should the textures better be implemented inside the enum?

\$\endgroup\$
2
\$\begingroup\$

Take a look at this.
It's common to have a single image for all your tiles and draw a different part of it at rendering.
You can then draw your tiles like this :

int mx = tileId % numberOfTileCols;
int my = tileId / numberOfTileRows;

graphics.drawImage(image, x, y,
    x + tileWidth, y + tileHeight, 
    mx * tileWidth, 
    my * tileHeight,
    mx * tileWidth + tileWidth,
    my * tileHeight + tileHeight, this);

This way you can store a single texture in the MapPanel but get rid of the huge switch statement.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.