How can I access the Cell Array in my getCell method? (Java) - java

my Task is to make an implementation of Conway's Game of Life. Therefor I need to create the class GameMap. In this class I will initialize an 2D Array.
Therefor I use those two methods.
private static Cell[][] buildCellArray(int width, int height){
Cell[][] cellArray = new Cell[width][height];
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
Now I want to access the cellArray to access a special Cell with the getCell(int posX, int posY) method.
My question is how I can access the cellArray?
I wanted to access it like this:
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
So that I get the Cell at a special position.
I hope somebody can help me out.
So the complete code part is:
public class GameMap {
private static Cell[][] buildCellArray(int width, int height){
Cell[][] cellArray = new Cell[width][height];
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
}
And the IDE says that cellArray in the method getCell is not a variable.

The IDE says cellArray cannot be resolve to a variable because it is local variable, to pass this problem just move Cell[][] cellArray = new Cell[width][height]; outside the buildCellArray().
public class GameMap {
Cell[][] cellArray;
private static Cell[][] buildCellArray(int width, int height){
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
}

Related

Java - counting the occurrences of a character in a random generator method using a separate method

I'm trying to figure out how to count the number of stars that were printed last time the print() method was used.
I'm confused on how to take the value of starsInLastPrint variable into the starsInLastPrint() method. My understanding is that this isn't possible. I assume there are plenty of things wrong with my current code that isn't helping. Below is my current state as I am stuck.
import java.util.Random;
public class NightSky {
private double density;
private int width;
private int height;
private int starsInLastPrint;
public NightSky(double density) {
width = 20;
height = 10;
this.density = density;
}
public NightSky(int width, int height) {
density = 0.1;
this.width = width;
this.height = height;
}
public NightSky(double density, int width, int height) {
this.density = density;
this.width = width;
this.height = height;
}
public void printLine() {
Random starPlacement = new Random();
String[] stars = new String[(this.width)];
for (int i = 0; i < this.width; i++) {
double random = starPlacement.nextDouble();
if (random <= this.density) {
stars[i] = "*";
this.starsInLastPrint++;
} else {
stars[i] = " ";
}
}
int j = 0;
while (j < stars.length) {
System.out.print(stars[j]);
j++;
}
System.out.println("");
}
public void print() {
NightSky nightSky = new NightSky(this.density, this.width, this.height);
this.starsInLastPrint = 0;
int i = 0;
while (i < this.height) {
nightSky.printLine();
i++;
}
}
public int starsInLastPrint() {
return this.starsInLastPrint;
}
}
You are on the right track. Though, you don't need to instantiate another NightSky object inside the print method. You can just do the following,
public void print() {
this.starsInLastPrint = 0;
int i=0;
while (i < this.height) {
printLine();
i++;
}
}
So, everytime you call print, it will update the stars count for that print method call. Here is the whole code,
import java.util.Random;
public class NightSky {
private double density;
private int width;
private int height;
private int starsInLastPrint;
public static void main(String[] args){
NightSky sky = new NightSky(5,5);
sky.print();
System.out.println(sky.starsInLastPrint());
sky.print();
System.out.println(sky.starsInLastPrint());
}
public NightSky(double density) {
width = 20;
height = 10;
this.density = density;
}
public NightSky(int width, int height) {
density = 0.1;
this.width = width;
this.height = height;
}
public NightSky(double density, int width, int height) {
this.density = density;
this.width = width;
this.height = height;
}
public void printLine() {
Random starPlacement = new Random();
String[] stars = new String[(this.width)];
for (int i = 0; i < this.width; i++) {
double random = starPlacement.nextDouble();
if (random <= this.density) {
stars[i] = "*";
this.starsInLastPrint++;
} else {
stars[i] = " ";
}
}
int j = 0;
while (j < stars.length) {
System.out.print(stars[j]);
j++;
}
System.out.println("");
}
public void print() {
this.starsInLastPrint = 0;
int i=0;
while (i < this.height) {
printLine();
i++;
}
}
public int starsInLastPrint() {
return this.starsInLastPrint;
}
}
Sample run of the above code:
* *
*
*
4
0

How do I fix "cannot resolve method"?

So first I have this class:
public float getPixel(int height, int width)
{
return data[height][width];
}
public void setPixel(float value, int height, int width)
{
if (value > getMax())
value = getMax();
if (value < 0)
value = 0;
data[height][width] = value;
}
private Image(String magicNumber, int height, int width, float max) {
this.magicNumber = magicNumber;
this.width = width;
this.height = height;
this.max = max;
data = new float[height][width];
}
...
public Image clone()
{
Image clone = new Image(getMagicNumber(), getHeight(), getWidth(), getMax());
for (int i = 0; i < getHeight(); i++)
{
for (int j = 0; j < getWidth(); j++)
{
clone.setPixel(getPixel(i, j), i, j);
}
}
return clone;
}
And then this class:
public class Filter {
public Filter() {
}
public Image linearFilter(Image image, float[][] kernel)
{
Image filtered = image.clone();
for (int i = 0; i < getHeight(); i++)
{ /* cannot resolve getHeight*/
...
}
return filtered;
}
}
I have two questions:
1) Why do I don't need to create an instance of the class Image. Here I can already use filtered.setPixels...
2) How do I fix the Problem with "cannot resolve method"?
I can't really tell from your post because the first snippet you've posted doesn't seem to be an entire class but rather a portion of it. I assume you have an Image class, and that Image class has a method called getHeight().
Inside the for loop condition for (int i = 0; i < getHeight(); i++), you'll most likely want to change getHeight() to filtered.getHeight() because getHeight() is a method inside of the Image class, and filtered is (presumably) of type Image.

Create multiple of 1 objects next to each other (grid like)

Hey if i have a simple rectangle class, how can i make it so that it creates that rectangle next to each other in a grid like pattern? maybe like 10 rows 10 columns?
public class Vak {
private int posX = 0;
private int posY = 0;
private int width = 50;
private int height = 50;
private Color colour;
public Vak(Color c, int x, int y){
this.colour = c;
this.posX = x;
this.posY = y;
}
public int vakPosY(){
return this.posY;
}
public int vakPosX(){
return this.posX;
}
public void draw (Graphics g){
g.setColor(this.colour);
g.drawRect(posX, posY, width, height);
}
public void move(int numberPixelsX, int numberPixelsY){
this.posX = this.posX + numberPixelsX;
this.posY = this.posY + numberPixelsY;
}
}
this is my code for rectangle "vak"
Is this what you are looking for?
int mapWidth = 10;
int mapHeight = 10;
// tileWidth and tileHeight should probably be public static const fields or static readonly properties of some class, but I put them here for now.
int tileWidth = 50; // Pixels
int tileHeight = 50; // Pixels
// tiles should probably be a field of a Map class (if you have one)
Vak[][] tiles = new Vak[mapWidth][mapHeight];
for(int x = 0; x < mapWidth; x++)
{
for(int y = 0; y < mapHeight; y++)
{
tiles[x][y] = new Vak(Color.white, x*tileWidth, y*tileHeight);
}
}
And then in the drawing part of the main loop:
for(Vak[] row : tiles)
{
for(Vak tile : row)
{
tile.draw(g);
}
}

Gabor Image Processing in Java without MathLab

I'm looking for some help in applying 2D Gabor Wavelets Formula to an image in java.
This is the formula that I'm using.
Gabor Formula
I need my output to look like this
I've read the image in and its currently stored in a 2D array. My code is as follows:` public void RunGabor() throws IOException
{
double[][]pixels=getImage();
int H= pixels.length;
int W =pixels[0].length;
size=H*W;
gaussian=size/2;
System.out.println(gaussian);
GaborGrid = new int[H][W];
GaborNorm = new int[H][W];
double X=0,Y=0, gx=-gaussian,gy=-gaussian, count=0, total=0;
int ax=0, dy=0;
for(int x=0; x<pixels.length; x++)
{
for(int k=0;k< pixels[0].length; k++)
{
X=gx*Math.cos(theta)+gy*Math.sin(theta);
Y=-gx*Math.sin(theta)+gy*Math.cos(theta);
pixels[dy][ax]=((Math.exp(-(Math.pow(X, 2)+(Math.pow(Y, 2)*
Math.pow(upsi,2)))/(2*Math.pow(sigma, 2))))*
(Math.cos((kappa*X+varphi))));
System.out.println("Pixels" +pixels[dy][ax]);
total+=pixels[dy][ax];
count++;
System.out.println("Count" +count);
gx+=1;
ax++;
}
System.out.println("second loop");
ax=0;
dy++;
gy+=1;
gx=-gaussian;
}
mean=total/count;
System.out.println("Mean" +mean);
NormaliseImage(pixels);
}`
From there it calls a method normaliseImage
public void NormaliseImage(double[][] pixels)
{
double minII = pixels[0][0];
double maxII = pixels[0][0];
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
if(pixels[y][x] <= minII){
minII =pixels[y][x];
}
if(pixels[y][x]>= maxII){
maxII=pixels[y][x];
}
}
My create image class looks like this
public CreateImage(int[][] data, String IMGname)
{
name = IMGname;
width = data[0].length;
height = data.length;
System.out.println("NEW IMAGE 1");
pixels = new int[height*width];
int count=0;
for(int i=0; i<data.length; i++)
{
for(int j=0; j<data[0].length; j++)
{
pixels[count] = (int)Math.abs(data[i][j]);
pixels[count] = convert2pixel(pixels[count]);
count++;
}
}
Create(width, height, pixels, name);
}
public int convert2pixel(int pixel)
{
return ((0xff<<24)|(pixel<<16)|(pixel<<8)|pixel);
}
public int convert2grey(double pixel)
{
int red=((int)pixel>>16) & 0xff;
int green = ((int)pixel>>8) & 0xff;
int blue = (int)pixel & 0xff;
return (int)(0.3*red+0.6*green+0.1*blue);
}
public void Create(int Width, int Height, int pixels[], String n)//throws Exception
{
//System.out.println("Inside Create Image");
MemoryImageSource MemImg = new MemoryImageSource(Width,Height,pixels,0,Width);
Image img2= Toolkit.getDefaultToolkit().createImage(MemImg);
BufferedImage bfi = new BufferedImage(Height,Width, BufferedImage.TYPE_INT_BGR);
Graphics2D g2D = bfi.createGraphics();
g2D.drawImage(img2, 0, 0, Width, Height, null);
try
{
ImageIO.write(bfi, "png", new File(n+".png"));
}
catch(Exception e){}
}
}
My output is just a grey screen, any help would be appreciated.
Update: Gabor Driver Class `
public class Gabor_Driver{
public static void main(String[]args)throws IOException
{
double lamda=75;
double theta=45;
double varphi=90;
double upsi=10;
double bandW=10;
//int size=500;
Gabor gabor = new Gabor(lamda, theta, varphi, upsi, bandW );
}
}
`
Gabor class :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Gabor
{
CreateImage ci;
private double lamda=0;
private double theta=0;
private double varphi=0;
private double upsi=0;
private double bandW=0;
private double B=0;
private double sigma=0;
private double kappa=0;
private int[][] GaborGrid;
private int[][] GaborNorm;
int size=0;
double toRadians=180/Math.PI, min=500, max=-500, mean=0;;
int gaussian=0;
double rotation;
double GLFmean=0;
//Standard Gabor no quantization
public Gabor(double l, double t, double v, double u, double b) throws IOException
{
lamda=l;
theta=t/toRadians;
varphi=v/toRadians;
upsi=u;
bandW=b;
kappa=(2*Math.PI)/lamda;
Calculate_Sigma();
RunGabor();
}
public void RunGabor() throws IOException
{
double[][]pixels=getImage();
int H= pixels.length;
int W =pixels[0].length;
size=H*W;
gaussian=size/2;
System.out.println(gaussian);
GaborGrid = new int[H][W];
GaborNorm = new int[H][W];
double X=0,Y=0, gx=-gaussian,gy=-gaussian, count=0, total=0;
int ax=0, dy=0;
for(int x=0; x<pixels.length; x++)
{
for(int k=0;k< pixels[0].length; k++)
{
X=gx*Math.cos(theta)+gy*Math.sin(theta);
Y=-gx*Math.sin(theta)+gy*Math.cos(theta);
pixels[dy][ax]=((Math.exp(-(Math.pow(X, 2)+(Math.pow(Y, 2)*
Math.pow(upsi,2)))/(2*Math.pow(sigma, 2))))*
(Math.cos((kappa*X+varphi))));
System.out.println("Pixels" +pixels[dy][ax]);
total+=pixels[dy][ax];
count++;
System.out.println("Count" +count);
gx+=1;
ax++;
}
System.out.println("second loop");
ax=0;
dy++;
gy+=1;
gx=-gaussian;
}
mean=total/count;
System.out.println("Mean" +mean);
NormaliseImage(pixels);
}
public double[][] getImage() throws IOException{
int[][]pixels =null;
double[][] doubles = null;
JFileChooser fc = new JFileChooser();
int returnValue = fc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
BufferedImage image = ImageIO.read(selectedFile);
System.out.println(selectedFile.getName());
int W =image.getWidth();
int H= image.getHeight();
int width = image.getWidth();
int height = image.getHeight();
pixels = new int[height][width];
for (int row = 0; row < height; row++) {
image.getRGB(0, row, width, 1, pixels[row], 0, width);
}
doubles = new double[pixels.length][pixels[0].length];
for(int i=0; i<pixels.length; i++) {
for(int j=0; j<pixels[0].length; j++)
doubles[i][j] = pixels[+i][+j];
}
}
return doubles;
}
public void NormaliseImage(double[][] pixels)
{
double minII = pixels[0][0];
double maxII = pixels[0][0];
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
if(pixels[y][x] <= minII){
minII =pixels[y][x];
}
if(pixels[y][x]>= maxII){
maxII=pixels[y][x];
}
}
}
int count=0;
double total=0;
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
total += pixels[y][x];
count++;
}
}
double average =(double)total/count;
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
double normalise= ((((pixels[y][x]-min))/((max-min)))*255);
if(normalise<=average){
normalise =0;
}
GaborNorm[y][x] = (int) normalise;
}
}
ci = new CreateImage(GaborNorm, "Gabor");
}
private void Calculate_Sigma()
{
B=(1/Math.PI)*(0.588705011)*((Math.pow(2, bandW)+1)/(Math.pow(2, bandW)-1));
sigma=B*lamda;
}
}
Create image class:
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
public class CreateImage
{
int[] pixels;
int width=0, height=0;
String name;
public CreateImage(int[][] data, String IMGname)
{
name = IMGname;
width = data[0].length;
height = data.length;
System.out.println("NEW IMAGE 1");
pixels = new int[height*width];
int count=0;
for(int i=0; i<data.length; i++)
{
for(int j=0; j<data[0].length; j++)
{
pixels[count] = (int)Math.abs(data[i][j]);
pixels[count] = convert2pixel(pixels[count]);
count++;
}
}
Create(width, height, pixels, name);
}
public int convert2pixel(int pixel)
{
return ((0xff<<24)|(pixel<<16)|(pixel<<8)|pixel);
}
public int convert2grey(double pixel)
{
int red=((int)pixel>>16) & 0xff;
int green = ((int)pixel>>8) & 0xff;
int blue = (int)pixel & 0xff;
return (int)(0.3*red+0.6*green+0.1*blue);
}
public void Create(int Width, int Height, int pixels[], String n)//throws Exception
{
//System.out.println("Inside Create Image");
MemoryImageSource MemImg = new MemoryImageSource(Width,Height,pixels,0,Width);
Image img2= Toolkit.getDefaultToolkit().createImage(MemImg);
BufferedImage bfi = new BufferedImage(Height,Width, BufferedImage.TYPE_INT_BGR);
Graphics2D g2D = bfi.createGraphics();
g2D.drawImage(img2, 0, 0, Width, Height, null);
try
{
ImageIO.write(bfi, "png", new File(n+".png"));
}
catch(Exception e){}
}
}
Your calculations are mostly correct. You are calculating the function itself in RunGabor - I think gx, gy should be replaced with x, k. This
for(int x=0; x<pixels.length; x++)
{
for(int k=0;k< pixels[0].length; k++)
{
X=gx*Math.cos(theta)+gy*Math.sin(theta);
Y=-gx*Math.sin(theta)+gy*Math.cos(theta);
pixels[dy][ax]=((Math.exp(-(Math.pow(X, 2)+(Math.pow(Y, 2)*
Math.pow(upsi,2)))/(2*Math.pow(sigma, 2))))*
(Math.cos((kappa*X+varphi))));
should be replaced with
public Kernel getKernel() {
double sigma = calculateSigma(waveLength, bandwidth);
float[] data = new float[width*height];
for(int k = 0, x = -width/2; x <= width/2; x++) {
for(int y = -height/2; y <= height/2; y++) {
for(double orientation : orientations) {
double x1 = x*Math.cos(orientation) + y*Math.sin(orientation);
double y1 = -x*Math.sin(orientation) + y*Math.cos(orientation);
data[k] += (float)(gaborFunction(x1, y1, sigma, aspectRatio, waveLength, phaseOffset));
}
k++;
}
}
But you have to apply the function on the pixels that you are reading, the image. If you look at this other implementation https://github.com/clumsy/gabor-filter/blob/master/src/main/java/GaborFilter.java
you will find many parallels. See if you can fix it.
At least as a first step you should try to print the values of the gabor function either 3x3 or 5x5. If they look reasonable you can go ahead to apply it to the image.

Cannot be instantiated

I've been trying to create a sprite to be used on our java game. Everything seems normal, i see no errors on my program but suddenly when it's to be run an error appeared that it Cannot be Instantiated. Can somebody tell me what's wrong with it?
#SuppressWarnings("unused")
public class TrueSprite
{
BufferedImage spriteSheet = ImageIO.read(new File("robin.png"));
int width = 240, height = 314, rows = 5 , columns = 5;
BufferedImage[] sprites = new BufferedImage[rows * columns];
public TrueSprite(int width, int height, int rows, int columns) throws IOException
{
this.width = width;
this.height = height;
this.rows = rows;
this.columns = columns;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
sprites[(i * columns) + j ] = spriteSheet.getSubimage(i * width, j * height, width, height);
}
}
}
public void paint(Graphics g)
{
g.drawImage(sprites[1], 100, 100, null);
}
}
here's the error:
load: really.sprite.TrueSprite.class can't be instantiated.
java.lang.InstantiationException: really.sprite.TrueSprite
at java.lang.Class.newInstance(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
First of all, you have no constructor, which is essential for your class to be instantiated. Put this inside your class declaration:
public TrueSprite() {
//code to run when your class is instantiated.
}
Now, this won't do anything special, but you can call it with:
TrueSprite sprite = new TrueSprite();
Additionally, your class needs to be cleaned up. Try putting your assignment code inside the constructor we just built, and the declaration to these variables outside of it:
#SuppressWarnings("unused")
public class TrueSprite
{
private final int width;
private final int height;
private final int rows;
private final int cols;
private BufferedImage bigImg;
private BufferedImage[] sprites;
public TrueSprite(int width, int height, int rows, int columns) {
this.width = width;
this.height = height;
this.rows = rows;
this.cols = columns;
this.bigImg = ImageIO.read(new File("robin.png"));
this.sprites = new BufferedImage[rows * cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sprites[(i * cols) + j] = bigImg.getSubimage(j * width, i * height, width, height);
}
}
}
public void paint(Graphics g)
{
g.drawImage(sprites[1], 100, 100, null);
}
}
Just make sure you pass in four valid arguments into your TrueSprite constructor to call it correctly:
TrueSprite sprite = new TrueSprite(200, 500, 20, 50);
I think you need to create a non param constructor like
public TrueSprite() throws IOException
Your BufferedImage[] sprites = new BufferedImage[rows * columns]; outside the constructor initialised the sprites array with a size of 5*5=25. If you created a TrueSprit with a higher row or column, e.g. TrueSprite(100,100,100,100), the entries after sprites[24] will not be instantiated yet.
You should always place your initialisation inside the constructor. i.e.
private BufferedImage[] sprites;
public TrueSprite(int width, int height, int rows, int columns) throws IOException
{
this.width = width;
this.height = height;
this.rows = rows;
this.columns = columns;
this.sprites = new BufferedImage[rows * columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
sprites[(i * columns) + j ] = spriteSheet.getSubimage(i * width, j * height, width, height);
}
}
}
This will set the rows and columns to the correct value before creating your array with the values. Furthermore, you should have used a default constructor if you wanted to have default values. i.e.
public TrueSprite() throws IOException
{
this.width = 240;
this.height = 314;
this.rows = 5;
this.columns = 5;
this.sprites = new BufferedImage[rows * columns];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
sprites[(i * columns) + j ] = spriteSheet.getSubimage(i * width, j * height, width, height);
}
}
}

Categories

Resources