Even distribution of colours - java

It's a pretty basic question however I can't understand it very well I'm afraid.
What I'm trying to do is spawn squares a certain colour out of 3 colours. each colour has it's own number value (-1, 0, 1) what I will then do is add that to a 2D array making a grid of squares.
For blue, it's a 1/4 chance. For red it's a 1/4 chance. For white it's a 1/2 chance.
I understand how to use Java's Random class, however I'm not quite sure how to implement what I'm looking for.
Could someone point me in the right direction?

Create a (1D) array the size of the number of squares, put the proportionate number of each colour into the array, random sort it (Collections.shuffle), and then pop them all off and into your 2D array.

Could someone point me in the right direction?
Create a square 2D array of int's: int[][] matrix = new int[SIZE][SIZE]
Fill it using random numbers from 0 to 3
CORRESPONDENCES (for example)
0-1 yellow
2 blue
3 red
Iterate over the 2D array and in each iteration:
draw a rectangle
increase y value (position) in each inner iteration and x in outer
assign color depending the value of the array.
HOW? Executing something like this method each iteration
//this will draw a square of size 50 at position x,y colored
public void paint(Graphics g, int color){
switch (color) {
case 2:
g.setColor(Color.blue);
break;
case 3:
g.setColor(Color.red);
break;
default:
g.setColor(Color.yellow);
break;
}
g.drawRect(x,y,50,50);
}
That's it, I think you have enough to achieve your goal.

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<>();

find the minimum and maximum distance between 2 rectangles of any dimension

I have a Rectangle class that represents a d-dimension rectangle with 2*d numbers for every dimension. For every dimension i have a lower and an upper bound. Dimensionality stores the number of dimensions of the rectangle, and for the lower and upper bounds i use a double array.
I want to create 2 methods that they have as input another rectangle object of the same Dimensionality and return the minimum and maximum distance between the rectangles, im trying to do this using the minimum/maximum distances of each of their projections in every axis. I also have a method that creates the projections.
//returns 2 position array
public double[] project(int x)
{
//x is the selected dimension
double proj[] = new double[2];
proj[0] = this.lb[x];
proj[1] = this.ub[x];
return proj;
}
you can see on the third set of shapes what i want to do more clearly
https://s15.postimg.org/l8aijyl1n/imageedit_2_6689786765.jpg
Find mutual orientation of rectangles (as direction of vector between centers, it is enough to get signs of center.x and center.y differences)
Depending on orientation quadrant, get distances from selected edges of the first rectangle to selected edges of the second. Using signs of these distances, find extremal distances:
For the case at the picture (direction in the 4th quadrant) one have to check distances from right bottom corner of the first rectangle to the left and top edges of the second one, and from left top corner of the second - to the right and bottom edges of the first one.
min_dx = rect2.left - rect1.right
min_dy = rect2.top - rect.bottom
if both values > 0 (++ case)
min_dist = sqrt(min_dx^2 + min_dy^2) //corner-corner case
+- case
min_dist = min_dx
-+ case
min_dist = min_dy
-- case
min_dist = 0
Seems the same approach might be used for higher dimensions. Number of cases becomes too high, so it is worth to select planes for checking with indexes corresponding to center-center direction vector components' signs

drawing random image libgdx

I am learning java game development with libgdx and have the following issue.
I have a Rectangle array which I iterate through and draw an image according to the position of the rectangle.
My Questions is how do I draw a random image every render but still keep drawing the same random image until it leaves the screen. currently it is drawing the same image but I would like know how to draw a different pipe image every iter.
Thank you
My Iterator
Iterator<Rectangle> upperIter = upperPipes.iterator();
while(upperIter.hasNext()) {
Rectangle upperpipe = upperIter.next();
upperpipe.x -= 8 * Gdx.graphics.getDeltaTime();
if(upperpipe.x < -32) upperIter.remove();
My draw method
public void drawPipes(){
batch.begin();
for(Rectangle upperPipe: Pipes.lowerPipes) {
batch.draw(Assets.pipeImg, upperPipe.x, upperPipe.y, upperPipe.width, upperPipe.height);
batch.end();
}
One great way to get repeatable random data is to use a Random object (java.util.Random is suitable for game usage), and provide it with a non-random seed. Each time you put in the seed and request the same sequence of number types+ranges, you will get the same (psuedo-)random numbers. When you want different numbers, just change the seed.
As an example:
Random rand = new Random(1234);
System.out.println(rand.nextInt()); // an int from Integer.MIN to Integer.MAX
System.out.println(rand.nextInt(100)); // an int from 0 to 100
Will always output the following, every single time.
-1517918040
33
But change the seed (in the constructor for Random), and the output values will change. rand.setSeed(seed) will reset the Random to start its sequence over.
You could use this to produce the same set of random numbers over and over while the rect is on screen.
However, a more direct and simple way would be to to just generate one random number for each rect when it is created, and store that number until it leaves:
public void drawPipes(){
for(int i = 0; i<Pipes.color.size; i++){
num = Pipes.color.get(i);
}
for(Rectangle bottomPipe: Pipes.lowerPipes) {
switch(num){
case 0:
batch.draw(Assets.redPipeImg, bottomPipe.x, bottomPipe.y, bottomPipe.width, bottomPipe.height);
break;
case 1:
batch.draw(Assets.yellowPipeImg, bottomPipe.x, bottomPipe.y, bottomPipe.width, bottomPipe.height);
break;
}
}
}
SOLVED!!
I created a custom pipe class and just created an array of pipes, each new pipe object that went into the array took a random image.
I iterated through the array, and called the draw method on each pipe object.
Simple and it works perfect

how to calculate image gradient

My instructor gave us the pseudocode:
grad = abs(im(x+1,y)-im(x-1,y)) + abs(im(x,y+1)-im(x,y-1))
to calculate the gradient of an image for an edge detector we are making. I thought that the way this pseudocode would look like is:
int grad = Math.abs(img.getRGB(i+1,j)-img.getRGB(i-1,j)) +
Math.abs(img.getRGB(i,j+1)-img.getRGB(i,j-1));
he said this code would only get the R value of a color. I'm having trouble understanding this. Could someone help me understand how to use this formula to get an entire color gradient? (this formula would go in a nested for loop and apply to every pixel)
Your instructor means that you need to get the Red for each pixel. You can either fiddle with the bits that are returned from getRGB(x, y) to get just the red, or you can put the RGB value into a Color and extract it that way.
public int getRed(BufferedImage image, int x, int y)
{
// Color color = new Color(image.getRGB(x, y), true); if you care about alpha
Color color = new Color(image.getRGB(x, y));
return color.getRed();
}
This will give you a value between [0, 255]. If you want a value between [0, 1], then you need to divide by 255.0.
Bit shifting would be a faster solution, but this is the easier solution and it is likely fast enough. For reference, red would be bits [16, 23].

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