In the last blog, Xiaobian has realized the compilation of the main interface of the jigsaw puzzle, but the panel of the jigsaw puzzle area and the panel of the preview area have not been completed. In this blog, Xiaobian takes the code to complete the rest of the code. Let's Go!!!!
Game puzzle area
The above figure is the effect to be displayed in our puzzle area, and the puzzle area is a JPanel. We will add the puzzle area to our main interface class:
Picturecanvaspane in our main interface class MainFrame is our game puzzle area Through the display effect of Figure 1, what does the class in our puzzle area contain?
It is easy to know from Figure 1 that the puzzle area contains 12 puzzle pieces, and the first 11 of the 12 puzzle pieces are pictures and the last one is a blank piece. Why do you want a blank piece? This is because if there are all pictures, we can't move the picture blocks and make puzzles, so the last blank block is to move the blocks. When we click the picture block, we will switch the picture block and the blank block, so as to realize the moving effect of the picture block
Similarly, our picture block is also abstracted into a class: PictureCell,
public class PictureCell extends JButton { private static final long serialVersionUID = -7205714777675652025L; public PictureCell(Icon icon) { super(icon); this.setSize(150, 150); } public void move(String direction){ if(direction != null && !direction.isEmpty()){ switch(direction){ case "up": this.setLocation(this.getBounds().x, this.getBounds().y - this.getHeight()); break; case "right": this.setLocation(this.getBounds().x + this.getWidth(), this.getBounds().y ); break; case "down": this.setLocation(this.getBounds().x, this.getBounds().y + this.getHeight()); break; case "left": this.setLocation(this.getBounds().x - this.getWidth(), this.getBounds().y ); break; } } } }
Through the above code, we find that the puzzle piece is a button, and we show the picture through Icon In addition, we specify that the size of each small block is 150 * 150, and define a moving method:
Let's analyze the method of move. Up means moving up. From the above figure, we know that moving up the picture block is to subtract the height of the block from the y-axis coordinate of the picture block, which is the y-axis coordinate of the moved picture block, and the x-axis coordinate does not need to be changed
Next, let's look at the code of our puzzle area:
public class PictureCanvasPanle extends JPanel implements MouseListener { private PictureCell[] cells = new PictureCell[12]; private Rectangle nullCell; public static int stepNum = 0; // Number of steps private boolean hasMouseListener = false;// Judge whether mouse monitoring is added. false is not true //.. Unfinished
cells are used to store 12 puzzle pieces, and nullCell is used as a blank piece,
Next, we write a method to add puzzle pieces:
public void addCell() { int length = cells.length; int width = 0; int height = 0; for (int i = 0; i < length; i++) { ImageIcon icon = new ImageIcon( MainFrame.selectedPicture.getSubPicPaths()[i]); if (i == 0) { width = icon.getIconWidth(); height = icon.getIconHeight(); } cells[i] = new PictureCell(icon); //Add picture cells[i].setSize(width, height); //Set the size of the puzzle piece cells[i].setLocation((i % 3) * width + 20, (i / 3) * height + 20); //Location of small blocks this.add(cells[i]); } this.remove(cells[length - 1]); //Remove the last picture block // Replace the blank area with a rectangle nullCell = new Rectangle((11 % 3) * width + 20, (11 / 3) * height + 20, width, height); //Create a blank block }
In the addCell() method, we loop to create 12 image blocks, delete the last image block, and create a blank block
After the puzzle pieces are created, we need to put 11 picture pieces and blank pieces out of order:
/** * Disrupt small squares */ public void start() { if (!hasMouseListener) { for (int i = 0; i < cells.length - 1; i++) { cells[i].addMouseListener(this); } // Update mouse monitoring status hasMouseListener = true; } // The first small square cannot be located at the four positions in the upper left corner. If it is located at the four positions in the upper left corner, the small square needs to be moved int width = cells[0].getWidth(); int height = cells[0].getHeight(); while (cells[0].getBounds().x <= width + 20 && cells[0].getBounds().y <= height + 20) { // Gets the position of the empty square int nullX = nullCell.getBounds().x; int nullY = nullCell.getBounds().y; // Randomly generate the moving direction of an empty square up, down, left, right int num = (int) (Math.random() * 4); String direction = ""; switch (num) { case 0: // The empty box moves up and the corresponding box moves down direction = "down"; nullY -= height; break; case 1: // The empty box moves to the right and the corresponding box moves to the left direction = "left"; nullX += width; break; case 2: // The empty box moves down and the corresponding box moves up direction = "up"; nullY += height; break; case 3: // The empty box moves to the left and the corresponding box moves to the right direction = "right"; nullX -= width; break; } cellMove(nullX, nullY, direction); } }
The scrambling strategy is that we can't let the first block be in the first position of our puzzle area. If it is in the first position, we will randomly exchange the blank block with the blocks around it, and keep cycling until the first block is not in the first position. The cycle ends and the scrambling is completed Moreover, the start() method is bound to the click event of the start button on the main interface. When a single user clicks start, the click event is triggered, and the start() method is called to start the game
Next, we need to bind mouse events to JPanel in the puzzle area to operate the movement of puzzle pieces:
/** Monitor mouse press */ @Override public void mousePressed(MouseEvent e) { // Get the clicked small box PictureCell btn = (PictureCell) e.getSource(); int clickX = btn.getBounds().x; int clickY = btn.getBounds().y; int width = btn.getWidth(); int height = btn.getHeight(); //Get the coordinates of the empty grid int nullX = nullCell.getBounds().x; int nullY = nullCell.getBounds().y; if(clickX == nullX && clickY - nullY == -height){//The clicked box is above the empty box btn.move("down"); }else if(clickX - nullX == width && clickY == nullY){//The clicked box is located to the right of the empty box btn.move("left"); }else if(clickX == nullX && clickY - nullY == height){//The clicked box is below the empty box btn.move("up"); }else if(clickX - nullX == -width && clickY == nullY){//The clicked box is located to the left of the empty box btn.move("right"); }else{ return; } //Move empty squares nullCell.setLocation(clickX, clickY); this.repaint(); stepNum++; MainFrame.stepTxt.setText("Number of steps:"+stepNum); //Judge whether it is completed if(isFinished()){ JOptionPane.showMessageDialog(this, "Congratulations on completing the puzzle,Steps used:"+stepNum); for (int i = 0; i < cells.length - 1; i++) { cells[i].removeMouseListener(this); } hasMouseListener = false; } }
The movement of puzzle pieces is to first move the puzzle pieces to the blank pieces, and then move the blank pieces to the puzzle pieces:
Finally, we need to write a method to judge whether the puzzle is completed:
private boolean isFinished() { int width = cells[0].getWidth(); int height = cells[0].getHeight(); for (int i = 0; i < cells.length - 1; i++) { int cellX = cells[i].getBounds().x; int cellY = cells[i].getBounds().y; if(((cellX-20)/width + (cellY-20)*3/height) != i ){ return false; } } return true; }
At this point, our puzzle area has been completed Next, we will complete the code of the preview area
Preview area
The code of the preview area is relatively simple. We only need to draw the complete picture of the puzzle area on the Panel of the preview area Well, not much to say, just go to the code:
public class PicturePreviewPanel extends JPanel { private String path; public PicturePreviewPanel() { super(); this.setBorder(new TitledBorder("Preview area")); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if(null == path || path.isEmpty()){ path = "image/1.jpg"; } ImageIcon imageIcon = new ImageIcon(path); Image image = imageIcon.getImage(); g.drawImage(image, 20, 15, 450, 600, this); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
We call g.drawImage(image, 20, 15, 450, 600, this); This line of code will draw the picture on our panel
At this time, we have finished all the coding. Thank you for reading
If the code wants the complete project of the puzzle game, please move to gitee to download. Here is the download address for you: