How to change RGB colour depending on mouse position in Processing3? - java

I am writing a little program in Processing3 that enables me to change the background to a specific colour RGB code stored in arrays. Each vale for R, G and B is stored in a separate array.
Changing the mouse horizontal position changes the colour of the background.
However this solutions code is quite repetitive, and there is a lot of if/else statements. I want to use a for() loop to simplify the code and make it less repetitive. However, i am struggling to include the mouse position variable in the for() loop. Is there to simplify this code using a for() loop and somehow map the mouse position to access array items? This is the code I have right now:
int[] r = {255,249,240,233,227};
int[] g = {115,138,157,173,187};
int[] b = {0,18,63,94,120};
void setup() {
size(500, 500);
}
void draw() {
int x = mouseX;
if(x >= 0 && x <=100) {
background(r[0], g[0], b[0]);
}
else if (x >= 101 && x <= 200){
background(r[1], g[1], b[1]);
}
else if (x >= 201 && x <= 300){
background(r[2], g[2], b[2]);
}
else if (x >= 301 && x <= 400){
background(r[3], g[3], b[3]);
}
else {
background(r[4], g[4], b[4]);
}
}
I wish to simplify the code to something more like this:
int[] r = {255,249,240,233,227};
int[] g = {115,138,157,173,187};
int[] b = {0,18,63,94,120};
void setup() {
size(500, 500);
}
void draw() {
for(int i=0; i<r.length; i++) {
background(r[i],g[i],b[i]);
}
}
However, I don't know how to change this code in a way, that the background colour would change depending on mouse horizontal position, as it is shown in the first example.
Thank you for your reply and help!

If your steps between your different values are 100, then you can just divide the input X value by 100. Integer division will take care of the rest.
The if statement is just to make sure it stays within the bounds of your array.
int mouseX = ...;
int i = mouseX / 100;
if(i < r.length && i < g.length && i < b.length)
{
background(r[i], g[i], b[i]);
}

Related

Ant on a Chess board

currently my program is only always giving me 4, how can I determine how many steps the ant took to cover the whole board? The ant can walk up down left right, but can't walk off the board, and then do this simulation 4 times.
public static void main(String args[]) {
int[][] grid = new int[8][8];
int count = 0;
int x = 0;
int y = 0; // arrays are 0 based
while(true)
{
int random = (int)Math.random()*4+1;
if (random == 1)
{
x--; // move left
}
else if (random == 2)
{
x++; // move right
}
else if (random == 3)
{
y--; // move down
}
else if (random == 4)
{
y++; // move up
}
if(x < 0 || y < 0 || x >= grid.length || y >= grid[x].length) break;
count++;
grid[x][y]++;
}
System.out.println("Number of Steps in this simulation: " + count); // number of moves before it fell
}
}
The problem is this expression:
int random = (int)Math.random()*4+1;
Through the explicit cast, only Math.random() ist casted to int. But since Math.random() returns a dobule < 1, it is casted to 0 and thus random is always 1 and the method always returns 0.
The problem can be fixed by casting Math.random() * 4:
int random = (int) (Math.random() * 4) + 1;
The parenthesis enforce that the value of Math.random() * 4 (which will be a value in the interval [0, 3)) will be casted to int.
Two remarks on your code:
I would recommend introducing an enum Direction with four values (one for each direction) and choose a random Direction by calling Direction.values()[(int) (Math.random() * 4)];
I would recommend to use a switch instead of the if-else-if cascade.
Ideone demo
The program will exit the while(true) loop once one of the 4 conditions is true. My suggestion is to move these conditions in your if(random == value) checks like this:
if( random == 1 )
{
x--;
if (x < 0 )
{
x++;
}
}
Now to exit your while(true) loop you need to have an extra condition. I would suggest to think about your board in terms of 0's and 1's. Everytime the ant cross a cell, you set the grid[x][y] = 1.
int stepsTaken = 0;
int cellsToCover = grid.length * grid[0].length ;
int coveredCells = 0;
while(true)
{
//your code here
if( random == 1 )
{
stepsTaken++;
x--;
if (x < 0 )
{
x++;
}
}
// the other if's with "stepsTaken" incremented too.
if ( grid[x][y] == 0 )
{
grid[x][y] = 1;
coveredCells++;
}
if (coveredCells == cellsToCover )
break;
}
But please notice the many ifs statements inside a while(true) loop. If you have to fill a board of 10 rows x 10 columns it would take too much until the board is filled. Instead I would suggest you to use some more efficient algorithms like backtracking, dynamic programming etc.
Edit : Added step counter.

