Boolean fuction to all the elements in an array processing 3.0 - arrays

I'm trying to make a program which shows some circles, and when the user puts all the circles in one place, the background changes. The problem I have is that when one circle is moved to that place the background changes, but I need that to happened once all the elements of the array had changed position..
DragMe[] drags = new DragMe[15];
PGraphics topLayer;
PGraphics toperLayer;
color backgr;
void setup() {
size(500, 500);
for (int i = 0; i < drags.length; i++) {
drags[i] = new DragMe();
}
topLayer = createGraphics(width, height, g.getClass().getName());
}
void draw() {
background(backgr);
{
topLayer.beginDraw();
topLayer.noFill();
topLayer.stroke(0 );
if (mousePressed ==true) {
topLayer.line( pmouseX, pmouseY, mouseX, mouseY );
topLayer.endDraw();
}
image( topLayer, 0, 0 );
}
for (int i = 0; i < drags.length; i++) {
drags[i].display();
drags[i].update();
}
for (int i = 0; i < drags.length; i++) {
drags[i].fondo();
}
{
ellipse(width/2.5, height/2.5, 110, 110);
fill(255);
}
}
void mousePressed() {
for (int i = 0; i < drags.length; i++) {
if (!drags[i].isOver())
drags[i].dontMove = true;
drags[i].offset_x = mouseX - drags[i].pos_x;
drags[i].offset_y = mouseY - drags[i].pos_y;
}
}
void mouseReleased() {
for (int i = 0; i < drags.length; i++) {
drags[i].locked = false;
drags[i].dontMove = false;
}
}
class DragMe {
float pos_x, pos_y, SIZE = 25;
float prev_x, prev_y;
boolean locked;
boolean dontMove;
boolean all;
color c = color (255);
float offset_x, offset_y;
DragMe() {
pos_x = random(width-SIZE);
pos_y = random(height-SIZE);
}
void update() {
if (isOver() && !locked && !dontMove || locked && !dontMove )
c = color (255);
else
c = color (255);
if (isClicked()) {
locked = true;
}
if (isIn()) {
locked = false;
all = true;
}
if (locked && !dontMove) {
pos_x = mouseX - offset_x;
pos_y = mouseY - offset_y;
}
}
void display() {
fill(c);
ellipse(pos_x, pos_y, SIZE, SIZE);
ellipseMode(CORNER);
noStroke();
}
boolean isOver() {
float right_x = pos_x + SIZE;
float bottom_y = pos_y + SIZE;
return mouseX >= pos_x && mouseX <= right_x &&
mouseY >= pos_y && mouseY <= bottom_y;
}
boolean isClicked() {
return isOver() && mousePressed && !dontMove;
}
boolean isIn() {
float right_x = pos_x + SIZE;
float bottom_y = pos_y + SIZE;
return right_x >= width/2.5 + SIZE && right_x <= width/2.5 + 100 &&
bottom_y >= height/2.5 + SIZE && bottom_y <= height/2.5 + 100;
}
void fondo() {
if (all == true)
backgr= 255;
}
}

You have 15 instances of DragMe.
Each of those instances contains a variable named all.
When one instance's all is true, you set the background to white.
Specifically, this function:
void fondo() {
if (all == true)
backgr= 255;
}
Which you call from draw():
for (int i = 0; i < drags.length; i++) {
drags[i].fondo();
}
Instead, you need to check every instance's all variable, and only change the background if they are all true (in other words, if none of them are false):
boolean allIn = true;
for (int i = 0; i < drags.length; i++) {
if (!drags[i].all) {
allIn = false;
}
}
if (allIn) {
backgr= 255;
}
For future questions, please try to make sure your code is formatted. It might also be a good idea to use better variable names- naming a variable all is a bit hard to talk about. Maybe something like isInsideWhiteCircle would be better.

Related

Modify variable or struct inside a C function

I wanted to make a game of life in C to learn C, but it doesn't work. I just noticed that my code doesn't work when I try to modify a variable created inside a function, even if I try to modify it inside the same function.
When I pass val = 1 in comment, and color in comment, the code works
so val = 0 doesn't cause problem, neither color = {0,0,0,0} because it doesn't modify the variable.
How can I do to correct it ?
void next_grid(int nbc, int nbr,Cell tab[][120],Cell newtab[][120]){
for (int y = 0; y<120; y++){
for(int x = 0; x<120; x++){
int nb_neighbors = count_neighbors(tab,120,120,y,x);
int val = 0;
Color color = {0,0,0,0};
// When a cell is dead
if (tab[y][x].val == 0)
{
if (nb_neighbors == 3)
{
val = 1;
color = (Color) {230,160,0,255};
}
else{
val = 0;
color = (Color) {0,0,0,255};
}
}
{
if (nb_neighbors == 2 || nb_neighbors == 3)
{
val = 1;
color = (Color) {230,160,0,255};
}
else
{
val = 0;
color = (Color) {0,0,0,255};
}
}
newtab[y][x] = (Cell) {val,x,y,color};
}
}
// swap array
for (int y = 0; y<120; y++){
for(int x = 0; x<120; x++){
tab[y][x] = (Cell) newtab[y][x];
}
}
}

