Rasterizing a Triangle in Java using 2D array - java

I am creating a 3D renderer in Java but I have a problem when trying to render the polygons with a solid color fill. It works perfectly fine but every so often it's tearing but I'm not sure whether it is because the algorithm is inefficient or if it's something else because it's only at the vertices's it is tearing. Here is a picture:
Wireframe:
You can see that near the vertices's or rather points of the polygons it tears. I'm storing the color of the pixels in a 2 dimensional array and then cycling through it and rendering them. It still tears even when I make the polygon's really small so I don't think it's a performance problem. I use the Bresham algorithm and store the pixels in a 2 dimensional array then in the polygon I get the pixels and make them into one big array which I cycle through down the y and then across the x until I hit a pixel. That is set as beginLine and then the last one is set as endLine. I then draw a line between the points.
public void render()
{
int tempPixels[][] = new int[(int) Math.max(vertex_1.getX(), Math.max(vertex_2.getX(), vertex_3.getX())) + 30][(int) Math.max(vertex_1.getY(), Math.max(vertex_2.getY(), vertex_3.getY())) + 30];
for (int x = 0; x < vector_1.getWidth(); x++)
{
for (int y = 0; y < vector_1.getHeight(); y++)
{
if (vector_1.getPixels()[x][y] == 1)
{
tempPixels[(int) (x + Math.min(vertex_1.getX(), vertex_2.getX()))][(int) (y + Math.min(vertex_1.getY(), vertex_2.getY()))] = 1;
}
}
}
for (int x = 0; x < vector_2.getWidth(); x++)
{
for (int y = 0; y < vector_2.getHeight(); y++)
{
if (vector_2.getPixels()[x][y] == 1)
{
tempPixels[(int) (x + Math.min(vertex_2.getX(), vertex_3.getX()))][(int) (y + Math.min(vertex_2.getY(), vertex_3.getY()))] = 1;
}
}
}
for (int x = 0; x < vector_3.getWidth(); x++)
{
for (int y = 0; y < vector_3.getHeight(); y++)
{
if (vector_3.getPixels()[x][y] == 1)
{
tempPixels[(int) (x + Math.min(vertex_3.getX(), vertex_1.getX()))][(int) (y + Math.min(vertex_3.getY(), vertex_1.getY()))] = 1;
}
}
}
for (int y = 0; y < (int) Math.max(vertex_1.getY(), Math.max(vertex_2.getY(), vertex_3.getY())) + 4; y++)
{
int beginLine = -1;
int endLine = -1;
for (int x = 0; x < (int) Math.max(vertex_1.getX(), Math.max(vertex_2.getX(), vertex_3.getX())) + 4; x++)
{
if (tempPixels[x][y] == 1)
{
if (beginLine == -1)
{
beginLine = x;
}
else
{
endLine = x;
}
}
}
for (int i = beginLine; i < endLine; i++)
{
pixels[i][y] = 1;
colors[i][y] = Color.PINK;
}
}
vector_1.render();
vector_2.render();
vector_3.render();
vertex_1.render();
vertex_2.render();
vertex_3.render();
}
So basically my questions are:
Is this algorithm inefficient, if so what would be a better way?
Why is it tearing near the vertices's only?

Out of the problem description one cannot conclude that the attached image does not show what you want. Technically, the pink zone could depict a set of triangles you have 'correctly' painted (i.e. exactly the way you intended to) :p You could mark the triangles that you intended to be in the image, as an update. I suspect there are 4 triangles, though there are more such possible combinations.
First of all, since the part that, for each y, determines the beginLine and endLine seems to be correct, you should probably iterate till endLine when drawing the associated vertical segment (and not till endLine-1).
But that is probably not the real problem. Try drawing one triangle at a time. If some triangles still render incorrectly also try to see what happens when you eliminate the last part (the one rendering the vectors and the vertices). Why this?! Considering your implementation, you expect just a segment on each y. The image you provided indicates that your implementation sometimes renders more than one segment. So the rendering of the vectors and the vertices might be incorrect, though rendering multiple 'not perfectly aligned' triangles could also cause it.
If this does not solve it either, there might be some small offset in between your triangles. Try to see why that is.
Related to efficiency, that is not at fault. Generally, efficiency and correctness are not related in this way.
EDIT
You should add endLine = x after beginLine = x. With your implementation if you only have one pixel on a vertical line you do not draw it (since endLine will stay -1). This is one way to correct this issue. Also check that beginLine is greater than -1 before starting drawing. And do not forget to iterate from beginLine to exactly endLine.

