Swap objects in array? - java

I have this array ColorObject gameGrid[][] = new ColorObject[8][8]; It's a grid of sprite objects of the type ColorObject. Each object draw a circle in different colors.
I'm selecting one of them by comparing the x and y of the touch input coordinates with the positions of all objects in a loop to get the x index and y index of the selected object in the array. I then use this index values as selectedGridPositionX and selectedGridPositionY.
I also get the object like this:
selectedColorObject = gameGrid[col][row];
Finally in a method I'm trying to swap them like this:
tempColorObject = gameGrid[selectedGridPositionX + 1][selectedGridPositionY];
gameGrid[selectedGridPositionX + 1][selectedGridPositionY] = selectedColorObject;
gameGrid[selectedGridPositionX][selectedGridPositionY] = tempColorObject;
This works almost. On screen they swap, but when I touch them, they show the values from the previously object. What could I have done wrong? I hope my question isn't too unclear?

Related

how to add two coordinates (x,y) to a arraylist

My code reads all the pixels from the screen until it finds a pixel with the RGB value that I specified, which I managed to do, however if my screen has multiple pixels of that RGB value, I want to be able select a random pixel within that RBG value, instead of only working with the first pixel that my code finds I want to work with a random one. A workaround that I made generates a random number between 1 and 100 and everytime it checks a pixel it has a 1% chance of working with it, however this isn't the best method because of the way that my code scans the screen, (top-down, left-right) that means most of the time the pixel will end up on the upper left corner with isn't exactly random. I thought a good solution would be evertime the code goes through the if statement it stores the values x,y in a arraylist then I would get a random Index from that arraylist, but I couldn't figure out how to do that.
I appreciate any suggestions and help :)
int rng = new Random().nextInt(100) + 1;
if (color.equals(iron) && rng == 5){
if (r != 215 || g != 215 || b != 215){
Robot move = new Robot();
mousemoving.mouseGlide(x,y,1250,1000);
Runecraft.randomInt(35, 481);
move.mousePress(InputEvent.BUTTON1_DOWN_MASK);
move.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
System.out.println(iron);
flag = true;
break;
how to add two coordinates (x,y) to a arraylist
Check out the Point or Point2D classes. They have exactly what you want.
Then
List<Point> points = new ArrayList<>();

Java swing 2D pixel based sprite class not working correctly

I made me a pixel based sprite class for a simple game in java and swing, and I don't want to let some sprites go through other sprites. So I wrote two loops that are supposed to add the pixels of every other sprite to the "material" array of the level. Material should not be passable. With the level it does work. There the sprite can't pass through its material. But with other sprites it doesn't. It can go through them. And that's the bug I actually want to fix. It seems that the sprites' pixel arrays aren't appended.
Any help is greatly appreciated !
Code :
int applied_pixels=lvl.material.length;
Sprite[] others=new Sprite[] {other sprites};
/*EDIT : others[i].frameborders[others[i].frame].all is the point array of the sprites' pixels
others[i].frame is the frame of the sprite object, because they contain an array of BufferedImages. Frame is the one that should be taken*/
Level lvl=the level; //Containing a couple of point arrays of pixels of some types, for example containing the material array of pixels
int apply_pixels=0; //How many pixels are needed ?
for (int i=0; i < others.length; i++) {
if (others[i] != null) { //Isn't the sprite null
apply_pixels=apply_pixels+others[i].frameborders[others[i].frame].all.length; //How many points does it has to add ?
}
}
level=lvl.clone(); //Copy level to be able to later append points to the material array
level.material=new Point[apply_pixels];
System.arraycopy(lvl.material,0,level.material,0,lvl.material.length); //Copy old material array points
int appending_position=0;
appending_position=lvl.material.length; //Which destination position to append the points at ?
for (int i=0; i < others.length; i++) {
if (others[i] != null) { //Isn't the sprite null
System.arraycopy(others[i].frameborders[others[i].frame].all,0,level.material,appending_position,others[i].frameborders[others[i].frame].all.length); //Copy the points from the sprite to the material array
appending_position=appending_position+others[i].frameborders[others[i].frame].all.length; //Position to append at is now plus the length of appended points
}
}
I see two possible problems with your code as posted.
The first is that level.material=new Point[apply_pixels]; only allocates elements for the new pixels. It should probably read level.material=new Point[lvl.material.length + apply_pixels];. Alternatively, you can initialize apply_pixels as int apply_pixel = lvl.material.length instead of to zero.
The second problem is that you never show us how lvl replaces the original level. Presumably the code you posted is part of a method somewhere and level is an input that is passed in, but is accessed through a field by other parts of the program. Unless the modified lvl is correctly returned and replaces the original, the code here will have no effect. However, this is only speculation because OP refuses to post the relevant code.

How to compare variable values from multiple objectives

I've just started with java so bear with me if I confuse things.
Anyway, I want to create a level that contains 4 different rooms. I've done it so that every room is a seperate object which is created in the main method.
What I want to do then is to place every room inside a level of a certain size, and if a room overlaps another it will return false. Every room is basically a block of 100x100 pixels.
I've done so that every room object stores it's location on the level when placed by assigning the (x,y) cords to 2 variables defined within the room class.
But I run into trouble when placing the second room. How do I check if the second room I want to place doesn't overlap with the others? My tought was that you check all the (x,y) variable values in all the room objects and if any of them overlaps it will return false. However I don't know how to refer to all these variables, how can I check the variables in every room object?
Thank you so much for your help!
Place the rooms that are assigned to a place in an ArrayList, so you can loop through them and compare the parameters. I suppose a room does not only have x and y coordinates, but also length and width.
// using a list of rooms that are placed on level
List<Room> assignedRooms = new ArrayList<Room>();
// create a new room (x, y, width, height)
Room newRoom = new Room(0, 0, 100, 100);
assignedRooms.add(newRoom);
// create further rooms
In order to find out whether a room overlaps with another one or not, you best loop through the remaining rooms, i.e., the ones you have already placed within the whole area and check if the x and y coordinates of the newly added room are in conflict with any of the other rooms.
for (int i = 0; i < assignedRooms.size(); i++) {
Room assignedRoom = assignedRooms.get(i);
if (assignedRoom.x < roomToAdd.x && assignedRoom.x + assignedRoom.width > roomToAdd.x)
// overlap
return false;
else if (assignedRoom.y < roomToAdd.y && assignedRoom.y + assignedRoom.height > roomToAdd.y)
// overlap
return false;
}
return true;

populate gridview from bottom left

I'm looking for a way to populate a gridview from the bottom left going across and up rather than the top left going across and down, but also still be able to use pointToPosition(x, y) to get the correct element in the array (so bottom left would be 0).
I'm not entirely sure if this is possible or not but I guess it must be, however I can't think of any way to do it without messing up the ability to find the array indices properly. Any help would be appreciated.
here is the code to get the string array used to fill the grid:
int num = 0;
//populates a standard array from the grid in the JSONObject
for (int vertical = 0; vertical < puzzleArray.size(); vertical++) //rows
{
for (int horizontal = 0; horizontal < puzzleArray.get(0).length(); horizontal++) //columns
{
//adds each letter of each row stored in puzzleArray to puzzleInputArray
puzzleInputArray[num] = puzzleArray.get(vertical).charAt(horizontal) + "";
num++;
}
}
The puzzleArray comes in as 9 strings of 9 letters which are then separated into a seperate array with the code above.
I fill the GridView with a standard ArrayAdapter:
//fill GridView with the puzzle input array from the puzzle class
ArrayAdapter<String> gridAdapter = new ArrayAdapter<String>(c, R.layout.cell_layout, todaysPuzzle.puzzleInputArray);
wordsearchGrid.setAdapter(gridAdapter);
And I need to be able to call the equivalent of this on the grid:
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
startPosition = wordsearchGrid.pointToPosition((int)downX, (int)downY);
letterDown = (String) wordsearchGrid.getItemAtPosition(startPosition);
Thanks.
to solve your problem, you simply have to use more advances techniques to create your adapter.
Writing an adapter in one line of code is great, but to get a more customized experience of adapting your array to a gridView, you will have to write a BaseAdapter yourself.
From there, it will be quite simple, you can for example have two arrays as its member variables, one to store the "real" indexes, and one to the "displaying" indexes.
Hope I helped you :) !

How to make a hitbox?

I'm making a game similar to mario and I've got this map generated by arrays and images. But my problem is that I don't know how to make a hitbox system for all the tiles. I've tried to have a position based collision system based on your position on the map
like this
if(xpos > 10*mapX && xpos < 14 * mapX){
ypos -= 1;
}
But I don't want to that for every wall or hole.
So is there a way to check in front, below and above the character to see if there is a hitbox there and if there is you cant move that direction or fall?
Thank you
If it's a simple 2D game, I'd suggest dividing the map into square tiles. You could store the map in the memory as a two dimensional array and during each frame check tiles adjacent to the player. Of course he can occupy as much as 4 tiles during movement, but it makes you check only up to 12 positions, which can be easily done.
Further collision checking can be done easily using image position and dimension.
Remember that there is no need to check if a static object (environment) is colliding with something, you just need to check objects that have made a move since last frame, i.e. the player and sprites.
EDIT:
Let's say you've got the following section of map (variable map):
...
.pe
ooo
where
. = nothing
p = player
o = floor
e = enemy
you also have the pair (x, y) representing tile indices (not exact position) of the player. In this case you have to do something like this:
if ("o".equals(map[y + 1, x + 1]))
//floor is under
if ("e".equals(map[y, x + 1]))
//enemy is on the right
if ("o".equals(map[y - 1, x]))
//floor is above us
If any of these conditions are met, you have to check image positions and handle collisions.
Note: clicked submit way after the last post was made...
As Mateusz says a 2D array is best for this type of game:
e.g. using chars:
0123456789012
0 ==
1 * ===
2===== =======
So in this case tileMap[8][1] == '*'. You'd probably be best using an enumeration instead of chars though e.g. Tile.SPRING for a Sonic style spring board.
If your map was made up of regular sized tiles you could say:
int xInFrontOfPlayer = playerX + PLAYER_WIDTH;
int xBehindPlayer = playerX - PLAYER_WIDTH;
Tile tileInFrontOfPlayer = getTileAtWorldCoord(xInFrontOfPlayer, playerY);
Tile tileBehindPlayer = getTileAtWorldCoord(xBehindPlayer, playerY);
...
public Tile getTileAtWorldCoord(int worldX, worldY) {
return tileMap[worldX / TILE_WIDTH][worldY / TILE_HEIGHT];
}
Where TILE_WIDTH and TILE_HEIGHT are the dimensions of your tiles in pixels. Then use similar math for yAbovePlayer and yBelowPlayer.
You might then have some logic in your game loop:
if user is pressing the "go right" key:
if the tile to the right is Tile.SPACE:
move player right
else if the tile to the right is Tile.WALL:
don't do anything
if the tile below is Tile.SPACE:
fall

Categories