Trim Image White Space with maintaining the Aspect ratio

i am trying to trim and crop image without the whitespace surrounded with , but the image i got has aspect ratio not equal to the original image .
i am using the following code in C#
public Bitmap TrimImageWhiteSpaces(Bitmap bitmap)
{
int w = bitmap.Width;
int h = bitmap.Height;
Func<int, bool> isAllWhiteRow = row =>
{
for (int i = 0; i < w; i++)
{
if (bitmap.GetPixel(i, row).R != 255)
{
return false;
}
}
return true;
};
Func<int, bool> isAllWhiteColumn = col =>
{
for (int i = 0; i < h; i++)
{
if (bitmap.GetPixel(col, i).R != 255)
{
return false;
}
}
return true;
};
int leftMost = 0;
for (int col = 0; col < w; col++)
{
if (isAllWhiteColumn(col)) leftMost = col + 1;
else break;
}
int rightMost = w - 1;
for (int col = rightMost; col > 0; col--)
{
if (isAllWhiteColumn(col)) rightMost = col - 1;
else break;
}
int topMost = 0;
for (int row = 0; row < h; row++)
{
if (isAllWhiteRow(row)) topMost = row + 1;
else break;
}
int bottomMost = h - 1;
for (int row = bottomMost; row > 0; row--)
{
if (isAllWhiteRow(row)) bottomMost = row - 1;
else break;
}
if (rightMost == 0 && bottomMost == 0 && leftMost == w && topMost == h)
{
return bitmap;
}
int croppedWidth = rightMost - leftMost + 1;
int croppedHeight = bottomMost - topMost + 1;
try
{
Bitmap target = new Bitmap(croppedWidth, croppedHeight);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(bitmap,
new RectangleF(0, 0, croppedWidth, croppedHeight),
new RectangleF(leftMost, topMost, croppedWidth, croppedHeight),
GraphicsUnit.Pixel);
}
//target = (Bitmap)FixedSize(target,bitmap.Height, bitmap.Width,false);
return target;
}
catch (Exception ex)
{
throw new Exception($"Values are top={topMost} bottom={bottomMost} left={leftMost} right={rightMost}", ex);
}
}
this is the original image
and this the image i got after executing the code
So Please is there any way to trim the image with preserving the aspect ratio of the original image

How to let Stage show the pictures after timer

