import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
public class Board extends JPanel
{
private int[] queenList=new int[8];
public Board()
{
queens(queenList,2);
this.setBorder(new EtchedBorder(EtchedBorder.RAISED,Color.WHITE,new Color(148,145,140)));
}
public static boolean safeLocation(int row,int col,int[]queenList)
{
int qRow,qCol;
for(qCol=0;qCol<col;qCol++)
{
qRow=queenList[qCol];
if(qRow==row)
return false;
else if(qCol==col)
return false;
else if(qCol-qRow==col-row||qCol+qRow==col+row)
{
return false;
}
}
return true;
}
public static boolean queens(int[]queenList,int row)
{
queenList[0]=row;
if(placeQueens(queenList,1))
{
return true;
}
else
return false;
}
public static boolean placeQueens(int[]queenList,int col)
{
int row=0;
boolean foundLocation;
if(col==8)
foundLocation=true;
else
{
foundLocation=false;
row=0;
}
while(row<8&&!foundLocation)
{
if(safeLocation(row,col,queenList))
{ queenList[col]=row;
foundLocation=placeQueens(queenList,col+1);
if(!foundLocation)
row++;
}
else
row++;
}
return foundLocation;
}
public void paintComponent(Graphics g)
{
boolean white=true;
super.paintComponent(g);
g.setColor(Color.BLACK);
for(int i=0;i<8;i++)
{
if(i%2==0)
{
white=false;
}
else
{
white=true;
}
for(int j=0;j<8;j++)
{
if(queenList[j]==i)
{
g.setColor(Color.ORANGE);
if(white)
{
white=false;
}
else
{
white=true;
}
}
else if(white)
{
g.setColor(Color.WHITE);
white=false;
}
else
{
g.setColor(Color.BLACK);
white=true;
}
g.fill3DRect(j*50, i*50,50,50,true);
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class GUI extends JFrame
{
Board gameboard;
public GUI()
{
setTitle("八皇后");
setSize(410,440);
this.setResizable(false);
Dimension scrSize=Toolkit.getDefaultToolkit().getScreenSize();
Container container=getContentPane();
setLayout(new BorderLayout());
setLocation((scrSize.width-getSize().width)/2,(scrSize.height-getSize().height)/2);
gameboard=new Board();
add(gameboard,BorderLayout.CENTER);
}
public static void main(String[]args)
{
new GUI().setVisible(true);
}
}