Return outside method error - java

boolean openingboard;
{
Robot robot = new Robot();
Color color3 = new Color(108, 25, 85);
Rectangle rectangle = new Rectangle(0, 0, 1365, 770);
while(true)
{
BufferedImage image = robot.createScreenCapture(rectangle);
search: for(int x = 0; x < rectangle.getWidth(); x++)
{
for(int y = 0; y < rectangle.getHeight(); y++)
{
if(image.getRGB(x, y) == color3.getRGB())
{
System.out.println("About to finish and return true");
return true;
}
System.out.println("About to finish and return false");
}
}
}
}
the error is:
java:71: return outside method
return true
^
i don't know what this is happening please help!

From your comment response above, I am going to make the educated guess that you believe that
boolean openingboard;
{
return true;
}
defines a Java method called openingboard. This isn't the case. Java follows the C paradigm of requiring you to specify your parameters in parentheses, regardless of whether you have any parameters or not. So, the method
boolean openingboard() {
return true;
}
is a valid Java method (assuming it is inside some class), as is a version of openingboard with much more code between the curly braces.
That said, I'm going to pass along a few friendly pointers on Java style:
Java (and indeed most higher-level language) programmers tend to frown on "forever" loops such as while (true), since those loops make it much harder to determine when the loop actually stops.
There is no need for the label search in the code, and labels are even more discouraged than forever loops are.
So, I would recommend rewriting your code to look something like
private boolean openingboard() {
Robot robot = new Robot();
Color color3 = new Color(108, 25, 85);
Rectangle rect = new Rectangle(0, 0, 1365, 770);
BufferedImage image = robot.createScreenCapture(rect);
for(int x = 0; x < rectangle.getWidth(); x++) {
for(int y = 0; y < rectangle.getHeight(); y++) {
if(image.getRGB(x, y) == color3.getRGB())
return true;
}
}
return false;
}
assuming of course that you prefer a debugger to trace prints.

Proper methods look like: boolean openingboard ( )
not like boolean openingboard;
The parenthesis are not optional.
The way you have it: openingboard is a field. There is a init block with a Robot and a color and some for loops nested inside of each other. Inside one of the for loops is a return which is not allowed in an init block.

Related

How do I target my random colour variable in my IF statement?

I have a question that is leading from the chosen best answer from my previous post:
How can I use randomisation to specify different object parameters to a single iteration in a loop? I'm new to stack and wasn't sure of the best way to reference that post.
I have the code written as advised from the post above, however, now I'm attempting to have a method run different lines of code based off the colour of the 'brick' that is interacted with via my 'ball' object:
public Color brickColour;
public GameObj( int x, int y, int w, int h, Color c ){
topX = x;
topY = y;
width = w;
height = h;
colour = c;
}
public void initialiseGame(){
Random random = new Random();
int yellowBrick = random.nextInt(5);
for (int i = 0; i < 5; i++) {
brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, brickColour);
brick.moveX(75);
brick.visible = true;
bricks.add(brick);
System.out.println("Model:: Create Brick =" + brick);
}
}
public synchronized void updateGame(){
for(GameObj brick: bricks){
if (ball.hitBy(brick)){
if(brickColour.equals(Color.YELLOWGREEN)){
ball.changeDirectionY();
addToScore(HIT_BRICK);
brick.visible = false;
Debug.trace("Model::Brick Hit YELLOWGREEN = " + brick);
startGame();
}else {
ball.changeDirectionY();
addToScore(HIT_BRICK);
brick.visible = false;
Debug.trace("Model::Brick Hit = " + brick);
}
}
}
}
I have tested the program and when the YELLOWGREEN 'brick' is hit, it's still running the else statement. I then printed the brickColour variable and got "0x0000ffff", though, even using that as a string in the color.equals() parameters, it didnt work. How exactly can I target the yellowgreen brick object?
Your problem lies in this:
brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
You have defined a global variable here and are using whatever the most recent set of this is. You should make this a local variable and not re-use it between methods.
for (int i = 0; i < 5; i++) {
Color brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, brickColour);
// omitted for answer
}
Then when doing your check:
for(GameObj brick: bricks){
if (ball.hitBy(brick)){
if(brick.brickColour == Color.YELLOWGREEN) {
// yellow logic
} else {
// blue logic
}
}
}
Of course, using the colour itself is a rather poor design decision to begin with. Instead, you would want to have a property of the GameObj that declares its brick type, and have the colour determined by the brick type. But that's tangential to this discussion.
The lesson here is to make your variables scoped only to what is necessary. Don't use a global if you don't need to, use locals wherever you can.

Arraylist no overlapping graphics

I am creating a game program where I need to run through an array list of circle graphics set at x and y coordinates. I need to make sure that none of the circle graphics overlap each other. This is what i have and seems to work sometimes but I think it is creating an infinite loop. Would love if someone could help me with my code.
for (int i = 0; i < circles.size(); i++) {
if (circles.isEmpty()) {
graphic.setX(x);
graphic.setY(y);
continue;
}
if (this.graphic.isCollidingWith(circles.get(i).graphic)) {
x = rng.nextInt((int)Engine.getWidth());
y = rng.nextInt((int)Engine.getHeight());
i = -1;
}
else {
graphic.setX(x);
graphic.setY(y);
}
}