You can use the method fillPolygon.
Syntax
g.setColor(Color.*color you want*)
g.fillPolygon (new int[]{width Dimensions}, new int [] {Height Dimensions}, no. of co-ordinates);
Note: - The 1st Value is of right Co-Ordinate, 2nd is of mid point and the 3rd is of Left Co-Ordinate.
The final programming with class, variables and methods.
/*Import the following files: -*/
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;
import java.awt.Font;
public class Shapes extends JPanel
{
public Shapes()
{
this.addComponentListener(new ComponentListener(){
public void componentShown(ComponentEvent arg0) {
}
public void componentResized(ComponentEvent arg0) {
paintComponent(getGraphics());
}
public void componentMoved(ComponentEvent arg0) {
}
public void componentHidden(ComponentEvent arg0) {
// TODO Auto-generated method stub
}
});
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.MAGENTA);
g.setColor(Color.BLUE);
g.fillPolygon (new int[]{250,135,10}, new int [] {160,15,160}, 3);
g.setFont(new Font("TimesRoman", Font.PLAIN, 35));
g.setColor(Color.GREEN);
g.drawString("Triangle", 75, 120);
}
public static void main(String[] args)
{
Shapes obj = new Shapes();
JFrame frame = new JFrame("Shapes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(obj);
frame.setSize(600, 500);
frame.setVisible(true);
}
}

Related

Problem with Scan-Line Polygon Filling algorithm in java

