Coordinate generation for memory card game - java

How can I generate (x, y) coordinates for a memory card game? Let's say I can set the number of cards, rows and columns. How would my for loop look like?
My general idea is as follows:
final int ROWS = 4;
final int COLUMNS = 5;
for(int i = 0; i<ROWS; i++){
for(int j = 0; j<COLUMNS; j++){
//calculate X coordinate
int index = some_calculation
MemoryCard memoryCard = new MemoryCard(x, y, index);
}
//calculate y coordinate
}
However, I'm having an issue creating my objects here. The above loop will go 4 times for i and 5 times for j. So, in total I have 20 objects there. But how do I get to my object's index?
Let's say I have an array list of my objects:
private ArrayList<MemoryCard> objects = new ArrayList<MemoryCard>();
//parameters for MemoryCard object are (float x, float y, Texture frontImage)
Is there a way to make this dynamic? To make the program generate proper positions if I set number of ROWS to 3 and COLUMS to 6? Or any other even pair.

you can translate easy...
public int getIndexOf(int x, int y){
return x + y * ROWS;
}
and revert as well...
public int getXFromIndex(int index){
return index%ROWS;
}
public int getYFromIndex(int index){
return index/ROWS;
}

Martin Frank already provided the correct answer to your question, but I'd like to present an alternative solution. Instead of serializing your rows and columns into a 1D array list, why not use a 2D array?
MemoryCard[][] cards = new MemoryCard[ROWS][COLUMNS];
Then you can access your card on row x and column y just like this:
MemoryCard card = cards[x][y];

Sounds like it would be better to use a 2D array which will be easier to maintain and visualize positions, something like
Objects[][] memoryCards;
Then to fill it you just use your loop.

Related

Java * Two-Dimensional Array * Plotting Points on Array [duplicate]

This question already has an answer here:
Java - Two-Dimensional Arrays - Plotting Points
(1 answer)
Closed 6 years ago.
I have an assignment for a JAVA class I am taking. We are discussing two-dimensional arrays, however on this particular assignment, I can not figure out how to return back specific points and set those points with a specific value. Here is the assignment:
Write a method called create2DArray that will fill, create, and return a 10 x 10 2d array with random numbers in the range of 1 to 100. Write a method called print2DArray that will print a 10 x 10 2D array in row column fashion. Write a method called createCoords that will search the 2D array looking for any value that is evenly divisible by 3. Once you have found a number you should log the row, column location. This means when your method finishes it should produce a list of coordinates that I can use to plot my graph. This method must also return the number of coordinates that are divisible by 3 so that I know how many points there are to plot. I am not particular as to how the coordinates are returned back as long as I get a list of the row, column locations. So, I will leave it to you to work out a mechanism for returning the values. To test that you have logged the coordinates create another function called fillLocations that will fill the locations in the array you have logged with -1. So, your program should flow in this order 1.create2DArray 2.print2DArray 3.createCoords 4.fillLocations 5.print2DArray
I understand and have completed create2DArray and print2DArray, but I can not figure out createCoords and fillLocations. Here is what I have so far, but it does not work and there are errors present:
public int createCoords(int row1, int col1){
int[][] coords = new int[row1][col1];
int[][] count = new int[0][0];
int co = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(coords[row][col] % 3 == 0)
co++;
return count[row][col];
}
}
return co;}
public int fillLocations(int[][] count){
int x = 0;
int y = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(count[row][col] % 3 == 0)
x = row;
y = col;
break;
}
}
return (x, y);}
I'm not going to write the code, but pretty much how I would go about doing this is:
I would have a separate 2d boolean array the same size as the 2d int array, auto filled with false. This would go in createCoords.
use nested for loop to cycle through all addresses of the 2d int array, and when i find a number that's divisible by three, i mark the corresponding point on the boolean array as 'true'. This would also go in createCoords.
after the for loops finish, I then look at the original 2d int array and boolean array. i would use the nested for loops again, and when i find a true value on the boolean array, i would mark the corresponding location on the int array as -1. This would go in fillLocations. You should also pass the 2d boolean array to fillLocation along with the 2d int array.
Good luck!
EDIT: this is assuming that the FillLocation function REPLACES values in the 10x10 int array with -1. That's what I interpreted your question to be. Please correct me if i'm wrong. I also added a short description at the end of each paragraph where each segment of code would go.
There are couple of problems with your code. Firstly, for the fillLocations method, you are expected to return the NUMBER of cells ([row][column]) where the value is divisible by 3. This means that for each value that passes the test:
if(coords[row][col] %3 === 0)
Then you should increment the counter by 1.
So for this part, your code would look like:
int [][] your2DArray = new int[10][10];
...
private int getNumberOfValuesDivisibleByThree(){
int numberOfValuesDivisibleByThree = 0;
for (int row=0; row < your2DArray.length; row++){
for(int col = 0; col < your2DArray[0].length; col++){
if(your2DArray[row][col] % 3 === 0){
//value at this coordinate or in this cell is divisible by 3
//here you can 'log' the coordinates as required -
System.out.println(row+","+col);
//increment the count
numberOfValuesDivisibleByThree +=1;
}
}
}
//return the final count
return numberOfValuesDivisibleByThree;
}
Please see how to create and manipulate a 2D array in Java. Syntax for creating a two-dimensional array

Java - Two-Dimensional Arrays - Plotting Points

