SlideShare a Scribd company logo
need help with this java lab: please read below and follow the steps! Copy and paste the code at
the bottom into your ide and go from there, please do not write a whole new program!
The purpose of this lab is to give you an opportunity to make use of a stack in the
implementation of a backtracking algorithm.
This problem is generally referred to as the N Queens problem. The gist of the problem is to
create an algorithm which can position N queens on a chess board so none of the queens can
attack any other queen. For those of you who may not be familiar with chess, the queen can
move horizontally, vertically, and diagonally. In the generalized N Queens problem, N represents
the number of rows and columns of the game board and the number of queens that must be
placed on the board in safe positions.
we will NOT be using recursion in any way to solve this problem.
The basic strategy that we will employ to solve this problem is to use backtracking. In this
particular case, what backtracking means is that we will make a move that is safe for a queen at
the time we make the move, but later on, we may discover that we are stuck and there is no safe
move available for the next queen we are trying to place on the board, so we must backtrack.
That means we will go back to the previous queen’s move, undo that move, and continue
searching for another safe place to put that queen. We will use the stack to remember where we
have placed queens on the board and when we need to back up, the queen at the top of the stack
will be popped and we will use that queen’s position to resume the search for the next safe
location.Stradegy below:
There are N rows. When a queen is placed into a row, that row cannot be used by other queens.
There are N columns. When a queen is placed into a column, that column cannot be used by
other queens.
There are 2 sets of diagonals to be concerned with, diagonals running upper left to lower right
and diagonals running upper right to lower left. There is a simple mathematical relationship
between N and the number of diagonals in each direction. When a queen is placed onto the
board, one left to right diagonal is no longer safe for other queens, and one right to left diagonal
is no longer safe for other queens.
Our approach to placing the queens on the board will be to use nested loops. As an example the
outer loop will be in control of which column we are currently searching for a spot to place a
queen. So, the first queen we place will be in column 0, and when the outer loop has completed
we will have placed N queens on the board, one in each column.
The inner loop will iterate through the rows, from 0 to N-1 until it finds a row R such that row R
is not taken by another queen, AND the 2 diagonals which intersect row R and the current
column are not taken by another queen. IF we find such a safe location, we push the current row,
column value onto a stack. Note: we can use the Java Point class to store the row and column
numbers in the x, y values of a Point object. By placing a queen’s location information into the
stack, we have affected the state of the board. We must update the state information to reflect
that a row is no longer safe for other queens. We also must update the state of the two diagonals
which intersect with the queen’s row, column position to indicate that those diagonals are no
longer available to other queens to be placed later. After updating the state information, we can
break out of the inner loop and continue on to the next column in the outer loop.
The backtracking aspect of this exercise occurs when the inner loop fails to find a spot to place a
queen in the current column. Inside the inner loop, we need to recognize that we have checked
position (row N-1, current column) and found that it is not safe. Therefore there is no safe place
for a queen in this column. Since we are stuck, we need to back up and try a different placement
for the previously placed queen. To backtrack, we need to undo the actions taken when we
placed the last queen onto the stack. That means pop the last queen off the stack, mark the row
and diagonals associated with that queen’s position as available again, and reset the row and
column loop control variables back to the point where they were when this queen was pushed
onto the stack (ie row = poppedPoint.x, column = poppedPoint.y). After backtracking the row
loop will continue to the next row to check if that row, column position is safe.
I am providing you with a partially completed Java FX project for this project. The project I am
giving you contains 2 classes. The GameBoard class provides methods for creation of the game
board based on the size given to its constructor. It also provides methods for placing and
removing a queen from a specific row, column position on the game board.
The JavaFxQueens class is the main application class. It determines what size the game board is
to be, creates an GameBoard object, and places the game board into a scene on the stage. It also
starts up a thread which will find safe places on the board for all the queens.
The placeQueens method in the JavaFxQueens class has not been completed. You must write the
code needed to find safe locations for all the queens. Whenever you find a safe place and push a
row, col position onto the stack, you must also call the placeQueen method on the GameBoard
object to draw that queen on the board. Whenever you backtrack and pop a row, col position off
the stack, you must also call the removeQueen method on the GameBoard object to remove that
queen from the game board display. Note, that after calling either one of these 2 methods, you
must call the delay method (which is provided) to slow down the rate at which moves are drawn
on the board so that every queen placed or removed is visible on the display for a reasonable
amount of time.
Think very carefully about how you want to organize the data which captures the state of the
game board (rows, diagonals). You do not need an actual representation of the game board (ie.
no 2 dimensional array). Also think carefully about how to mathematically capture the
relationship between a row, column position and which diagonals intersect that position. Part of
creating efficient programs is designing clever data representations which can be accessed in
very efficient ways from known information.
here is the code: please copy the java queens class and the gameboard class into your ide and
read the above to solve.
****javaQueens****
package javafxqueens;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
/**
*
* @author RVolkers
*/
public class JavaFxQueens extends Application implements Runnable {
private GameBoard board;
private int boardSize = 0;
@Override
public void start(Stage primaryStage) {
// Get the size of the game board from the user. Must be at least 5.
while(boardSize < 5)
{
boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board."));
}
board = new GameBoard(boardSize);
// The game board calculates how much display area it will need to display properly
Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize());
primaryStage.setTitle("N Queens");
primaryStage.setScene(scene);
primaryStage.show();
// Since the main thread is responsible for doing all the GUI updating,
// we need a separate thread to process the placement of queens. That thread
// will call methods on the GameBoard to tell the main thread where to place
// or remove queens on the board.
Thread thread = new Thread(this);
thread.start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
// Must do the main processing in a separate thread, so this class
// implements the Runnable interface.
@Override
public void run() {
// This thread calls a private method to figure out where the queens go
placeQueens();
}
// Used to slow down moves to enable seeing the board placement change
// as each queen is placed or removed from the board
private void delay()
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
}
// Figure out where to place the queens here....
// Call placeQueen and removeQueen methods on the gameBoard object when needed
private void placeQueens()
{
//insert new code here!
}
}
******gameboard******
package javafxqueens;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
/**
*
* @author RVolkers
*/
public class GameBoard extends GridPane {
private final int ButtonSize = 110;
private final int GapSize = 5;
private int size;
private Button[][] board;
public GameBoard() {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = 8;
createBoard();
}
public GameBoard(int n) {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = n;
createBoard();
}
private void createBoard() {
// Create an array to hold references to all the buttons on the board.
board = new Button[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
// Create each button with alternating colors
Button b = new Button();
b.setPrefSize(ButtonSize, ButtonSize);
if ((row + col) % 2 == 0) {
b.setStyle("-fx-background-color: red");
} else {
b.setStyle("-fx-background-color: black");
}
// Add the button to the board and to the GridPane
board[row][col] = b;
add(b, col, row);
}
}
}
// Calculate the size of the display based on the size
// of the buttons and the size of the gaps between buttons.
public double getDisplaySize() {
return size * ButtonSize + (size + 1) * GapSize;
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by adding the queen graphic to the appropriate button on the board
public void placeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(new ImageView("queen.gif"));
});
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by removing the queen graphic from the appropriate button on the board
public void removeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(null);
});
}
}
Solution
i add some methods for display the queens as Q and move the queens
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
public class JavaFxQueens extends Application implements Runnable {
private GameBoard board;
private int boardSize = 0;
@Override
public void start(Stage primaryStage) {
// Get the size of the game board from the user. Must be at least 5.
while(boardSize < 5)
{
boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board."));
}
board = new GameBoard(boardSize);
// The game board calculates how much display area it will need to display properly
Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize());
primaryStage.setTitle("N Queens");
primaryStage.setScene(scene);
primaryStage.show();
// Since the main thread is responsible for doing all the GUI updating,
// we need a separate thread to process the placement of queens. That thread
// will call methods on the GameBoard to tell the main thread where to place
// or remove queens on the board.
Thread thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
launch(args);
}
// Must do the main processing in a separate thread, so this class
// implements the Runnable interface.
@Override
public void run() {
// This thread calls a private method to figure out where the queens go
placeQueens();
}
// Used to slow down moves to enable seeing the board placement change
// as each queen is placed or removed from the board
private void delay()
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
}
// Figure out where to place the queens here....
// Call placeQueen and removeQueen methods on the gameBoard object when needed
//here we need on method for display the queens
public void showQueens(int[] s) {
int n = s.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (s[i] == j) {
System.out.print("Q");
} else {
System.out.print("");
}
}
System.out.println();
}
System.out.println();
}
public void placeQueens(int p, int n) {
for (int c = 0; c < n; c++) {
if (placeQueens(p, c)) {
s[r] = c;
if (r == n - 1) {
printQueens(s);
} else {
placeQueens(p + 1, n);
}
}
}
}
public void callplaceNqueens() {
placeQueens(0, s.length);
}
}
******gameboard******
package javafxqueens;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
/**
*
* @author RVolkers
*/
public class GameBoard extends GridPane {
private final int ButtonSize = 110;
private final int GapSize = 5;
private int size;
private Button[][] board;
public GameBoard() {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = 8;
createBoard();
}
public GameBoard(int n) {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = n;
createBoard();
}
private void createBoard() {
// Create an array to hold references to all the buttons on the board.
board = new Button[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
// Create each button with alternating colors
Button b = new Button();
b.setPrefSize(ButtonSize, ButtonSize);
if ((row + col) % 2 == 0) {
b.setStyle("-fx-background-color: red");
} else {
b.setStyle("-fx-background-color: black");
}
// Add the button to the board and to the GridPane
board[row][col] = b;
add(b, col, row);
}
}
}
// Calculate the size of the display based on the size
// of the buttons and the size of the gaps between buttons.
public double getDisplaySize() {
return size * ButtonSize + (size + 1) * GapSize;
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by adding the queen graphic to the appropriate button on the board
public void placeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(new ImageView("queen.gif"));
});
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by removing the queen graphic from the appropriate button on the board
public void removeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(null);
});
}
}