(please don't mark this question as not clear, I spent a lot of time posting it ;) )
Okay, I am trying to make a simple 2d java game engine as a learning project, and part of it is rendering a filled polygon as a feature.
I am creating this algorithm my self, and I really can't figure out what I am doing wrong.
My though process is something like so:
Loop through every line, get the number of points in that line, then get the X location of every point in that line,
Then loop through the line again this time checking if the x in the loop is inside one of the lines in the points array, if so, draw it.
Disclaimer: the Polygon class is another type of mesh, and its draw method returns an int array with lines drawn through each vertex.
Disclaimer 2: I've tried other people's solutions but none really helped me and none really explained it properly (which is not the point in a learning project).
The draw methods are called one per frame.
FilledPolygon:
#Override
public int[] draw() {
int[] pixels = new Polygon(verts).draw();
int[] filled = new int[width * height];
for (int y = 0; y < height; y++) {
int count = 0;
for (int x = 0; x < width; x++) {
if (pixels[x + y * width] == 0xffffffff) {
count++;
}
}
int[] points = new int[count];
int current = 0;
for (int x = 0; x < width; x++) {
if (pixels[x + y * width] == 0xffffffff) {
points[current] = x;
current++;
}
}
if (count >= 2) {
int num = count;
if (count % 2 != 0)
num--;
for (int i = 0; i < num; i += 2) {
for (int x = points[i]; x < points[i+1]; x++) {
filled[x + y * width] = 0xffffffff;
}
}
}
}
return filled;
}
The Polygon class simply uses Bresenham's line algorithm and has nothing to do with the problem.
The game class:
#Override
public void load() {
obj = new EngineObject();
obj.addComponent(new MeshRenderer(new FilledPolygon(new int[][] {
{0,0},
{60, 0},
{0, 60},
{80, 50}
})));
((MeshRenderer)(obj.getComponent(MeshRenderer.class))).color = CYAN;
obj.transform.position.Y = 100;
}
The expected result is to get this shape filled up.(it was created using the polygon mesh):
The actual result of using the FilledPolygon mesh:
You code seems to have several problems and I will not focus on that.
Your approach based on drawing the outline then filling the "inside" runs cannot work in the general case because the outlines join at the vertices and intersections, and the alternation outside-edge-inside-edge-outside is broken, in an unrecoverable way (you can't know which segment to fill by just looking at a row).
You'd better use a standard polygon filling algorithm. You will find many descriptions on the Web.
For a simple but somewhat inefficient solution, work as follows:
process all lines between the minimum and maximum ordinates; let Y be the current ordinate;
loop on the edges;
assign every vertex a positive or negative sign if y ≥ Y or y < Y (mind the asymmetry !);
whenever the endpoints of an edge have a different sign, compute the intersection between the edge and the line;
you will get an even number of intersections; sort them horizontally;
draw between every other point.
You can get a more efficient solution by keeping a trace of which edges cross the current line, in a so-called "active list". Check the algorithms known as "scanline fill".
Note that you imply that pixels[] has the same width*height size as filled[]. Based on the mangled output, I would say that they are just not the same.
Otherwise if you just want to fill a scanline (assuming everything is convex), that code is overcomplicated, simply look for the endpoints and loop between them:
public int[] draw() {
int[] pixels = new Polygon(verts).draw();
int[] filled = new int[width * height];
for (int y = 0; y < height; y++) {
int left = -1;
for (int x = 0; x < width; x++) {
if (pixels[x + y * width] == 0xffffffff) {
left = x;
break;
}
}
if (left >= 0) {
int right = left;
for (int x = width - 1; x > left; x--) {
if (pixels[x + y * width] == 0xffffffff) {
right = x;
break;
}
}
for (int x = left; x <= right; x++) {
filled[x + y * width] = 0xffffffff;
}
}
}
return filled;
}
However this kind of approach relies on having the entire polygon in the view, which may not always be the case in real life.

Matrixes and for loops becoming inconsistent?

This is a follow-up post to my previous question, here. I got a remarkable response to instead of using array data tracking, to use matrixes. Now, the code here works just as planned (as in, the rectangles somewhat most of the time get filled in properly with white), but it's very inconsistent. When holding the left or right mouse button the colors phase over each other in a battle of randomness, and I don't know nearly that much about why this is happening. Just for reference, I'm using Java in Processing 3.
This is a result that I made with the project. As you can see, it looks fine.
Except for that jitter when hovering over a rect, and that more than not the rectangles are not being filled in half the time. And plus, the hover color is cycling almost randomly.
int cols, rows;
int scl = 20;
boolean[][] matrix = new boolean[scl+1][scl+1];
void setup() {
size(400, 400);
int w = 400;
int h = 400;
cols = w / scl;
rows = h / scl;
}
void draw() {
background(255);
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
int xpos = x*scl;
int ypos = y*scl;
stroke(55);
if ((mouseX >= xpos && mouseX <= xpos+scl) &&
(mouseY >= ypos && mouseY <= ypos+scl)) {
fill(75);
if (mousePressed == true) {
println("Clicked at: " + xpos + " and " + ypos);
if (!matrix[xpos/scl][ypos/scl]) {
matrix[xpos/scl][ypos/scl] = true;
} else {
matrix[xpos/scl][ypos/scl] = false;
}
fill(100);
//here is the desired location for the fill to remain constant even
//after unclicking and leaving hover
}
println("Mouse at: " + xpos + " and " + ypos);
} else {
fill(50);
}
if (matrix[x][y]) {
//fill(204, 102, 0);
fill(240);
rect(xpos, ypos, scl, scl);
}
rect(xpos, ypos, scl, scl);
}
}
}
Remeber that Processing fires the draw() function 60 times per second.
So your check for whether the mouse is pressed is happening 60 times per second. That means you're toggling the state of whatever cell the mouse is in 60 times per second.
To fix that problem, you might switch to using the event functions like mousePressed() instead of constantly polling every frame.
From the reference:
int value = 0;
void draw() {
fill(value);
rect(25, 25, 50, 50);
}
void mousePressed() {
if (value == 0) {
value = 255;
} else {
value = 0;
}
}
As for certain cells being skipped over, that's because when you move the mouse, it doesn't actually go through every pixel. It "jumps" from frame to frame. Those jumps are usually small enough that humans don't notice it, but they're large enough that it's skipping over cells.
One solution to this is to use the pmouseX and pmouseY variables to calculate a line from the previous mouse position to the current mouse position, and fill in any cells that would have been hit along the way.