I have an assignment for a JAVA class I am taking. We are discussing two-dimensional arrays, however on this particular assignment, I can not figure out how to return back specific points and set those points with a specific value. Here is the assignment:
Write a method called create2DArray that will fill, create, and return
a 10 x 10 2d array with random numbers in the range of 1 to 100. Write
a method called print2DArray that will print a 10 x 10 2D array in row
column fashion. Write a method called createCoords that will search
the 2D array looking for any value that is evenly divisible by 3.
Once you have found a number you should log the row, column location.
This means when your method finishes it should produce a list of
coordinates that I can use to plot my graph. This method must also
return the number of coordinates that are divisible by 3 so that I
know how many points there are to plot. I am not particular as to how
the coordinates are returned back as long as I get a list of the row,
column locations. So, I will leave it to you to work out a mechanism
for returning the values. To test that you have logged the
coordinates create another function called fillLocations that will
fill the locations in the array you have logged with
-1. So, your program should flow in this order
create2DArray
print2DArray
createCoords
fillLocations
print2DArray
I understand and have completed create2DArray and print2DArray, but I can not figure out createCoords and fillLocations. Here is what I have so far, but it does not work and there are errors present:
public int createCoords(int row1, int col1){
int[][] coords = new int[row1][col1];
int[][] count = new int[0][0];
int co = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(coords[row][col] % 3 == 0)
co++;
return count[row][col];
}
}
return co;}
public int fillLocations(int[][] count){
int x = 0;
int y = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(count[row][col] % 3 == 0)
x = row;
y = col;
break;
}
}
return (x, y);}
As a programmer you'll nearly always need to research for doing different things. This research will be easier when you divide your problem to smaller problems.
For example you need to generate random numbers? So search on google that and you'll find this: How do I generate random integers within a specific range in Java?.
You need to create and return a 2D array? Google and see Syntax for creating a two-dimensional array
And with your art, put the pieces of the puzzle together in a way that gives your desired result.
public int[][] create2DArray() {
int[][] newArray = new int[10][10];
Random random = new Random();
int range = 100;
for(int i = 0; i < 10; i++)
{
for(int j = 0;j<arr[0].length;j++)
{
newArray[i][j]= (random.nextInt(range) + 1);
}
}
return newArray;
}
This method, creates and returns a 10*10 2D array filled with random generated numbers between 1-100. I'm sure you can write the rest of your program and enjoy from it by yourself.

Java 2D Array: Go through groups of entries and sum their values

Let's say that there exists a 2D Java array (4x6 for representation purposes) filled with numbers ranging from 1 to 9 in a random order.
What if one wanted to calculate the individual sum of all groups of numbers in that array?
Simple illustration:
In this particular case:
Sum of the blue area
Sum of the violet area
Sum of the red area
Sum of the yellow area
...
The following code works for any array, but only if each entry is precisely 1x1 big which is useless in this case (and any other case), as it simply goes through all entries.
for (int a = 0; a < x; a++) {
for (int b = 0; b < y; b++) {
sum = array[a][b];
}
}
How would you make it go through groups of entries and then sum all values located in an individual group?
startx, starty, endx, endy is the answer to that. You will iterate from start to end. This does require you to know (or be able to calculate) those variables. If not please clarify the exact structure.
If your array is declared like:
int[][] matrix = new int [4][6];
A rough example:
public int sumOfSubMatrix (int startx, int starty, int endx, int endy) {
int sum = 0;
for (int x = startx; x <= endx; x++) {
for (int y = starty; y <= endy; y++) {
sum += matrix[x][y];
}
}
return sum;
}
You simply add every "cell" to the sum variable.
Now, this is not possible if the "colors" were spread out, even one cell being off, then the algorithm has to something of them, like their position. If the structure is 100% chaotic then your best option is brute force with if-guards.

Mean values of this 3-D array along the third dimension in java

How do I compute the mean of a 3-D matrix which is similar to using mean(array, 3) in matlab, where 'array' is 3-D ie. mean values of a 3-D array along the third dimension. A java equivalent
For each element in the 3rd dimension you get a 2D matrix. For instance,
int my3darray[][][] = new int[10][20][30];
new2darray = my3darray[i];
For that 2D matrix you can calculate the mean value. For instance,
The size of a 2D array can be calculated as follows:
array.length * array[0].length;
Then more or less this is what you need:
int rows = 2; // you get the size from array.length
int cols = 3; // you get the size from array[0].length
int i, j;
for (i=0;i<rows;i++); {
for (i=0;j<cols;j++); {
sum += res[i][j];
}
}
System.out.println(sum/(rows*cols))
In case you are using Apache Common Math there is a getMean and a mean function and you can use it like this:
// assume values is a double[] array
double mean = StatUtils.mean(values);

2d array squares initialization and selection

For code optimization purposes, I want to create a 2d array that contains 40 equal squares (10x10px). Each square represents 1\40 of the displayed window (400x400px).
I populate the 2d array with the standard double for-loop methodology.
int col = 40;
int row = 40;
int boxPosition = 0; //Position of the box (coordinates)
Integer[][] boxes = new Integer[40][40];
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
boxes[i][j] = boxPosition;
boxPosition += 10; //Creates a 10px box.
}
boxPosition = 0; //Resets box size for next column
}
There are several circles in this program. We have a ship(circle) that fires missiles(circles) toward enemies(circles).
I want to run collision detection ONLY when there is a bullet + an enemy in one of the squares. This will greatly optimize the code.
The question is... how do I create these squares off of a 2d array? How do I select each square? How do I test if the missiles and the enemies are inside the same square?
Code examples are GREATLY appreicated.
Thanks.
I'm not sure what you're doing with the 2D array or why it contains Integers or why it contains an increasing size in each column, but the general way to do grid-based collision is to have a 2D array of GameObjects. A GameObject in your case could be a Ship, a Missile, or an Enemy.
When one of your GameObjects wants to move, you simply check the 2D array of GameObjects to see what is already in the square you want to move to. If it's empty, you can do the move. If it's not empty, you've got a collision.

Categories