After I click start button, my program will not show the second scene and thread , until the thread is finish. And the thread will not run correctly(grass didn't increase).
public class test111 extends Application {
private static int grass_i=130;
private static int grass_j=200;
private static int[][] map = new int[grass_i][grass_j];//草地資料grassdata
private static int totalgrass; //grass total number
private static int totalgrassrest; //grass rest number
private static int months=1; //月
private Timer timer;//時間
//GUI
Scene menusc ;
//START後的視窗
BorderPane bpAll = new BorderPane();
Pane playView = new Pane();
Scene mainsc = new Scene(bpAll);
//草
Image littlegrassImg = new Image(getClass().getResourceAsStream("map_littlegrass.png"));
Image midiumgrassImg = new Image(getClass().getResourceAsStream("map_midiumgrass.png"));
Image muchgrassImg = new Image(getClass().getResourceAsStream("map_muchgrass.png"));
Rectangle2D[][] viewportRect = new Rectangle2D[130][200];
private static ImageView[][] mapView = new ImageView[130][200];
//時間
#Override
public void start(Stage primaryStage) throws InterruptedException {
//MENU
Pane menu = new Pane();
menusc = new Scene(menu);
menu.setPrefSize(1000, 800);
Image MenuImg = new Image(getClass().getResourceAsStream("Menu_title.jpg"));
Image StartImg = new Image(getClass().getResourceAsStream("Start.jpg"));
menu.getChildren().add(new ImageView(MenuImg));
Button StartBt = new Button();
StartBt.setPrefSize(450, 150);
StartBt.setGraphic(new ImageView(StartImg));
StartBt.setMaxSize(450, 150);
StartBt.setLayoutX(300);
StartBt.setLayoutY(600);
menu.getChildren().addAll(new ImageView(MenuImg),StartBt);
primaryStage.setMinHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMinWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setMaxHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMaxWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setScene(menusc);
primaryStage.setTitle("Hypnos' yard");
//START
StartBt.setOnAction(e->{
BorderPane bp2 = bp2();
menusc = new Scene(bp2);
primaryStage.setScene(menusc);
});
primaryStage.show();
}
public BorderPane bp2(){
playView = playView();
bpAll = new BorderPane();
bpAll.setPrefSize(1000, 800);
playView.setPrefSize(1000, 650); //庭院
bpAll.setTop(playView);
Random ran = new Random();
totalgrass = (ran.nextInt(50)*1000)+48000;
totalgrassrest = totalgrass;
grasscreate();
//設定初始草地construct the initial grass
grassGraphicsLoading(); //loading grass pictures
return bpAll;
}
public Pane playView(){
playView = new Pane();
while(months<12){
timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
month();
}
};//after program executing 0.2s, a month past
timer.schedule(task, 200);
try {
Thread.sleep(200);
}
catch(InterruptedException e6) {
}
timer.cancel();
}
return playView;
}
//月month
protected void month(){
if(months<13){
grassgrow(totalgrass*2);//grass growth
Platform.runLater(new Runnable(){
#Override
public void run(){
grassGraphicsLoading();
}
});
months++;
}
}
//把草地資料帶入圖形loading grass pictures
private void grassGraphicsLoading(){
for (int i = 0; i < grass_i; i++) { // 設定imageView的圖形和位置
for (int j = 0; j < grass_j; j++) {
viewportRect[i][j] = new Rectangle2D(j * 5, i * 5, 5, 5);
if (170 <= j && j <= grass_j - 1) {
mapView[i][j] = new ImageView(muchgrassImg);
} else if (140 <= j && j < 170) {
mapView[i][j] = new ImageView(muchgrassImg);
} else {
if (map[i][j] == 0) {
mapView[i][j] = new ImageView(littlegrassImg);
} else if (map[i][j] == 1 || map[i][j] == 2) {
mapView[i][j] = new ImageView(midiumgrassImg);
} else {
mapView[i][j] = new ImageView(muchgrassImg);
}
}
playView.getChildren().add(mapView[i][j]);
mapView[i][j].setViewport(viewportRect[i][j]);
mapView[i][j].setX(j * 5);
mapView[i][j].setY(i * 5);
}
}
}
public static void main(String[] args) {
launch(args);
}
// 每經過30天(一個月)草地+1grassgrowth
protected void grassgrow(int sum) {
for (int i = 0; i < grass_i; i++) {
for (int j = grass_j - 1; j >= 0; j--) {
if (map[i][j] < 4 && totalgrass <sum) {
map[i][j] += 1;
totalgrass++;
}
if (totalgrass == 104000||totalgrass ==sum) {
break;
}
}
}
}
//建構草地construct grass
protected void grasscreate() {
for (int j = grass_j - 1; j >= 0; j--) {
for (int i = grass_i - 1; i >= 0; i--) {
if (170 <= j && j <= grass_j - 1) {
map[i][j] = 0;
} else if (140 <= j && j < 170) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest <= 0) {
map[i][j] = 0;
} else if (4 * (j + 1) * grass_i <= totalgrassrest) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest < 4) {
map[i][j] = totalgrassrest;
totalgrassrest = 0;
} else {
map[i][j] = rancreate();
totalgrassrest -= map[i][j];
}
}
}
totalgrass -= totalgrassrest;
totalgrassrest = 0;
}
// 一格(5X5)內草地數量隨機1-4平米z there is 1-4 grass inside a rectangle
private int rancreate() {
Random ran = new Random();
int grass = ran.nextInt(5);
return grass;
}
}`

All elements change in Arraylist - Processing

My program is a zombie survival game, set in a 2d array of blocks.
I use an arraylist - my first attempt - to store the zombies, and each in tern "checks" if there is a block above, below and around it, to detect it's movement.
I'll post the relevant code here, and upload the sketch folder separately.
ArrayList zombies;
void setup() {
zombies = new ArrayList();
}
void draw() {
for (int i = 0; i < zombies.size(); i++) {
Zombie zombie = (Zombie) zombies.get(i);
zombie.draw();
}
}
void keyPressed() {
if (key == 'z') {
zombies.add(new Zombie());
}
}
class Zombie
{
int posX = 20;
int posY = 10;
boolean fall;
boolean playerOnBlock;
Zombie() {
posX = 10;
posY = 590;
fall = false;
}
void draw() {
grid.blockCheck(posX, posY, 2);
fill(0, 255, 0);
rect(posX, posY, 10, 10);
}
void fall() {
posY += 5;
println("zombiefall"+posY);
}
void move(boolean left, boolean right, boolean above) {
if (left == true && player.playerX < posX) {
posX -= 1;
}
if (right == true && player.playerX > posX) {
posX += 1;
}
}
}
class Grid {
void blockCheck(int x, int y, int e) {
for (int i = 0; i < l; i++)
for (int j = 0; j < h; j++)
{
grid[i][j].aroundMe (x, y, i, j, e);
}
}
}
class Block {
void aroundMe(int _x, int _y, int _i, int _j, int entity) {
int pGX = _x/10;
int pGY = _y/10;
if (entity == 1) {
if (pGY+1 == _j && pGX == _i && state == 4) {
player.fall();
}
if (pGX == _i && pGX-1 <= _i && _y == posY && state == 4) {
leftOfMe = true;
}
else
{
leftOfMe = false;
}
if (pGX+1 == _i && _y == posY && state == 4) {
rightOfMe = true;
}
else
{
rightOfMe = false;
}
if (pGY-1 == _j && _x == posX && state ==4) {
aboveOfMe = true;
}
else
{
aboveOfMe = false;
}
player.controls(leftOfMe, rightOfMe, aboveOfMe);
}
if (entity == 2) {
if (pGY+1 == _j && pGX == _i && state == 4) {
for (int i = 0; i < zombies.size(); i++) {
Zombie zombie = (Zombie) zombies.get(i);
zombie.fall();
}
}
if (pGX == _i && pGX-1 <= _i && _y == posY && state == 4) {
ZleftOfMe = true;
}
else
{
ZleftOfMe = false;
}
if (pGX+1 == _i && _y == posY && state == 4) {
ZrightOfMe = true;
}
else
{
ZrightOfMe = false;
}
if (pGY-1 == _j && _x == posX && state ==4) {
ZaboveOfMe = true;
}
else
{
ZaboveOfMe = false;
}
for (int i = 0; i < zombies.size(); i++) {
Zombie zombie = (Zombie) zombies.get(i);
zombie.move(ZleftOfMe, ZrightOfMe, ZaboveOfMe);
}
}
Sketch is here: http://www.mediafire.com/?u5v3117baym846v
I believe the problem lies in specifying which element of an arraylist I am referring to, as I can observe the issues to be:
All "zombies" fall when one detects that it should fall.
Zombie's speed increases with each additional zombie added - somehow treating all the zombie elements as one zombie object?
This might be a similar issue:
All elements of An ArrayList change when a new one is added?
But I've fiddled with my project and I can't seem to get it working still.
Please don't hesitate to ask for more information on my project. I will be with my computer all evening so should be able to reply quickly. Thanks in advance.
Thanks for your help.
I'm using it like this:
ArrayList <Zombie> zombies = new ArrayList <Zombie>();
-------------------------------------------
void setup(){
zombies = new ArrayList();
-------------------------------------------
void draw(){
for (Zombie z:zombies) {
z.draw();
}
}
-------------------------------------------
void keyPressed() {
if (key == 'z') {
for (int i = 0; i< 1; i++) {
zombies.add(new Zombie(i));
}
}
-------------------------------------------
class Zombie
{
int posX = 20;
int posY = 10;
boolean fall;
boolean playerOnBlock;
int z;
Zombie(int _z) {
posX = 10;
posY = 590;
fall = false;
z = _z;
}
void draw() {
grid.blockCheck(posX, posY, 2);
fill(0, 255, 0);
rect(posX, posY, 10, 10);
}
void fall() {
posY += 5;
println("zombiefall"+posY);
}
void move(boolean left, boolean right, boolean above) {
if (left == true && player.playerX < posX) {
posX -= 1;
}
if (right == true && player.playerX > posX) {
posX += 1;
}
}
}
Here is the idea :)
//use generics to keep it simple. Only Zoombies in this list
ArrayList <Zoombie> samp = new ArrayList <Zoombie>();
void setup() {
//a regular for loop to use the i as id
for (int i = 0; i< 100; i++) {
samp.add(new Zoombie(i));
}
//run just once
noLoop();
}
void draw() {
//a enhanced for, no need for use get()
// z will represent each element in the collection
for (Zoombie z:samp) {
z.d();
}
println("done");
}
// a dummy class ;)
class Zoombie {
int id;
Zoombie (int _id)
{
id =_id;
}
void d()
{
println(id);
}
}

TicTacToe Array. Winner method and is square free

I dont know what I'm doing wrong here.
Can anyone tell me what's wrong with my checkRow code in checkWinner and isSquareFree method?
Here's my code:
public class TicTacToe
{
/**
* intance variables to hold the data's state for the game.
*/
public static final int GRIDSIZE = 3;
public static final char BLANK = ' ';
public static final char TIE = 'T';
public static final char NOUGHT = 'O';
public static final char CROSS = 'X';
private char[][] grid;
private char WhoseTurn;
/**
* Construct a tic tac toe grid ready to play a new game.
* The game grid should be GRIDSIZE by GRIDSIZE spaces
* all containing the BLANK character.
* Initially, the starting player is not decided,
* indicated by setting whoseturn as BLANK.
*/
public TicTacToe()
{
this.WhoseTurn = BLANK;
this.grid = new char[GRIDSIZE][GRIDSIZE];
for (int r = 0; r < grid.length; r++)
{
for ( int c = 0; c < grid[r].length; c++)
{
this.grid[r][c] = BLANK;
}
}
}
/**
* Reset the tic tac toe game ready to play again.
* Conditions for play are the same as for the constructor.
*/
public void newGame()
{
char[][] boardToClear = getGrid();
final int sizeOfBoard = grid.length;
for ( int row = 0; row < grid.length; row++)
{
for ( int col = 0; col < grid.length; col++)
{
grid[row][col] = BLANK;
}
}
}
public char[][] getGrid()
{
int gridLen = grid.length;
char[][] gridCopy = new char[gridLen][];
for ( int r = 0; r < gridCopy.length; r++)
{
gridCopy[r] = new char[gridCopy.length];
for ( int c = 0; c < gridCopy.length; c++)
{
gridCopy[r][c] = grid[r][c];
}
}
return gridCopy;
}
public char getWhoseTurn()
{
return WhoseTurn;
}
/**
* printGrid() displays the current state of the game grid
* on the console for debugging.
* It uses the form feed character \u000C to clear the console before
* printing the current grid.
*/
private void printGrid()
{
System.out.print('\u000C'); // clear the console window
for (int x = 0; x < GRIDSIZE-1; x++) {
System.out.print(grid[x][0] + "|" +
grid[x][1] + "|" + grid[x][2]);
System.out.println("\n-----"); //
System.out.print(grid[GRIDSIZE-1][0] + "|" +
grid[GRIDSIZE-1][1] + "|" +
grid[GRIDSIZE-1][2]);
}
}
// Now print last row (with no bottom edge)
private boolean checkIfGridFull()
{
char[][] board = getGrid();
int size = grid.length;
for ( int row = 0; row < size; row++)
{
for ( int col = 0; col < board[row].length; col++)
{
if ( grid[row][col] == BLANK)
{
return false;
}
}
}
return true;
}
public boolean move(char player, int row, int col)
{
char[][] boardToPlay = getGrid();
int size = grid.length;
char x = player;
if ( (player == NOUGHT) || ( player == CROSS))
{
if ( (x == WhoseTurn) || (WhoseTurn == BLANK))
{
if ((checkIfGridFull() == false) && ( boardToPlay[row][col] == BLANK))
{
if( (row < size) && ( col < size))
{
boardToPlay[row][col] = player;
if ( player == CROSS)
{
WhoseTurn = NOUGHT;
}
if ( player == NOUGHT)
{
WhoseTurn = CROSS;
}
return true;
}
}
}
}
return false;
}
public boolean isSquareFree( int row, int col)
{
if ((grid[row][col] == BLANK))
{
return true;
}
return false
;
}
public char checkWinner()
{
int countNought;
int countCross ;
int size = grid.length;
for ( int row = 0; row < size; row++)
{
countNought = 0;
countCross = 0;
for ( int col = 0; col < size; col++)
{
if ( grid[row][col] == CROSS)
{
countCross++;
}
if ( grid[row][col] == NOUGHT)
{
countNought++;
}
if ( countNought == size)
{
return NOUGHT;
}
if ( countCross == size)
{
return CROSS;
}
}
}
return BLANK;
}
}
One good method for tracking down a bug in a project like this is to use print line statements. Try this: put a print line somewhere near where you think the problem is, and print out the values of some of the local variables. If you see values that you shouldn't then you know that your data has come into some trouble earlier on in the code. In that case, move the print lines further back in the flow and try again. Keep doing this until you notice values going from good to bad (or bad to good): at that point you have tracked down the code that contains the bug.
Once you've done this, you will usually have only a small function to think about, and it will be much easier to understand what you've done wrong. If you still can't find the problem, then post the code snippet here and someone will probably be able to help you.
checkWinner() is wrong you're not checking diagonals, just write the eights winning combinations

Resources