Java Game of Life using Swing

I am trying to make a replica of the Game of Life using swing, I admit i have used code from some 1 else as i am trying to get my head around it and then proceed with my own implementation. I have some understanding of their code, yet i wanted to implements 2 additional features to their code. However i am finding that the way it is written is posing problems as i wanted to add a MouseListener(To make a cell come to life when clicked) and WindowListener(To make a start,pause and resume button).
I do understand how they work to some extent, yet i need your help to get my headaround it.
Here is the code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.Transient;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
#SuppressWarnings("serial")
public class ConwaysGameOfLife extends JPanel implements MouseListener{
private int[][] cellsGrid; // grid is the size of the 2d array
private static final Random rnd = new Random(); // make a new random generator
private int generationCounter; // counter for the generation
public ConwaysGameOfLife(int width, int height) {
this.cellsGrid = new int[width / 4][height / 4];// divides by 4 whatever the width and height set is
setupGrid();
}// new method for creating the game with input sizes for the size of the game window
/*The grid consists fully of cells, the grid size is divided by 4 to make the cells
* setupGrid makes the grid of cells
*
* */
private void setupGrid() {
for (int[] row : cellsGrid) {
for (int j = 0; j < row.length; j++) {
if (rnd.nextDouble() < 0.92)
continue;
row[j] = rnd.nextInt(2);
//
}
}
}
/*
* applies the rule to the existing cells changing their state depending on the position to neighbors set in the rules
* */
public void updateGrid() {
for (int i = 0; i < cellsGrid.length; i++) {
for (int j = 0; j < cellsGrid[i].length; j++) {
applyRule(i, j);
}
}
}
// Rules of game of life cells iterations
private void applyRule(int i, int j) {
int left = 0, right = 0, up = 0, down = 0;
int dUpperLeft = 0, dUpperRight = 0, dLowerLeft = 0, dLowerRight = 0;
//this shows the 8 possible neighbors in terms of position
if (j < cellsGrid.length - 1) {
right = cellsGrid[i][j + 1];
if(i>0)
dUpperRight = cellsGrid[i - 1][j + 1];
if (i < cellsGrid.length - 1)
dLowerRight = cellsGrid[i + 1][j + 1];
}
if (j > 0) {
left = cellsGrid[i][j - 1];
if (i > 0)
dUpperLeft = cellsGrid[i - 1][j - 1];
if (i< cellsGrid.length-1)
dLowerLeft = cellsGrid[i + 1][j - 1];
}
if (i > 0)
up = cellsGrid[i - 1][j];
if (i < cellsGrid.length - 1)
down = cellsGrid[i + 1][j];
int sum = left + right + up + down + dUpperLeft + dUpperRight
+ dLowerLeft
+ dLowerRight;
if (cellsGrid[i][j] == 1) {
if (sum < 2)
cellsGrid[i][j] = 0;
if (sum > 3)
cellsGrid[i][j] = 0;
}
else {
if (sum == 3)
cellsGrid[i][j] = 1;
}
}
#Override
#Transient
public Dimension getPreferredSize() {
return new Dimension(cellsGrid.length * 4, cellsGrid[0].length * 4);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Color gColor = g.getColor();
g.drawString("Generation: " + generationCounter++, 0, 10);
for (int i = 0; i < cellsGrid.length; i++) {
for (int j = 0; j < cellsGrid[i].length; j++) {
if (cellsGrid[i][j] == 1) {
g.setColor(Color.black); // change colour
g.fillRect(j * 8, i * 8, 8, 8); // change size of cells
}
}
}
g.setColor(gColor);
//paint the cells to a colour
}
public static void main(String[] args) {
final ConwaysGameOfLife c = new ConwaysGameOfLife(800, 800);
JFrame frame = new JFrame();
frame.getContentPane().add(c);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
JButton start=new JButton("START");
/* This method specifies the location and size
* of button. In method setBounds(x, y, width, height)
* x,y) are cordinates from the top left
* corner and remaining two arguments are the width
* and height of the button.
*/
start.setBounds(80,0,80,20);
//Adding button onto the frame
//frame.add(start);
new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.add(start);
c.updateGrid();
c.repaint();
}
}).start();
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
First of all, The button flickers, and only appears when hovered over with the mouse, still flickering. Then i want the iterations to begin after start button is pressed, and pause button to pause it, and resume(Have a decent idea how it would work, but not how to implement it with the structure of swing that is done in this code.)
Secondly, I wanted the cells to come to life when they are pressed with the mouse, But, i am unsure how to implement the mouseListener to do this.
I tried something like cellsGrid[i][j] = 1; when clicked by mouse but i get errors, which is due to my lack of understanding of the implementation of cellsGrid.
I am not expecting solutions to the problem, I would like some guidance to understand the Listeners better and maybe how to make this simpler to understand for me. Thank You :)
Your simulation has a model that is a grid of cells; it has a view that paints an 8 x 8 square to represent a cell in the grid. As suggested here, you can map model and view coordinates using linear interpolation. In particular, given the following proportions, you can cross-multiply and solve for the missing coordinate.
view.x : panelWidthInPixels :: model.x : modelXRange
view.y : panelHeightInPixels :: model.y : modelYRange
For reference, this complete example maps mouse coordinates to pixel coordinates in an image. A complete example of John Conway’s Game of Life in Java Swing is cited here.