Trying to draw axes for Quadrant I, getting Quadrant IV instead

Currently, I am trying to create a program that draws a square anywhere in a 15x15 Quadrant I (Coordinate plane) grid. I am stuck on trying to get the axes displaying correctly.
This is the code I have thus far:
import java.util.Scanner;
public class Question2square {
public static void main(String[] args) {
// Axis variables
int yAxismin = 0;
int yAxismax = 15;
int xAxismin = 0;
int xAxismax = 15;
//Loop through all coordinates on plane using for loops
for(int y = yAxismin; y <= yAxismax; y++)
{
for(int x = xAxismin; x <= xAxismax; x++)
{
//Draw the axis
if (!Axis(x,y).equals("")) {
System.out.print(Axis (x,y));
}
}
System.out.println("");
}
}
// This method draws the 15x15 axis
public static String Axis(int x, int y)
{
// Each if and else if statement dictates what symbol needs to go where for the axes
// If there is nothing to be drawn, there will simply be a blank space
if (x == 15 && y== 0) return ">";
else if(x == 0 && y == 15) return "^";
else if (x == 0 && y == 0 )return ".";
else if(x == 0 && y >= 0) return "|";
else if(x >= 0 && y==0) return "-";
else return "";
}
/*
// Method to be used to draw actual square
public static ... drawSquare(...) {
}
*/
}
Unfortunately, instead of drawing the 'L' shaped axes I desire, it displays an 'r' shape instead. I'm trying to figure out how to display the axis properly.
I tried flipping the for loops but that didn't help. I don't see what else could be inhibiting this.
Try reversing the y loop:
for(int y = yAxismax; y >= yAxismin; y--) ...
As your loop prints lines to the console from "top to bottom" and then "left to right", you want your greatest value of y to come first and your least value of x to come first. Therefore you only need to reverse the y loop to go from yAxismax to yAxismin. The result (for limits of 3 and not 15 is then:
^
|
|
.-->

java: tetris random block generated upon row clear

I'm trying to make the game Tetris in java.
I've gotten it to the point where:
a new block is generated when it hits the floor or its y+1 is not null (meaning there's another block under it)
public void collisionCheck(int x, int y) {
if (activetile.getY() == this.height-2 || getTileAt(x, y+1) != null) {
activetile = new Tile(this, 0, 0);
}
}
A row clears when the bottom row is full of non-null values, or the Tetris pieces (for y = 4 (the floor), loop through x till x = 4 and check if all non-null)
public void checkBottomFull(int x, int y) {
while (getTileAt(x,y) != null) {
say("(" + x + ", " + y +")");
if (x == 3) {
say("row is full");
//replace full row with tiles from above
for (int i = 0; i < 4; i++) {
for (int j = 5; j > 0; j--) {
grid[j][i] = getTileAt(i,j-1);
grid[j-1][i] = null;
}
}
break;
}
x++;
}
}
Right now, I'm using keys to move the block:
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_DOWN) {
activetile.setLocation(activetile.getX(), activetile.getY()+1);
System.out.println("coordinates: " + activetile.getX() + ", " + activetile.getY());
collisionCheck(activetile.getX(),activetile.getY());
checkBottomFull(0,4);
repaint();
}
}
There's two issues I'm having:
1) In the picture you'll notice I've dropped the block all the way to the floor... and the row cleared. After it's cleared, it will generate a block to the top left (x=0, y=1) which I have no control over.
2) On the floor there seems to be a red line... which I'm assuming is a row of blocks hidden by the JFrame... I'm not sure why that's there.
FYI: If you're wondering why grid[j][i] has the rows and columns flipped (aka, why it's not grid[i][j]) is because I instantiated it as grid = new Tile[height][width];
Any thoughts?
Thanks!
It is hard to say what is wrong without actually debugging your app.
But maybe try this one:
public void checkBottomFull(int x, int y) {
while (getTileAt(x,y) != null) {
say("(" + x + ", " + y +")");
if (x == 3) {
say("row is full");
//replace full row with tiles from above
for (int i = 0; i < 4; i++) {
for (int j = 4; j >= 0; j--) {
grid[j][i] = getTileAt(i,j-1);
grid[j-1][i] = null;
}
}
break;
}
x++;
}
}
You have 5 rows (indexed from 0 to 4) and 4 columns (indexed from 0 to 3).
What values of height and width do you pass to:
grid = new Tile[height][width];
Because from what I see you should do something like that:
grid = new Tile[5][4];
Bah,
Turns out in the key event, I needed to check if the bottom was full before checking if there is a collision.
I guess what was happening is, when I was checking collisionCheck(activetile.getX(),activetile.getY()); before checkBottomFull(0,4);, when the bottom was full, it would clear the row and set the current row equal to the row above it: grid[j][i] = getTileAt(i,j-1);, the problem was that collisionCheck was generating a new piece and the that newly generated piece was getting cleared and replaced by checkBottomFull.
Putting the collision check after the checkBottomFull ensures that the newly generated piece won't be replaced if bottom is full.