More Related Content

PDF
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
PDF
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf
PDF
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
PDF
hello the code given is mostly complete but I need help with the Sol.pdf
PDF
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
PDF
Java Algorithm Interview Questions & Answers .pdf
PDF
Neural networks across space & time : Deep learning in java
PDF
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
hello the code given is mostly complete but I need help with the Sol.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Java Algorithm Interview Questions & Answers .pdf
Neural networks across space & time : Deep learning in java
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...

Similar to need help with this java lab please read below and follow the steps.pdf (20)

PDF
Copy of repast javagettingstarted
PPTX
Sudoku Solver using Convolutional Neural networks.pptx
PDF
Proyecto grupal algebra parcial ii
PDF
ngAnimate crash course
PPTX
Support vector machines (svm)
PDF
Read carefully and follow exactly Java You are to write a Breakou.pdf
PDF
Codeware
PDF
I need help with this assignment Ive gotten abit stuck with the cod.pdf
PDF
Im looking for coding help I dont really need this to be explained.pdf
PDF
Shoot-for-A-Star
PPT
Data Structure Lecture 4
PDF
Read carefully. Im not sure if the point class is correct but postin.pdf
PPTX
PRML Chapter 6
PPTX
Data structures and algorithms
PPTX
Data structures and algorithms
PPTX
Data structures and algorithms
PPTX
Data structures and algorithms
PPTX
Data structures and algorithms
PPTX
Data structures and algorithms
PPTX
Data structures and algorithms
Copy of repast javagettingstarted
Sudoku Solver using Convolutional Neural networks.pptx
Proyecto grupal algebra parcial ii
ngAnimate crash course
Support vector machines (svm)
Read carefully and follow exactly Java You are to write a Breakou.pdf
Codeware
I need help with this assignment Ive gotten abit stuck with the cod.pdf
Im looking for coding help I dont really need this to be explained.pdf
Shoot-for-A-Star
Data Structure Lecture 4
Read carefully. Im not sure if the point class is correct but postin.pdf
PRML Chapter 6
Data structures and algorithms
Data structures and algorithms
Data structures and algorithms
Data structures and algorithms
Data structures and algorithms
Data structures and algorithms
Data structures and algorithms
Ad