Using nested for loops to add to multidimensional array

Ok so i am creating a Breakout game and i need to create a method that creates rectangle objects for each of the bricks so i can implement hit detection, i already have a method so the bricks can be drawn out like this:
public void drawBricks(Graphics g)
{
g.setColor(brickColor);
for(int i = 0; i<10; i++)
{
for(int a = 0; a<121; a+=30)
{
g.fillRect(x+(width*i)+(spacer*i), y +a, width, height);
// spacer = 10, x and y = 5, width = 50, height = 20, if you need this...
}
}
}
Now to the part I cant figure out. I want to create rectangle objects with the exact corresponding coordinates as drawn above and add them to an multidimensional array, but i need the y to start at 5 and increment by 30 for each row at a time. This is what i have so far:
* Also I'm not sure if this is actually possible or not so let me know if you have an idea for another way i could do it.
public void setBricks()
{
for(int i= 0; i<10;i++)
{
for(int a=0; a<5; a++)
{
bricks[i][a] = new Rectangle(x+(width*i)+(spacer*i), y +a, width, height);
} // any ideas how to get each y ^ coordinate equal to the one above
} // i need the int variables to stay at 10 and 5 because of the size of the array.
}
Well, if you want y to start at 5 and increment by 30, use 5+a*30 :
public void setBricks()
{
for(int i= 0; i<10;i++)
{
for(int a=0; a<5; a++)
{
bricks[i][a] = new Rectangle(x+(width*i)+(spacer*i), 5 + a*30, width, height);
}
}
}

Breaking bricks with chain reaction

