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.
Related
I am new to programming and I have an assignment in Java that asks the user to navigate a 10X10X10 cubic maze, where there must be 500 monsters randomly generated, 499 open cells, and 1 treasure chest. The treasure chest must also be randomly generated, but it cannot occur within the same spot as a monster. The program I have to write asks for user input to check a cell in the array to see if its the treasure chest. If the cell is empty, I have to give a hint as to where the treasure chest is (how many cells away and if you're in the same row, column, or page). The user gets three tries to find the treasure chest. At the end of the three tries, or if they hit a monster, the user loses and is told in what cell the chest was placed. For the purposes of the assignment, an empty cell = 0, the only cell with the treasure chest = 1, and the monster cell = 2.
I am having trouble populating the cells with only 500 monsters and one chest. My code below populates all the cells with a random amount of 0's, 1's and 2's. I need to limit the 2's to five-hundred instances, the 1's to one instance (and check beforehand to make sure a monster isn't in the cell), and keep the rest 0. I also need to make sure I'm not populating the same cell with more than one monster. This is as far as I've got:
import java.util.Random;
public class FindTheCheese
{
public static void main(String args[ ])
{
int size = 10;
int[][][] maze = new int[10][10][10];
Random gen = new Random();
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++) {
for(int k = 0; k <10; k++) {
maze[i][j][k] = gen.nextInt(3);
System.out.print(maze[i][j][k] + ", "); // this won't be part of the final code, just used to check if I'm populating correctly
}
System.out.println();
}
}
}//closing main
}//closing class FindTheCheese
Create a one-dimensional array of length 1000 to hold all the values to go into the maze. Set 500 elements to 2 (the monsters), one element to 1 (the treasure chest) and 499 elements to 0 (the free cells).
Shuffle the array using Collections.shuffle(Arrays.asList(yourOneDimArray)).
Now fill the values from the shuffled array into your 3-dimensional matrix in turn. Underway when you encounter the chest, record its coordinates in the maze. You will need this for reporting back to the user.
When you first create the maze, all cells will be zero by default. Next, add the single treasure to a random spot. Finally, pick a random cell and see if it's empty. If it isn't, pick another random cell. If it is, place a monster. Repeat that 500 times with a for loop:
public static void main(String[] args) {
int size = 10;
int[][][] maze = new int[10][10][10]; // every cell is zero by default!
Random gen = new Random();
// place the treasure
maze[gen.nextInt(size)][gen.nextInt(size)][gen.nextInt(size)] = 1;
// place 500 monsters
for(int monsters = 1; monsters <= 500; monsters++) {
int i, j, k;
do {
i = gen.nextInt(size);
j = gen.nextInt(size);
k = gen.nextInt(size);
} while (maze[i][j][k] != 0);
maze[i][j][k] = 2;
}
// display the results
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++) {
for(int k = 0; k < size; k++) {
System.out.print(maze[i][j][k] + " ");
}
System.out.println();
}
}
}
for example, if the 2d image array is
1,10
2,20
3,30
4,40
so the size would be: int[][] table = new int[table.length][table[0].length];
from this point of view: table[# of columns][# of rows]
if I want to rotate counter clockwise by 90 degrees it would be
10,20,30,40
1,2,3,4
but the size would be [4][2] and I want it to stay [2][4]
the output I'm looking for is:
0,0
20, 30
2,3
0,0
I've seen how rotation is done but those methods change the size of the width and height. is there a way to accomplish this? TIA
The simple way I think is to use the for loop to get result.
Why don't you try the for loop for output?
The code below is an example.
for (int i = table[0].length; i < 0; i--) {
for(int j = 0; j < table.length; j++) {
print(a[i][j]);
}
}
I thought so, but I don't know if I got your intention well.
I am confused on how to print the location of the player in this array and have it update every time an input is plugged in for the direction it is moving? Currently I only get the - symbol in a 10 by 10 pattern but would like (0,0) to be an X where the player starts.
private final static int SIZEX = 10; // Board size
private final static int SIZEY = 10; // Board size
int[][] gameboard = new int[SIZEX][SIZEY];
for(int i=0; i<gameboard.length; i++)
{
for(int j=0; j<gameboard.length; j++)
{
System.out.print("-");
}
System.out.println("");
}
Use an if statement (or ternary operator) in your inner loop to print X if i and j match the x and y coordinate of the player
You could add a KeyListener to your games Component and set the x and y if the input matches the one required to move the player arround and print the position once the key is released.
To really answer your question we would need some sort of fields you have that hold the current players position
i want my program to randomly change the colour of around 50% of the rectangles within my grid, this is done using jframe.
i have an array with the length of the board and i want 50% of these numbers to be blue.
FALSE = grey
TRUE = blue
Note: this is within paint method using Graphics g
grid = new boolean[board.length];
Random r = new Random();
for(int i = 1;i <grid.length;i++){
int rand = r.nextInt(i);
}
Take the number of squares on the board and multiply by the target percent.
Assume 8x8 board, so 64 squares * .50 = 32.
I would create a List of all the rectangles.
Begin a loop. Generate a random number from 0 to the size of the rectangle list. Remove that position and make it blue. End loop if all 32 rectangles are identified.
//Pseudo code
java.util.Random random = new Random();
List<Integer> rectangles = new ArrayList<Integer>();
for(int i = 0; i < grid.length; i++)
{
rectangles.add(i);
}
//Fill the rectangles
for(int i = 0; i < 32; i++)
{
int position = random.nextInt(rectangles.size());
Integer toConvert = rectangles.remove(position);
//perform operation to make toConvert blue.
grid[toConvert] = true;
}
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.