Game of Life in Processing

I want to code my own version of "game of life", in processing 3, but I've come across an error I don't seem to understand. Whenever the code run, the screen keeps going black and white with a few pixels changing but it does not look like game of life.
Any help?
int windowW, windowH, percentAlive, gen;
//windowW is the width of the window, windowH is the height
//percentVlive is the initial percent of alive pixel
//gen is the counter for the generation
color alive, dead;//alive is white and dead is black to represent their respective colors
boolean[][] cells0, cells1;//two arrays for the state of the cells, either alive or dead
boolean zeroOrOne = true;//this is to check which array should be iterated over
void setup() {
size(700, 700);
int width = 700;
int height = 700;
windowW = width;
windowH = height;
percentAlive = 15;
alive = color(255, 255, 255);
dead = color(0, 0, 0);
cells0 = new boolean[width][height];
cells1 = new boolean[width][height];
frameRate(2);
background(alive);
for (int x=0; x<width; x++) {//set the percent of live pixels according to the precentAlive varriable
for (int y=0; y<height; y++) {
int state = (int)random (100);
if (state > percentAlive)
cells0[x][y] = true;
else
cells0[x][y] = false;
}
}
}
void draw() {
gen += 1;//increases the generation every time it draws
drawLoop(zeroOrOne);
WriteGeneration(gen);
if(zeroOrOne){//changes the zeroOrOne value to change the array being iterated over
zeroOrOne = false;
}
else {
zeroOrOne = true;
}
}
void WriteGeneration(int number) {//changes the label on top
fill(0);
rect(0, 0, windowW, 100);
fill(255);
textFont(loadFont("BerlinSansFB-Reg-100.vlw"));
text("Generation " + number, 10, 90);
}
void drawLoop(boolean check) {
loadPixels();
if (check) {//checks which array to iterate thrgough
for (int x = 0; x < windowW; x++) {//iterates through the array
for (int y = 0; y < windowH; y++) {
if (cells0[x][y]) {//checks wether the pixel is alive or dead
pixels[x * 700 + y] = alive;//gets the current pixel
int lives = lives(x, y, check);//checks how many cells are alive around the current cell
if (lives<2) {//these are supposed to put in place the game of life rules
cells1[x][y] = false;
} else if (lives>4) {
cells1[x][y] = false;
} else {
cells1[x][y] = true;
}
} else {
pixels[x * 700 + y] = dead;//gets the current pixel
int lives = lives(x, y, check);//checks how many cells are alive around the current cell
if (lives == 3) {//turns the pixel alive if the condition is met
cells1[x][y] = true;
}
}
}
}
} else {//the same as the top but instead the arrays being updated and read are switched
for (int x = 0; x < windowW; x++) {
for (int y = 0; y < windowH; y++) {
if (cells1[x][y]) {
pixels[x * 700 + y] = alive;
int lives = lives(x, y, check);
if (lives<2) {
cells0[x][y] = false;
} else if (lives>4) {
cells0[x][y] = false;
} else {
cells0[x][y] = true;
}
} else {
pixels[x * 700 + y] = dead;
int lives = lives(x, y, check);
if (lives == 3) {
cells0[x][y] = true;
}
}
}
}
}
updatePixels();
}
int lives(int x, int y, boolean check) {//this just checks how many live pixels are around a given pixel
int lives = 0;
if (x > 1 && y >1 && x < 699 && y < 699) {
if (check) {
if (cells0[x-1][y-1])
lives++;
if (cells0[x][y-1])
lives++;
if (cells0[x+1][y-1])
lives++;
if (cells0[x-1][y])
lives++;
if (cells0[x+1][y])
lives++;
if (cells0[x-1][y+1])
lives++;
if (cells0[x][y+1])
lives++;
if (cells0[x+1][y+1])
lives++;
} else {
if (cells1[x-1][y-1])
lives++;
if (cells1[x][y-1])
lives++;
if (cells1[x+1][y-1])
lives++;
if (cells1[x-1][y])
lives++;
if (cells1[x+1][y])
lives++;
if (cells1[x-1][y+1])
lives++;
if (cells1[x][y+1])
lives++;
if (cells1[x+1][y+1])
lives++;
}
}
return lives;
}
Please post your code as an MCVE. When I try to run your code, I get an error because I don't have the font file your'e trying to load on line 59. That font has nothing to do with your problem, so you should really get rid of it before posting a question.
You've got a lot going on in this code. I understand why you have two arrays, but having them both at the sketch level is only over-complicating your code. You shouldn't need to constantly switch between arrays like that. Instead, I would organize your code like this:
You should only have one array at the sketch level. You can also get rid of the zeroOrOne variable.
Initialize that array however you want.
Create a nextGeneration() that returns a new array based on the current array. This will probably call other functions for counting neighbors and whatnot. But the point is that you can just create a new array every time instead of switching between two global arrays.
This removes all of your duplicated logic.
General notes:
Having 8 if statements to check the neighbors is a bit of overkill. Why not just use a nested for loop?
You should get into the habit of following proper naming conventions. Functions should start with a lower-case letter, and variables should be descriptive- naming something check doesn't really tell the reader anything.
If you still can't get it working, then you're going to have to do some debugging. Add print() statements, or use the Processing editor's debugger to step through the code. Which line behaves differently from what you expect? Then you can post an MCVE of just that line (and whatever hard-coded variables it needs to show the behavior) and we'll go from there. Good luck.
The issues you are having are twofold:
The two cells arrays that you have interfere and make two separate games, when you only want one.
You are updating the cells in your arrays before you get to the end of checking which ones need to be modified.
The way to solve both problems at once is to repurpose the cells1 array. Instead of checking it every other time, make it an array set entirely to false. Then, whenever you want to modify a square in cells0, set that location in cells1 to true, and after you make a marker of each cell you want to change, change them all at once with a separate for loop at the end of the drawLoop() method. This solves both problems in one fell swoop.
Once you have done this, you can remove the check and zeroAndOne variables, as you won't need them anymore. This is what I got for the drawLoop() method after I made the modifications I recommend:
void drawLoop() {
loadPixels();
for (int x = 0; x < windowW; x++) {
for (int y = 0; y < windowH; y++) {
if (cells0[x][y]) {
pixels[x * 700 + y] = alive;
int lives = lives(x, y);
if (lives<2) {
cells1[x][y] = true;
} else if (lives>4) {
cells1[x][y] = true;
}
} else {
pixels[x * 700 + y] = dead;
int lives = lives(x, y);
if (lives == 3) {
cells1[x][y] = true;
}
}
}
}
for (int x = 0; x < windowW; x++) {
for (int y = 0; y < windowH; y++) {
if (cells1[x][y]) {
cells0[x][y] = !cells0[x][y];
cells1[x][y] = false;
}
}
}
updatePixels();
}
I'm sure you can figure out the rest. Good luck!