Why is this flood-fill algorithm not working?

For this question: Is there a proper algorithm for detecting the background color of a figure?, I will need to create a flood-fill algorithm to be able to separate all my pixels in groups of the same color.
I did this recursively, but it gives me a stack-overflow error. So I had to choose the iterative, queue based algorithm found here: http://en.wikipedia.org/wiki/Flood_fill#Alternative_implementations
First of all, I begin a search over all the matrix elements (elements being instances of the Pixel class).
private PixelGroup[] generatePixelGroupsFromMatrix(Pixel[][] matrix) {
PixelGroup[] tempGroups = new PixelGroups[9999999]; // Nevermind the 9999999....
int groupsFound = 0;
Pixel pixel;
for (int y = 0; y < matrix.length; ++y) {
for (int x = 0; x < matrix[0].length; ++x) {
pixel = matrix[y][x];
if (!pixel.evaluated) {
// This pixel has never been evaluated
// Therefore, it belongs to a new group
// First, we make a new group
PixelGroup newGroup = new PixelGroup();
// Begin search for connected pixels with the same color. All pixels found will belong to this new group.
findPixelsConnectedWith(pixel,newGroup);
tempGroups[groupsFound] = newGroup;
++groupsFound;
}
}
}
PixelGroup[] result = new PixelGroup[groupsFound];
for (int i = 0; i < groupsFound; ++i) {
result[i] = tempGroups[i];
}
return result;
}
So, Pixel has the following values: x, y, evaluated (boolean) and color (integer).
Then, PixelGroup is simply a class capable of holding pixels (it works).
And this is the method that is giving me trouble:
private void findPixelsConnectedWith(Pixel pixel, GroupOfPixels group) {
QueueOfPixels queue = new QueueOfPixels();
queue.add(pixel);
Pixel currentPixel;
int x,y;
Pixel neighbor;
while((currentPixel = queue.nextPixel()) != null) {
if (currentPixel.color == pixel.color && !currentPixel.evaluated) {
// This pixel has the required color, and has not been evaluated. It meets our needs.
// Add to group.
group.addPixel(currentPixel);
// Flag it as evaluated. So in the future, it will be ignored.
currentPixel.evaluated = true;
// Evaluate all 8 possible directions to find neighbor pixels
int[] xDirections = {0,1,1,1,0,-1,-1,-1};
int[] yDirections = {-1,-1,0,1,1,1,0,-1};
for (int i = 0; i < 8; ++i) {
x = xDirections[i];
y = yDirections[i];
if (pixelExists(currentPixel.y + y,currentPixel.x + x)) {
// There exists a pixel in this direction!
neighbor = getPixel(currentPixel.y + y,currentPixel.x + x);
queue.add(neighbor);
}
}
}
}
}
If you're curious, here is my QueueOfPixels class. I had to make my own with only vectors (school assignment requirement): https://codereview.stackexchange.com/questions/17823/vector-based-flood-fill-algorithm-queue-class (as far as I can tell, it simply works).
WHAT IS THE PROBLEM?
Alright, I have tested this with this image, which is 5x2 pixels (you'll need to zoom in a lot to see it): http://i.stack.imgur.com/xV0Lf.gif - the first row only has black pixels, and the second they're white. The program tells me it has found 6 pixel groups (when it should have been only 2!)
WHAT HAVE I TRIED TO DEBUG THE PROBLEM?
Well, first, before calling findPixelsConnectedWith, I placed this line:
System.out.println("The pixel (" + x + "," + y + ") has not been evaluated. Evaluating now.");
And this was the result:
The pixel (0,0) has not been evaluated. Evaluating now.
The pixel (1,0) has not been evaluated. Evaluating now.
The pixel (2,0) has not been evaluated. Evaluating now.
The pixel (3,0) has not been evaluated. Evaluating now.
The pixel (4,0) has not been evaluated. Evaluating now.
The pixel (0,1) has not been evaluated. Evaluating now.
So, as you can see, it seems like the code is unable to work with the first row (black pixels) since it thinks that every pixel in that row has not been evaluated (I expected it to say that (0,0) was not evaluated and done). But when it starts working with the second row, it does seem to work as expected (find (0,1) and then it is over).
But I still am unable to find out what is going on. Any ideas?
Edit:
My getPixel and pixelExists functions:
private boolean pixelExists(int y, int x) {
return (y > 0 && y < pixelMatrix.length) && (x > 0 && x < pixelMatrix[0].length);
}
private Pixel getPixel(int y, int x) {
return pixelMatrix[y][x];
}
Your pixelExists method should use y >= 0 and x >= 0 instead of y > 0 and x > 0.
private boolean pixelExists(int y, int x) {
return (y >= 0 && y < pixelMatrix.length) && (x >= 0 && x < pixelMatrix[0].length);
}
This may not be the only problem, but it will certainly prevent you from getting the correct answers.
Maybe pixelExists method has "y > 0" part while it should has "y>=0"?

When there is two for() loop, the second one doesn't work

Here are my for() loops :
public void showMovementCase(){
int movePlusAttack = moveAllowed+attackDistance;
int twiceMoveAllowed = (moveAllowed)*2;
for(int i = 0; i <= movePlusAttack*2; i++){
for(int j = 0; j <= movePlusAttack*2;j++){
boolean a = movePlusAttack <= j+i && movePlusAttack >= j-i && i <= movePlusAttack;
boolean b = movePlusAttack <= j+i && movePlusAttack >= i-j && i > movePlusAttack && j <= movePlusAttack;
boolean c = movePlusAttack*3 >= j+i && movePlusAttack >= j-i && i > movePlusAttack && j >= movePlusAttack;
if(a || b || c){
try{
actionSquare[i][j] = new JLabel();
actionSquare[i][j].setIcon(redsquare);
actionSquare[i][j].setBounds(sprite.getX()+(i-movePlusAttack)*16,sprite.getY()+(j-movePlusAttack)*16, 16, 16);
panel.add(actionSquare[i][j], new Integer(1));
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("red :" + e);}
}
}
}
for(int x = 0; x <= twiceMoveAllowed; x++){
for(int y = 0; y <= twiceMoveAllowed;y++){
boolean a = moveAllowed <= y+x && moveAllowed >= y-x && x <= moveAllowed;
boolean b = moveAllowed <= y+x && moveAllowed >= x-y && x > moveAllowed && y <= moveAllowed;
boolean c = moveAllowed*3 >= y+x && moveAllowed >= y-x && x > moveAllowed && y >= moveAllowed;
if(a || b || c){
try{
actionSquare[x][y].setIcon(bluesquare);
System.out.println("Coucou !");
actionSquare[x][y].addMouseListener(mouse);
panel.repaint();
panel.revalidate();
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("blue :" + e); }
}
}
}
}
if this.attackDistance is different of 0, then the second loop doesn't work (it seems to stop at the .setIcon() command).
Do you know a way to fix this ?
Thanks for reading.
Edit:
with :
try{
actionSquare[x][y].setIcon(bluesquare);
System.out.println("Coucou !");
[...]
}
On the second loop, nothing is printed.
but with :
try{
System.out.println("Coucou !");
actionSquare[x][y].setIcon(bluesquare);
[...]
}
"Coucou !" is printed once.
That's why I said that "it seems to stop at the .setIcon() command" I should have said that sooner, sorry.
Here are a few tips:
don't catch exceptions and do nothing with them. That's what you are doing here in both loops, and so it's normal you don't see the error message.
anytime you see long statements like you have, it should be a hint that you could refactor it. For example, create a separate method that validates whether or not you're going to do something in your loop, and then inside the main method you'd call it like if(shouldPerformAction())
consider using less than 8 spaces for indentation. This just eats up your screen real estate.
consider making computations before the loops instead of inside the loop conditions, if the computation is supposed to be fixed (for example this.moveAllowed*2)
imho, no point in prefixing all your methods/fields with this, it just clutters everything. Just call the methods directly.
This is a very, very bad idea:
catch(ArrayIndexOutOfBoundsException e){}
You effectively tell the JVM to ignore any problems with your arrays that it detects. And worse than that: you don't even print anything when that happens.
Put at least a e.printStackTrace() in there to see if a problem occurs and where.
And as a further step: fix your array access to not exceed any limits. Catching an ArrayIndexOutOfBoundsException is a terribly bad idea. Avoid having it thrown at all!
Hmmm... where to begin...
I would first suggest putting something (System.err.println(...)?) inside of your catch blocks. Or just commenting them out entirely so you'd see the full stacktrace. What if you're hitting an exception and just not seeing it?
catch(ArrayIndexOutOfBoundsException e){}
This is a bad practice for two reasons:
You should never catch RuntimeException. It is just a very helpful indicator for errors in code logic (i.e. developer errors) which ought be solved by writing good code.
You should never ignore e unless you know perfectly what you're doing. Add at least an e.printStackTrace() so that you at least know that something failed.
I cleaned up your code for you. Generally, when you have two sections of code that are supposed to be doing the exact same thing, but are not, then rolling them into one method can eliminate that possibility.public void showMovementCase(){
// probably want to remove anything left over from the last invocation
panel.removeAll();
for (JLabel[] array : actionSquare) Arrays.fill(array, null);
colorSquares(moveAllowed + attackDistance, redsquare, null);
colorSquares(moveAllowed * 2, bluesquare, mouse);
for (int x = 0; x < actionSquare.length; x++)
for (int y = 0; y < actionSquare[x].length; y++)
if (actionSquare[x][y] != null) panel.add(actionSquare[x][y], 1);
}
private void colorSquares(int move, Icon color, MouseListener mouse) {
int xMax = Math.min(2 * move, actionSquare.length);
int yMax = Math.min(2 * move, actionSquare[0].length);
for (int x = 0; x < xMax; x++) {
for (int y = 0; y < yMax; y++) {
if (isLegal(x, y, move)) {
if (actionSquare[x][y] == null)
actionSquare[x][y] = new JLabel();
actionSquare[x][y].setIcon(color);
actionSquare[x][y].setBounds(
sprite.getX() + (x - move) * 16,
sprite.getY() + (y - move) * 16, 16, 16 );
if (mouse != null) actionSquare[x][y].addMouseListener(mouse);
}
}
}
}
private static boolean isLegal(int x, int y, int move) {
// informative comment explaining why this mess makes sense
if (move <= y+x && move >= y-x && x <= move) return true;
// informative comment explaining why this mess makes sense
if (move <= y+x && move >= x-y && x > move && y <= move) return true;
// informative comment explaining why this mess makes sense
if (move * 3 >= y+x && move >= y-x && x > move && y >= move) return true;
return false;
}

Categories

Resources