I am developing a game in java just for fun. It is a ball brick breaking game of some sort.
Here is a level, when the ball hits one of the Orange bricks I would like to create a chain reaction to explode all other bricks that are NOT gray(unbreakable) and are within reach of the brick being exploded.
So it would clear out everything in this level without the gray bricks.
I am thinking I should ask the brick that is being exploded for other bricks to the LEFT, RIGHT, UP, and DOWN of that brick then start the same process with those cells.
//NOTE TO SELF: read up on Enums and List
When a explosive cell is hit with the ball it calls the explodeMyAdjecentCells();
//This is in the Cell class
public void explodeMyAdjecentCells() {
exploded = true;
ballGame.breakCell(x, y, imageURL[thickness - 1][0]);
cellBlocks.explodeCell(getX() - getWidth(),getY());
cellBlocks.explodeCell(getX() + getWidth(),getY());
cellBlocks.explodeCell(getX(),getY() - getHeight());
cellBlocks.explodeCell(getX(),getY() + getHeight());
remove();
ballGame.playSound("src\\ballgame\\Sound\\cellBrakes.wav", 100.0f, 0.0f, false, 0.0d);
}
//This is the CellHandler->(CellBlocks)
public void explodeCell(int _X, int _Y) {
for(int c = 0; c < cells.length; c++){
if(cells[c] != null && !cells[c].hasExploded()) {
if(cells[c].getX() == _X && cells[c].getY() == _Y) {
int type = cells[c].getThickness();
if(type != 7 && type != 6 && type != 2) {
cells[c].explodeMyAdjecentCells();
}
}
}
}
}
It successfully removes my all adjacent cells,
But in the explodeMyAdjecentCells() method, I have this line of code
ballGame.breakCell(x, y, imageURL[thickness - 1][0]);
//
This line tells the ParticleHandler to create 25 small images(particles) of the exploded cell.
Tough all my cells are removed the particleHandler do not create particles for all the removed cells.
The problem was solved youst now, its really stupid.
I had set particleHandler to create max 1500 particles. My god how did i not see that!
private int particleCellsMax = 1500;
private int particleCellsMax = 2500;
thx for all the help people, I will upload the source for creating the particles youst for fun if anyone needs it.
The source code for splitting image into parts was taken from:
Kalani's Tech Blog
//Particle Handler
public void breakCell(int _X, int _Y, String URL) {
File file = new File(URL);
try {
FileInputStream fis = new FileInputStream(file);
BufferedImage image = ImageIO.read(fis);
int rows = 5;
int colums = 5;
int parts = rows * colums;
int partWidth = image.getWidth() / colums;
int partHeight = image.getHeight() / rows;
int count = 0;
BufferedImage imgs[] = new BufferedImage[parts];
for(int x = 0; x < colums; x++) {
for(int y = 0; y < rows; y++) {
imgs[count] = new BufferedImage(partWidth, partHeight, image.getType());
Graphics2D g = imgs[count++].createGraphics();
g.drawImage(image, 0, 0, partWidth, partHeight, partWidth * y, partHeight * x, partWidth * y + partWidth, partHeight * x + partHeight, null);
g.dispose();
}
}
int numParts = imgs.length;
int c = 0;
for(int iy = 0; iy < rows; iy ++) {
for(int ix = 0; ix < colums; ix++) {
if(c < numParts) {
Image imagePart = Toolkit.getDefaultToolkit().createImage(imgs[c].getSource());
createCellPart(_X + ((image.getWidth() / colums) * ix), _Y + ((image.getHeight() / rows) * iy), c, imagePart);
c++;
} else {
break;
}
}
}
} catch(IOException io) {}
}
You could consider looking at this in a more OO way, and using 'tell don't ask'. So you would look at having a Brick class, which would know what its colour was, and its adjacent blocks. Then you would tell the first Block to explode, it would then know that if it was Orange (and maybe consider using Enums for this - not just numbers), then it would tell its adjacent Blocks to 'chain react' (or something like that), these blocks would then decide what to do (either explode in the case of an orange block - and call their adjacent blocks, or not in the case of a grey Block.
I know its quite different from what your doing currently, but will give you a better structured program hopefully.
I would imagine a method that would recursively get all touching cells of a similar color.
Then you can operate on that list (of all touching blocks) pretty easily and break all the ones are haven't been broken.
Also note that your getAdjentCell() method has side effects (it does the breaking) which isn't very intuitive based on the name.
// I agree with Matt that color (or type) should probably be an enum,
// or at least a class. int isn't very descriptive
public enum CellType { GRAY, RED, ORANGE }
public class Cell{
....
public final CellType type;
/**
* Recursively find all adjacent cells that have the same type as this one.
*/
public List<Cell> getTouchingSimilarCells() {
List<Cell> result = new ArrayList<Cell>();
result.add(this);
for (Cell c : getAdjecentCells()) {
if (c != null && c.type == this.type) {
result.addAll(c.getTouchingSimilarCells());
}
}
return result;
}
/**
* Get the 4 adjacent cells (above, below, left and right).<br/>
* NOTE: a cell may be null in the list if it does not exist.
*/
public List<Cell> getAdjecentCells() {
List<Cell> result = new ArrayList<Cell>();
result.add(cellBlock(this.getX() + 1, this.getY()));
result.add(cellBlock(this.getX() - 1, this.getY()));
result.add(cellBlock(this.getX(), this.getY() + 1));
result.add(cellBlock(this.getX(), this.getY() - 1));
return result;
}
}

Categories

Resources