Why is this code giving an "Unreachable Statement" error?

This is my code and im getting an unreachable statement error on it but i do not know why.
public boolean Boardload(String[] args) throws Exception
{
Robot robot = new Robot();
Color color3 = new Color(114, 46, 33);
Color color4 = new Color(180, 0, 0);
{
Rectangle rectangle = new Rectangle(0, 0, 1365, 770);
{
while(false)
{
BufferedImage image = robot.createScreenCapture(rectangle);
search: for(int x = 0; x < rectangle.getWidth(); x++)
{
for(int y = 0; y < rectangle.getHeight(); y++)
{
if(image.getRGB(x, y) == color3.getRGB())
{
return true;
}
}
}
}
}
return false;
}
}
the exact error is:
java:68: unreachable statement
{
^
Help would be nice, this code is supposed to loop until the pixel is found.
I think the problem is that your loop is
while(false) {
This loop never executes, because false != true. Consequently, the Java compiler is telling you that nothing in the body of the loop will ever execute, and hence it's unreachable.
Try changing your loop to
while (true) {
(the idiomatic "loop forever") and see if that fixes things.
Hope this helps!
while(false) is always false and the loop body is never executed: unreachable. Change to while (true).
The statement while(false) will never execute anything within that loop, thus it's all un-reachable.
Sorry, but that is some smelly code. I'm not sure what the braces/blocks are doing after declaring your Color local vars, and after declaring your Rectangle var. The main problem for unreachability is while(false), which means it will never execute the associated block.

if/then with pixel finding and looping, all of which is above me at the moment

I want to take a screenshot, and if the pixel is the correct value RGB then take another screenshot and find next pixel or else repeat.
this is the code to get the pixel and it works like a charm!
{
BufferedImage image = robot.createScreenCapture(rectangle);
search: for(int x = 0; x < rectangle.getWidth(); x++)
{
for(int y = 0; y < rectangle.getHeight(); y++)
{
if(image.getRGB(x, y) == color3.getRGB())
{
break search;
}
}
}
}
what i want to know i guess is how would i go about asking it to repeat this segment of code until the pixel equals the true color. the color i am looking for is:
Color color3 = new Color(114, 46, 33);
Ok context, i am building a program that goes through steps, one opens the given puzzle, i have that down because i can use simple pixel data, then it needs to center the mouse on the center pixel. The problem is i cant just use a second get pixel image because it takes a while for the game to open the relevant jpanel so i need my program to wait until it can find a pixel indicating the game is open before it starts to look for the pixel to center the mouse.
You can probably separate the screenshot code into a method and call it until you get the desired result:
public boolean checkColor(Color inputColor) {
BufferedImage image = robot.createScreenCapture(rectangle);
for(int x = 0; x < rectangle.getWidth(); x++) {
for (int y = 0; y < rectangle.getHeight(); y++) {
if (image.getRGB(x, y) == inputColor.getRGB()) {
return true;
}
}
}
return false;
}
This method will return true if it can find the given inputColor in the screenshot. You might then use it in a loop as follows:
Color newColor = ...;
while (!checkColor(newColor)) {
new Color = new Color(114, 46, 33);
// Or change color in here for every iteration
}
This loop will terminate if it can't match the screenshot to newColor.

Categories

Resources