More from arjuntiwari586 (20)

PDF
Would you recomend that Miss E begin to take a vitamin or mineral su.pdf
PDF
Which perspective best describes adolescenceWhen does adolescence.pdf
PDF
Which of the following is a trace element, required only in small amo.pdf
PDF
Which of the following enzymes has the ability to accomplish all thr.pdf
PDF
What risk are associated with pregnancySolutionThere are vari.pdf
PDF
What are the relative signal intensities for Grey and White matter u.pdf
PDF
What is the ovum doing during the primary oocyte stageSolution.pdf
PDF
What is the structural difference between the sugar found in RNA and.pdf
PDF
uìdyov fotect peaga e (or ways co profecé se p protect e . Haa .pdf
PDF
Use the Java Thread class to demonstrate the following functionaliti.pdf
PDF
Turner suppressor genes.... prevent gene expression of oncogenes. pre.pdf
PDF
This image is a reminder that statistical significant is often set at.pdf
PDF
The state diagram shown up corresponds to a circuit implementation th.pdf
PDF
The lineage that produced chimpanzees and humans split from other pri.pdf
PDF
production deviance postconventional level primary stakeholders perso.pdf
PDF
Question 19 (1 point) The DuPont identity breaks down return on equit.pdf
PDF
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
PDF
Place all the characteristics of living organisms the answer box. Ch.pdf
PDF
LABELING ACTIVITY 2 (Rs 1-10) 10 10. 12. 13 14, 15 16 62 circulatory .pdf
PDF
Of 10 fish in a pond 4 are tagged. If three fish are caught and not .pdf
Would you recomend that Miss E begin to take a vitamin or mineral su.pdf
Which perspective best describes adolescenceWhen does adolescence.pdf
Which of the following is a trace element, required only in small amo.pdf
Which of the following enzymes has the ability to accomplish all thr.pdf
What risk are associated with pregnancySolutionThere are vari.pdf
What are the relative signal intensities for Grey and White matter u.pdf
What is the ovum doing during the primary oocyte stageSolution.pdf
What is the structural difference between the sugar found in RNA and.pdf
uìdyov fotect peaga e (or ways co profecé se p protect e . Haa .pdf
Use the Java Thread class to demonstrate the following functionaliti.pdf
Turner suppressor genes.... prevent gene expression of oncogenes. pre.pdf
This image is a reminder that statistical significant is often set at.pdf
The state diagram shown up corresponds to a circuit implementation th.pdf
The lineage that produced chimpanzees and humans split from other pri.pdf
production deviance postconventional level primary stakeholders perso.pdf
Question 19 (1 point) The DuPont identity breaks down return on equit.pdf
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
Place all the characteristics of living organisms the answer box. Ch.pdf
LABELING ACTIVITY 2 (Rs 1-10) 10 10. 12. 13 14, 15 16 62 circulatory .pdf
Of 10 fish in a pond 4 are tagged. If three fish are caught and not .pdf
Ad

Recently uploaded (20)

PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Computing-Curriculum for Schools in Ghana
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Classroom Observation Tools for Teachers
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Basic Mud Logging Guide for educational purpose
PDF
01-Introduction-to-Information-Management.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Renaissance Architecture: A Journey from Faith to Humanism
Insiders guide to clinical Medicine.pdf
Microbial diseases, their pathogenesis and prophylaxis
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPH.pptx obstetrics and gynecology in nursing
Computing-Curriculum for Schools in Ghana
102 student loan defaulters named and shamed – Is someone you know on the list?
Anesthesia in Laparoscopic Surgery in India
2.FourierTransform-ShortQuestionswithAnswers.pdf
Classroom Observation Tools for Teachers
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
Microbial disease of the cardiovascular and lymphatic systems
Basic Mud Logging Guide for educational purpose
01-Introduction-to-Information-Management.pdf
VCE English Exam - Section C Student Revision Booklet
human mycosis Human fungal infections are called human mycosis..pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...

need help with this java lab please read below and follow the steps.pdf

  • 1. need help with this java lab: please read below and follow the steps! Copy and paste the code at the bottom into your ide and go from there, please do not write a whole new program! The purpose of this lab is to give you an opportunity to make use of a stack in the implementation of a backtracking algorithm. This problem is generally referred to as the N Queens problem. The gist of the problem is to create an algorithm which can position N queens on a chess board so none of the queens can attack any other queen. For those of you who may not be familiar with chess, the queen can move horizontally, vertically, and diagonally. In the generalized N Queens problem, N represents the number of rows and columns of the game board and the number of queens that must be placed on the board in safe positions. we will NOT be using recursion in any way to solve this problem. The basic strategy that we will employ to solve this problem is to use backtracking. In this particular case, what backtracking means is that we will make a move that is safe for a queen at the time we make the move, but later on, we may discover that we are stuck and there is no safe move available for the next queen we are trying to place on the board, so we must backtrack. That means we will go back to the previous queen’s move, undo that move, and continue searching for another safe place to put that queen. We will use the stack to remember where we have placed queens on the board and when we need to back up, the queen at the top of the stack will be popped and we will use that queen’s position to resume the search for the next safe location.Stradegy below: There are N rows. When a queen is placed into a row, that row cannot be used by other queens. There are N columns. When a queen is placed into a column, that column cannot be used by other queens. There are 2 sets of diagonals to be concerned with, diagonals running upper left to lower right and diagonals running upper right to lower left. There is a simple mathematical relationship between N and the number of diagonals in each direction. When a queen is placed onto the board, one left to right diagonal is no longer safe for other queens, and one right to left diagonal is no longer safe for other queens. Our approach to placing the queens on the board will be to use nested loops. As an example the outer loop will be in control of which column we are currently searching for a spot to place a queen. So, the first queen we place will be in column 0, and when the outer loop has completed we will have placed N queens on the board, one in each column. The inner loop will iterate through the rows, from 0 to N-1 until it finds a row R such that row R is not taken by another queen, AND the 2 diagonals which intersect row R and the current column are not taken by another queen. IF we find such a safe location, we push the current row,
  • 2. column value onto a stack. Note: we can use the Java Point class to store the row and column numbers in the x, y values of a Point object. By placing a queen’s location information into the stack, we have affected the state of the board. We must update the state information to reflect that a row is no longer safe for other queens. We also must update the state of the two diagonals which intersect with the queen’s row, column position to indicate that those diagonals are no longer available to other queens to be placed later. After updating the state information, we can break out of the inner loop and continue on to the next column in the outer loop. The backtracking aspect of this exercise occurs when the inner loop fails to find a spot to place a queen in the current column. Inside the inner loop, we need to recognize that we have checked position (row N-1, current column) and found that it is not safe. Therefore there is no safe place for a queen in this column. Since we are stuck, we need to back up and try a different placement for the previously placed queen. To backtrack, we need to undo the actions taken when we placed the last queen onto the stack. That means pop the last queen off the stack, mark the row and diagonals associated with that queen’s position as available again, and reset the row and column loop control variables back to the point where they were when this queen was pushed onto the stack (ie row = poppedPoint.x, column = poppedPoint.y). After backtracking the row loop will continue to the next row to check if that row, column position is safe. I am providing you with a partially completed Java FX project for this project. The project I am giving you contains 2 classes. The GameBoard class provides methods for creation of the game board based on the size given to its constructor. It also provides methods for placing and removing a queen from a specific row, column position on the game board. The JavaFxQueens class is the main application class. It determines what size the game board is to be, creates an GameBoard object, and places the game board into a scene on the stage. It also starts up a thread which will find safe places on the board for all the queens. The placeQueens method in the JavaFxQueens class has not been completed. You must write the code needed to find safe locations for all the queens. Whenever you find a safe place and push a row, col position onto the stack, you must also call the placeQueen method on the GameBoard object to draw that queen on the board. Whenever you backtrack and pop a row, col position off the stack, you must also call the removeQueen method on the GameBoard object to remove that queen from the game board display. Note, that after calling either one of these 2 methods, you must call the delay method (which is provided) to slow down the rate at which moves are drawn on the board so that every queen placed or removed is visible on the display for a reasonable amount of time. Think very carefully about how you want to organize the data which captures the state of the game board (rows, diagonals). You do not need an actual representation of the game board (ie. no 2 dimensional array). Also think carefully about how to mathematically capture the
  • 3. relationship between a row, column position and which diagonals intersect that position. Part of creating efficient programs is designing clever data representations which can be accessed in very efficient ways from known information. here is the code: please copy the java queens class and the gameboard class into your ide and read the above to solve. ****javaQueens**** package javafxqueens; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javax.swing.JOptionPane; /** * * @author RVolkers */ public class JavaFxQueens extends Application implements Runnable { private GameBoard board; private int boardSize = 0; @Override public void start(Stage primaryStage) { // Get the size of the game board from the user. Must be at least 5. while(boardSize < 5) { boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board.")); } board = new GameBoard(boardSize); // The game board calculates how much display area it will need to display properly Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize()); primaryStage.setTitle("N Queens"); primaryStage.setScene(scene); primaryStage.show(); // Since the main thread is responsible for doing all the GUI updating, // we need a separate thread to process the placement of queens. That thread
  • 4. // will call methods on the GameBoard to tell the main thread where to place // or remove queens on the board. Thread thread = new Thread(this); thread.start(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } // Must do the main processing in a separate thread, so this class // implements the Runnable interface. @Override public void run() { // This thread calls a private method to figure out where the queens go placeQueens(); } // Used to slow down moves to enable seeing the board placement change // as each queen is placed or removed from the board private void delay() { try { Thread.sleep(500); } catch(InterruptedException e) { } } // Figure out where to place the queens here.... // Call placeQueen and removeQueen methods on the gameBoard object when needed private void placeQueens() { //insert new code here!
  • 5. } } ******gameboard****** package javafxqueens; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; /** * * @author RVolkers */ public class GameBoard extends GridPane { private final int ButtonSize = 110; private final int GapSize = 5; private int size; private Button[][] board; public GameBoard() { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = 8; createBoard(); } public GameBoard(int n) { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = n;
  • 6. createBoard(); } private void createBoard() { // Create an array to hold references to all the buttons on the board. board = new Button[size][size]; for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { // Create each button with alternating colors Button b = new Button(); b.setPrefSize(ButtonSize, ButtonSize); if ((row + col) % 2 == 0) { b.setStyle("-fx-background-color: red"); } else { b.setStyle("-fx-background-color: black"); } // Add the button to the board and to the GridPane board[row][col] = b; add(b, col, row); } } } // Calculate the size of the display based on the size // of the buttons and the size of the gaps between buttons. public double getDisplaySize() { return size * ButtonSize + (size + 1) * GapSize; } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by adding the queen graphic to the appropriate button on the board public void placeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds"); } Platform.runLater(() -> { board[row][col].setGraphic(new ImageView("queen.gif")); });
  • 7. } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by removing the queen graphic from the appropriate button on the board public void removeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds"); } Platform.runLater(() -> { board[row][col].setGraphic(null); }); } } Solution i add some methods for display the queens as Q and move the queens import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javax.swing.JOptionPane; public class JavaFxQueens extends Application implements Runnable { private GameBoard board; private int boardSize = 0; @Override public void start(Stage primaryStage) { // Get the size of the game board from the user. Must be at least 5. while(boardSize < 5) { boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board.")); } board = new GameBoard(boardSize); // The game board calculates how much display area it will need to display properly
  • 8. Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize()); primaryStage.setTitle("N Queens"); primaryStage.setScene(scene); primaryStage.show(); // Since the main thread is responsible for doing all the GUI updating, // we need a separate thread to process the placement of queens. That thread // will call methods on the GameBoard to tell the main thread where to place // or remove queens on the board. Thread thread = new Thread(this); thread.start(); } public static void main(String[] args) { launch(args); } // Must do the main processing in a separate thread, so this class // implements the Runnable interface. @Override public void run() { // This thread calls a private method to figure out where the queens go placeQueens(); } // Used to slow down moves to enable seeing the board placement change // as each queen is placed or removed from the board private void delay() { try { Thread.sleep(500); } catch(InterruptedException e) { } } // Figure out where to place the queens here.... // Call placeQueen and removeQueen methods on the gameBoard object when needed
  • 9. //here we need on method for display the queens public void showQueens(int[] s) { int n = s.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (s[i] == j) { System.out.print("Q"); } else { System.out.print(""); } } System.out.println(); } System.out.println(); } public void placeQueens(int p, int n) { for (int c = 0; c < n; c++) { if (placeQueens(p, c)) { s[r] = c; if (r == n - 1) { printQueens(s); } else { placeQueens(p + 1, n); } } } } public void callplaceNqueens() { placeQueens(0, s.length); } } ******gameboard****** package javafxqueens; import javafx.application.Platform; import javafx.geometry.Insets;
  • 10. import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; /** * * @author RVolkers */ public class GameBoard extends GridPane { private final int ButtonSize = 110; private final int GapSize = 5; private int size; private Button[][] board; public GameBoard() { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = 8; createBoard(); } public GameBoard(int n) { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = n; createBoard(); } private void createBoard() { // Create an array to hold references to all the buttons on the board. board = new Button[size][size]; for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) {
  • 11. // Create each button with alternating colors Button b = new Button(); b.setPrefSize(ButtonSize, ButtonSize); if ((row + col) % 2 == 0) { b.setStyle("-fx-background-color: red"); } else { b.setStyle("-fx-background-color: black"); } // Add the button to the board and to the GridPane board[row][col] = b; add(b, col, row); } } } // Calculate the size of the display based on the size // of the buttons and the size of the gaps between buttons. public double getDisplaySize() { return size * ButtonSize + (size + 1) * GapSize; } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by adding the queen graphic to the appropriate button on the board public void placeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds"); } Platform.runLater(() -> { board[row][col].setGraphic(new ImageView("queen.gif")); }); } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by removing the queen graphic from the appropriate button on the board public void removeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds");