I have a 2D array of buttons called arr. For my game's win condition, I want to compare the graphics of the buttons to a 2D array of WritableImage's called newImage, where the condition is met once each button graphic is equal to the corresponding image. e.g. arr[0][0] equals newImage[0][0] etc. The code below doesn't seem to compare them, as nothing happens, guessing because of the different objects. Could anyone give any suggestions on how I should tackle this?
if (arr[3][3].getText().equals("blank")) {
System.out.println("this runs");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Objects.equals(arr[i][j].getGraphic(), newImage[i][j])) { //If the each button contains the correct corresponding graphic, puzzle is complete
System.out.println(arr[i][j] + " is correct");
}
setWin = true;
}
}
}
}
Related
I have a school project, I have to build a Tetris Game.
So I began with the creation of my menu with the different level, when I click on one level i go to my second activity (the game area) and I have also created my custom block.
My problem is a visual issue, indeed I don't know what type of layout I have to use for my surface game (gridlayout, linearlayout, grid etc. ...).
And then how to affect my blocks custom in this surface game, in this layout?
See the result expected.
enter image description here
I'm not sure I understand what you want entirely but ill give it a shot from what i think you mean.
You should use a nested for loop to do it, if your array was int[10,20](not right syntax but i cant be bothered to count the actual size of your array).
you should go:
(pseudocode)
also assume your resolution is 100, 200
For(int i = 1 To 10){
For(int k = 1 To 20){
DrawSquare(i*10, k*10, "block type")
k = k + 1
}
i = i + 1
}
Then it will fill your 100, 200 area with the block type specified. Now if you want to load what block type you want freom the array you can just call the array in the block type.
DrawSquare(i*10, k*10, Array[i,k])
Obviously bear in mind that its all pseudocode to display the logic.
Hope this helps
Building on Valhalla's answer with a Java-specific example, it's still a bit unclear what you're asking, but assuming you want to initialise the grid to begin with you can use this code:
private final int columns = 10;
private final int rows = columns * 2;
private int[][] grid;
private void initialise() {
grid = new int[columns][rows];
for (int i = 0; i < columns; i++) {
for(int j = 0; j < rows; j++) {
grid[i][j] = 0;
}
}
}
And assuming that you have a block that starts at the top, and falls one square with each iteration provided there's nothing underneath, you can try this:
private void blockFall() {
// Start from 1 row above the bottom and parse upwards
// so a block won't drop right to the bottom on a single iteration
for (int i = 0; i < columns; i++) {
for(int j = rows - 2; j >= 0; j--) {
if (grid[i][j] > 0 && grid[i][j+1] == 0) {
grid[i][j+1] = grid[i][j];
grid[i][j] = 0;
}
}
}
}
How do I search a 2D array for a specific number (1)? I thought the following code did it, but apparently I was looking in a specific spot whenI declared it with [4][4].
boolean undirectedCircuit (int [][] graph)
{
//graph = graph1(graph1(null));
int edgeCounter = 0;
for (int edge = 0; edge < graph.length; edge++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if(graph[4][4] == '1')
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
if (edgeCounter % 2 == 0)
{
System.out.println("This is a circuit!");
//return true;
}
else System.out.println("This is not a circuit!!");
return false;
}
public void go ()
{
graph1 = new int[][] //This line is complained about.
{
{0,1,1,1,0},
{1,0,0,0,1},
{1,0,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}
};
undirectedCircuit(graph1); //This is complained about.
}
This is part of an assignment from my school, just pointers would be great. Thank you!
This line is wrong in two ways:
if(graph[4][4] == '1')
The quotes around '1' make it a char literal. Since your array contains ints, you'll want to drop the quotes and just write 1.
graph[4][4] will always check the same value in the array as you said. Specifically, it will always access the fifth value in the fifth array of your 2d array. Whenever you write numbers in your code, they are constants: the number 4 is never going to change during your program's execution, so you keep using 4 as the index over and over again, accessing the fifth element each time you do so.
In order to access every element in an array, you can loop over it like this:
for (int n = 0; n < array.length; n ++)
{
array[n]; //access the nth element of the array
}
n in this instance is the same as your edge variable.
However, since you are using a 2d array, these elements are themselves arrays! Therefore, you need another loop:
//array is a 2d array...
for (int n = 0; n < array.length; n ++)
{
//...so its elements are 1d arrays
for (int m = 0; m < array[n].length; m ++)
{
array[m][n]; //here we have a specific object in our 2d array.
}
}
We use variables for our indices so they can change in the loop and access different values in the array. Hope this helps!
You could try something like this where you will iterate through both dimensions of the array and check your current location rather than the 4,4
for (int x = 0; x < graph.length; x++)
{
for (int y = 0; y < graph[x].length; y++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if (graph[x][y] == 1)
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
}
public void actionPerformed(ActionEvent e){
grid=new JButton[length+20][width+20];
grid1=new JButton[length+20][width+20];
for(int i=0;i<length+2;i++)
{
for(int j=0;j<width+2;j++)
{
grid1[i][j]=grid[i][j];
}
}
for(int i=1;i<length+1;i++)
{
for(int j=1;j<width+1;j++)
{
//final int row = i;
//final int col = j;
int count=0;
if(grid[i][j-1].getBackground() == Color.BLACK);
count++;
if(grid[i][j+1].getBackground()==Color.BLACK)
count++;
if(grid[i-1][j-1].getBackground()==Color.BLACK)
count++;
if(grid[i-1][j].getBackground()==Color.BLACK)
count++;
if(grid[i-1][j+1].getBackground()==Color.BLACK)
count++;
if(grid[i+1][j-1].getBackground()==Color.BLACK)
count++;
if(grid[i+1][j].getBackground()==Color.BLACK)
count++;
if(grid[i+1][j+1].getBackground()==Color.BLACK)
count++;
if(count==3) // exactly three neighbors
{
if(grid[i][j].getBackground()==Color.WHITE)
{
grid1[i][j].setBackground(Color.BLACK); // birth cell
}
}
if(count==2 || count==3) // 2 or 3 neighbors
{
if(grid[i][j].getBackground()==Color.BLACK)
{
grid1[i][j].setBackground(Color.BLACK); // survives
}
}
if(count>=4 || count<=1) //4 or more neighbors, or 1 or less neighbor
{
if(grid[i][j].getBackground()==Color.BLACK)
{
grid1[i][j].setBackground(Color.WHITE); // dies from over-population or isolation
}
}
}
}
for(int i=0;i<length+2;i++)
{
for(int j=0;j<width+2;j++)
{
grid[i][j]=grid1[i][j];
}
}
for(int i=1;i<length+1;i++)
{
for(int j=1;j<width+1;j++)
{
System.out.print(grid[i][j]);
}
System.out.println("\n");
}
}
I am getting a nullpointer exception when I try to display the next generation of conway game of life using a GUI. Please suggest whats wrong with my code. The action performed method is executed when a start button is clicked
The cause of the NullPointerException is this:
grid = new JButton[length+20][width+20];
grid1 = new JButton[length+20][width+20];
This way, you have a 2D-array of JButtons, but it is still full of null values. You have to initialize the individual "cells" in the array:
for (int i = 0; i < length+20; i++) {
for(int j = 0; j < width+20; j++) {
grid1[i][j] = new JButton();
}
}
Also, is the size of the array intentional, or should it be length+2 x width+2 instead, as in your for-loop?
But this is not your actual problem: You create a new buttons-array, and then check the background colors of those newly created buttons. Assuming that grid represents the current state of the game, you are erasing the game state before doing the update. More likely, you have to drop the line grid = new JButton[length+20][width+20]; entirely.
And even this will not work correctly, as the two arrays grid and grid1 will hold the same buttons, so when you change the background color of one, you also change the background color in the backup. With grid1[i][j]=grid[i][j] you just copy the reference to the button to the other array, but do not create a new button. And even if you did, you would have the problem that that new button would not be in the GUI at all.
Instead of storing your game state in the GUI elements, you should rather use two 2D-arrays of booleans (one for the current state, one as backup of the previous state during the state update) and set the background color of the buttons based on those booleans.
Hey I'm having trouble getting my code to compare the integers of a given row or column and block to make sure there are no duplicates within those parameters. I don't know if it would be a good idea separating the three contraints in 3 different methods or just trying to attempt to do all at once.
public static rowCheck(int[][] nsudokuBoard) {
for (int i =0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// (nsudokuBoard)
}
}
}
this is my code im starting. before you guys bash on me for not even being able to compile this im stuck on how to compare all the values of a row of the 2d array.
You can compare all the values of the 2d array as shown in the code below:
void validate(final int[][] nsudokuBoard) {
final int width = nsudokuBoard[0].length;
final int depth = nsudokuBoard.length;
for (int i = 0; i < width; i++) {
int j = i;
int reference = nsudokuBoard[i][j];
do {
if (j < width) {
int current = nsudokuBoard[i][j];
if (current == reference) {
// invalid entry found do something
}
}
if (j < depth) {
// note reversed indexes
int current = nsudokuBoard[j][i];
if (current == reference) {
// invalid entry found do something
}
}
++j;
} while ((j >= width) || (j >= depth));
}
}
I haven't tried to compile this code, but it should give you an idea of how to accomplish your task. I would suggest that rather than passing in int[][] sudokuBoard that you should define a class which encapsulates the concept of a SudokuSquare and pass in SudokuSquare[][] , that way your validate method can return a List<SudokuSquare> containing all the offending entries.
I'll show how you might do it for one row, and then you can figure out the rest. I'm assuming your values are 1 through 9 inclusive, and that you don't have any zeroes or any "unfilled entries."
boolean isRowValid(int[][] grid, int row) {
boolean[] seen = new boolean[9];
int row; // chosen somewhere else
for (int col = 0; col < 9; col++) {
if (seen[grid[row][col] - 1]) { // if we've seen this value before in this row
return false; // there is a duplicate, and this is a bad sudoku
}
seen[grid[row][col] - 1] = true; // mark us as having seen this element
}
return true; // we're all good
}
return true; // this row is fine
make a class Cell with fields row,col,block,value; then make a class Matrix with field cells = cell[], fill matrix.
make a class checker with main method Matrix matrix = init(int[][]) and check(matrix), where init(ยท) fills the matrix.
boolean ok = check(matrix) where check(Matrix) does if(!rowcheck())return false; if(!colcheck()) return false etc;
create some methods like getrows(), getrow(r) and for(Cell cell: matrix.values()) to filter out the ones you want.
a bit tedious but i have done it and it is solid as rock.
As a note, filtering over matrix may seem stupid but computers are fast and the problem is O(1) since it is 9x9.
I'm trying to print out an indicator of coordinates on a 2D array...
There is another class that I've used to instantiate objects on the array.
I need to the store coordinates in two (local?) variables, and then display the position of those coordinates in the printed array. (that has already been instantiated with various objects)
This is a snippet of code I have so far, but I can't get the 'C' to print in the right spot on the array. The few options that I tired, either doesn't print it at all, or prints the 'C' in the top left hand corner.
This is one option that I've tired: This option doesn't print the 'C' at all.
private int cX=0;
private int cY=0;
//Randomly set coordinates on array.
for(int i=0; i<array.length; i++){
for(int j=0; j<array[i].length; j++){
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (array [x][y].display()=='.'){
x=cX;
y=cY;
}
}
}
// print array
private void displayArray()
{
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
if ((array [i][j].display()==cX)&&
(array [i][j].display()==cY))
System.out.print("C");
System.out.print(board [i][j].display()+"\t")
}
System.out.println("\n");
}
}
If I understood you right, you'd like to save coordinates to some kind of data structure and later display them?
Wouldn't it be suitable to create a class for this purpose? E.g.
A class called Coordinator, that holds the X & Y values.
Later create a object of the class you've made with X & Y values and put it to a ArrayList.
Code Example:
//Creating the a object holding 2 values
Coordinator cords = new Coordinator(randGen.nextInt(9), randGen.nextInt(9));
//Putting in the object to the data structure
List<Coordinator> list = new ArrayList<>();
list.add(cords);
The explanation and code example should help you solve this issue on your own hopefully.
This option doesn't print the 'C' at all.
Your current code example will indeed never print a 'C'.
for (int j = 0; j < array[i].length; j++){
if ((array [i][j].display()==cX)&&
(array [i][j].display()==cY))
This if condition will be true only if cX equals cY and both are equal to the ascii code value assigned to the array (for '.' this is the value 46). But you may just want to find the cX,cY position and print a 'C'. You should try to campare your position (cX, cY) with the current i and j values.
if ((i==cX)&&(j==cY))
prints the 'C' in the top left hand corner
You never change the content of array at the position. You set x and y which will be overwritten and are later no accessible
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (array [x][y].display()=='.'){
x=cX;
y=cY;
}
Do you want to find a random position for your 'C' to appear, like in a board game?
Then you need to assign your found x and y coordinate to cX and cY. The right value gets assigned to the left variable.
cX = x;
cY = y;
I hope I understood you right and this helps.
For completeness: I think I worked it out. (Well it seems to be working anyway).
Thanks for the help!
private int cX=0;
private int cY=0;
//Randomly set coordinates on the array.
for(int i=0; i<1; i++){
int x = randGen.nextInt(9);
int y = randGen.nextInt(9);
if (board [x][y].display()=='.'){
CX=x;
CY=y;
}
}
//Print array
private void displayArray(){
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
if ((i==CX)&&(j==CY))
System.out.print("C"+"\t");
else
System.out.print(board [i][j].display()+"\t");
}
System.out.println("\n");
}
}
private double[][] mLatLng = {
{19.01062463, 73.01141475},
{19.02369039, 73.00778391},};
public void onMapReady(GoogleMap googleMap) { googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_icon);
for (int i = 0; i < mLatLng.length; i++) {
for (int j = 0; j < mLatLng[i].length; j++) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(mLatLng[i][j], mLatLng[i][j]))
.title("Location" + i).icon(bitmapDescriptorFromVector(context,R.drawable.ic_icon)));