must enter code in student code goes here area. Working with Layout Managers. No
ID: 3784006 • Letter: M
Question
must enter code in student code goes here area. Working with Layout Managers. Notes: 1. In part 2, note that the Game class inherits from JPanel. Therefore, the panel you are asked to add to the center of the content pane is the "game" object. 2. In part 4, at the end of the function, call validate(). This is not mentioned in the book, but it is mentioned in the framework comments. Upload your zipped assignment folder, which contains the java and class files. / import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Game extends JPanel { private JButton [][] squares; private TilePuzzle game; public Game( int newSide ) { game = new TilePuzzle( newSide ); setUpGameGUI( ); } public void setUpGame( int newSide ) { game.setUpGame( newSide ); setUpGameGUI( ); } public void setUpGameGUI( ) { removeAll( ); // remove all components setLayout( new GridLayout( game.getSide( ), game.getSide( ) ) ); squares = new JButton[game.getSide( )][game.getSide( )]; ButtonHandler bh = new ButtonHandler( ); // for each button: generate button label, // instantiate button, add to container, // and register listener for ( int i = 0; i < game.getSide( ); i++ ) { for ( int j = 0; j < game.getSide( ); j++ ) { squares[i][j] = new JButton( game.getTiles( )[i][j] ); add( squares[i][j] ); squares[i][j].addActionListener( bh ); } } setSize( 300, 300 ); setVisible( true ); } private void update( int row, int col ) { for ( int i = 0; i < game.getSide( ); i++ ) { for ( int j = 0; j < game.getSide( ); j++ ) { squares[i][j].setText( game.getTiles( )[i][j] ); } } if ( game.won( ) ) { JOptionPane.showMessageDialog( Game.this, "Congratulations! You won! Setting up new game" ); // int sideOfPuzzle = 3 + (int) ( 4 * Math.random( ) ); // setUpGameGUI( ); } } private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent ae ) { for( int i = 0; i < game.getSide( ); i++ ) { for( int j = 0; j < game.getSide( ); j++ ) { if ( ae.getSource( ) == squares[i][j] ) { if ( game.tryToPlay( i, j ) ) update( i, j ); return; } // end if } // end inner for loop } // outer for loop } // end actionPerformed method } // end ButtonHandler class } // end Game class import javax.swing.*; import java.awt.*; import java.awt.event.*; public class NestedLayoutPractice extends JFrame { private Container contents; private Game game; private BorderLayout bl; private JLabel bottom; // ***** Task 1: declare a JPanel named top // also declare three JButton instance variables // that will be added to the JPanel top // these buttons will determine the grid size of the game: // 3-by-3, 4-by-4, or 5-by-5 // Part 1 student code starts here: // Part 1 student code ends here. public NestedLayoutPractice() { super("Practicing layout managers"); contents = getContentPane(); // ***** Task 2: // instantiate the BorderLayout manager bl // Part 2 student code starts here: // set the layout manager of the content pane contents to bl: game = new Game(3); // instantiating the GamePanel object // add panel (game) to the center of the content pane // Part 2 student code ends here. bottom = new JLabel("Have fun playing this Tile Puzzle game", SwingConstants.CENTER); // ***** Task 3: // instantiate the JPanel component named top // Part 3 student code starts here: // set the layout of top to a 1-by-3 grid // instantiate the JButtons that determine the grid size // add the buttons to JPanel top // add JPanel top to the content pane as its north component // Part 3 student code ends here. // ***** Task 5: // Note: search for and complete Task 4 before performing this task // Part 5 student code starts here: // declare and instantiate an ActionListener // register the listener on the 3 buttons // that you declared in Task 1 // Part 5 student code ends here. contents.add(bottom, BorderLayout.SOUTH); setSize(325, 325); setVisible(true); } // ***** Task 4: // create a private inner class that implements ActionListener // your method should identify which of the 3 buttons // was the source of the event // depending on which button was pressed, // call the setUpGame method of the Game class // with arguments 3, 4, or 5 // the API of that method is: // public void setUpGame(int nSides) // At the end of the method call validate() // Part 4 student code starts here: // Part 4 student code ends here. public static void main(String[] args) { NestedLayoutPractice nl = new NestedLayoutPractice(); nl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } /* TilePUzzle class Anderson, Franceschi */ public class TilePuzzle { private int side; // grid size for game 1 private String[][] tiles; private int emptyRow; private int emptyCol; public TilePuzzle( int newSide ) { setUpGame( newSide ); } public void setUpGame( int newSide ) { if ( side > 0 ) side = newSide; else side = 3; side = newSide; tiles = new String[side][side]; emptyRow = side - 1; emptyCol = side - 1; for ( int i = 0; i < side; i++ ) { for ( int j = 0; j < side; j++ ) { tiles[i][j] = String.valueOf( ( side * side ) - ( side * i + j + 1 ) ); } } // set empty tile to blank tiles[side - 1][side - 1] = ""; } public int getSide( ) { return side; } /* public int getEmptyRow( ) { return emptyRow; } public int getEmptyCol( ) { return emptyCol; } */ public String[][] getTiles( ) { return tiles; } public boolean tryToPlay( int row, int col ) { if ( possibleToPlay( row, col ) ) { // play: switch empty String and tile label at row, col tiles[emptyRow][emptyCol] = tiles[row][col]; tiles[row][col] = ""; emptyRow = row; emptyCol = col; return true; } else return false; } public boolean possibleToPlay( int row, int col ) { if ( ( col == emptyCol && Math.abs( row - emptyRow ) == 1 ) || ( row == emptyRow && Math.abs( col - emptyCol ) == 1 ) ) return true; else return false; } public boolean won( ) { for ( int i = 0; i < side ; i++ ) { for ( int j = 0; j < side; j++ ) { if ( !( tiles[i][j].equals( String.valueOf( i * side + j + 1 ) ) ) && ( i != side - 1 || j != side - 1 ) ) return false; } } return true; } }
Explanation / Answer
#include <vector> #include <iostream> #include <iomanip> #include <thread> #include <future> // Print table. 'pos' is a vector of positions – the index in pos is the row, // and the number at that index is the column where the queen is placed. static void print(const std::vector<int> &pos) { // print table header for (int i = 0; i < pos.size(); i++) { std::cout << std::setw(3) << char('a' + i); } std::cout << ' '; for (int row = 0; row < pos.size(); row++) { int col = pos[row]; std::cout << row + 1 << std::setw(3 * col + 3) << " # "; std::cout << ' '; } std::cout << " "; } static bool threatens(int row_a, int col_a, int row_b, int col_b) { return row_a == row_b // same row or col_a == col_b // same column or std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal } // the i-th queen is in the i-th row // we only check rows up to end_idx // so that the same function can be used for backtracking and checking the final solution static bool good(const std::vector<int> &pos, int end_idx) { for (int row_a = 0; row_a < end_idx; row_a++) { for (int row_b = row_a + 1; row_b < end_idx; row_b++) { int col_a = pos[row_a]; int col_b = pos[row_b]; if (threatens(row_a, col_a, row_b, col_b)) { return false; } } } return true; } static std::mutex print_count_mutex; // mutex protecting 'n_sols' static int n_sols = 0; // number of solutions // recursive DFS backtracking solver static void n_queens(std::vector<int> &pos, int index) { // if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return if (index >= pos.size()) { if (good(pos, index)) { std::lock_guard<std::mutex> lock(print_count_mutex); print(pos); n_sols++; } return; } // backtracking step if (not good(pos, index)) { return; } // optimization: the first level of the search tree is parallelized if (index == 0) { std::vector<std::future<void>> fts; for (int col = 0; col < pos.size(); col++) { pos[index] = col; auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); }); fts.push_back(std::move(ft)); } for (const auto &ft : fts) { ft.wait(); } } else { // deeper levels are not for (int col = 0; col < pos.size(); col++) { pos[index] = col; n_queens(pos, index + 1); } } } int main() { std::vector<int> start(12); // 12: table size n_queens(start, 0); std::cout << n_sols << " solutions found. "; return 0; }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.