- import java.awt.Color;
- import java.awt.Container;
- import java.awt.GridLayout;
- import java.util.Random;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- public class ChessPaneCover {
- private final static int n = 4;
- static JButton[] button = new JButton[n*n];
- private static int amount = 0;
- static int[][] board = new int [n*n][n*n];
- static Color[] color = {Color.white,Color.pink,Color.blue,Color.CYAN,Color.green,Color.orange};
- public static void main(String[] args) {
- new ChessPaneCover().frameLaunch();
- }
- public static void frameLaunch(){
- JFrame frame = new JFrame("残缺棋盘覆盖");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(n*150, n*150);
- frame.setLocation(100,100);
- JPanel panel = new JPanel();
- panel.setLayout(new GridLayout(n,n,0,0));
- for (int i = 0; i < n*n; i++) {
- button[i] = new JButton();
- button[i].setBackground(Color.gray);
- panel.add(button[i]);
- }
- Random random = new Random();
- int temp = random.nextInt(16);
- cover(0,0,temp/n,temp%n,n);
- outputBoard(n);
- button[temp].setText("残");
- button[temp].setBackground(Color.black);
- frame.add(panel);
- frame.setResizable(false);
- frame.setVisible(true);
- }
- public static void cover(int tr, int tc, int dr, int dc, int size) {
- int s,t;
- if(size < 2){
- return;
- }
- amount++;
- t = amount;
- s = size/2;
- if(dr < tr + s && dc < tc + s){
- cover(tr,tc,dr,dc,s);
- board[tr + s - 1][tc + s] = t;
- board[tr + s][tc + s - 1] = t;
- board[tr + s][tc + s] = t;
- cover(tr, tc+s, tr+s-1, tc+s, s);
- cover(tr+s, tc, tr+s, tc+s-1, s);
- cover(tr+s, tc+s, tr+s, tc+s, s);
- }
- else if(dr < tr + s && dc >= tc + s){
- cover(tr,tc+s,dr,dc,s);
- board[tr + s - 1][tc + s - 1] = t;
- board[tr + s][tc + s - 1] = t;
- board[tr + s][tc + s] = t;
- cover(tr, tc, tr+s, tc+s-1, s);
- cover(tr+s, tc, tr+s, tc+s-1, s);
- cover(tr+s, tc+s, tr+s, tc+s, s);
- }
- else if(dr >= tr + s && dc < tc + s){
- cover(tr+s,tc,dr,dc,s);
- board[tr + s - 1][tc + s - 1] = t;
- board[tr + s - 1][tc + s] = t;
- board[tr + s][tc + s] = t;
- cover(tr, tc, tr+s-1, tc+s - 1, s);
- cover(tr, tc+s, tr+s-1, tc+s, s);
- cover(tr+s, tc+s, tr+s, tc+s, s);
- }
- else if(dr >= tr + s && dc >= tc + s){
- cover(tr+s,tc+s,dr,dc,s);
- board[tr + s - 1][tc + s -1] = t;
- board[tr + s - 1][tc + s] = t;
- board[tr + s][tc + s - 1] = t;
- cover(tr, tc, tr+s-1, tc+s-1, s);
- cover(tr, tc+s, tr+s-1, tc+s-1, s);
- cover(tr+s, tc+s, tr+s, tc+s-1, s);
- }
- }
- public static void outputBoard(int size){
- for(int i = 0; i < size; i++){
- for(int j = 0; j < size; j++){
- button[i*n+j].setBackground(color[board[i][j]]);
- button[i*n+j].setText("" + board[i][j]);
- }
- }
- }
- }