0
votes

I'd like to make it so that my code generates a cave system in a game. I'm having trouble with the code; it seems that it makes meshes in the parts inbetween the caves and I don't want a mesh, I want an open area. Here is my code:

package CATest;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CATest extends JPanel{
    static CATest w;
    static Random rand=new Random();
    JFrame jf=new JFrame();
    boolean tileMap[][];
    public static void main(String argsp[]){
        w=new CATest();
        w.jf.add(w);
        w.jf.setSize(100,400);
        w.jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        w.jf.setVisible(true);
        w.tileMap=new boolean[100][400];
        for(int x=0;x<w.tileMap.length;x++)
            for(int y=0;y<w.tileMap[0].length;y++)
                if(rand.nextFloat()<0.7)
                    w.tileMap[x][y]=true;
        for(int step=0;step<7;step++){
            boolean newMap[][]=new boolean[100][400];
            for(int x=0;x<w.tileMap.length;x++)
                for(int y=0;y<w.tileMap[0].length;y++){
                    int count=0;
                    if(x-1>=0&&y-1>=0&&x+1<w.tileMap.length&&y+1<w.tileMap[0].length){
                        if(w.tileMap[x-1][y])
                            count++;
                        if(w.tileMap[x+1][y])
                            count++;
                        if(w.tileMap[x][y-1])
                            count++;
                        if(w.tileMap[x][y+1])
                            count++;
                        newMap[x][y]=count<=3;
                    }
                }
            w.tileMap=newMap;
        }
        w.repaint();
    }
    @Override
    public void paintComponent(Graphics g){
        for(int x=0;x<tileMap.length;x++)
            for(int y=0;y<tileMap[0].length;y++){
                if(tileMap[x][y])
                    g.setColor(Color.black);
                else g.setColor(Color.white);
                g.drawRect(x,y,1,1);
            }
    }
}

Here's a picture of what happens:cellular automata As you can see, there is a mesh where there should be a cave. Please, help.

1

1 Answers

0
votes

I omitted the fact that the center tile needed to be accounted for. So instead of

if(w.tileMap[x-1][y])
    count++;
if(w.tileMap[x+1][y])
    count++;
if(w.tileMap[x][y-1])
    count++;
if(w.tileMap[x][y+1])
    count++;

it should be

if(w.tileMap[x][y])
    count++;
if(w.tileMap[x-1][y])
    count++;
if(w.tileMap[x+1][y])
    count++;
if(w.tileMap[x][y-1])
    count++;
if(w.tileMap[x][y+1])
    count++;