请编写八皇后游戏程序(要求采用图形界面):设计一个8×8的棋盘,允许用户在棋盘的格子上放置8个皇后(国际象棋中的棋子)。要求每两个皇后不能处于同一条横线,竖线和45度或135度的斜线上(即按国际象棋的规则要求任意两个皇后不能处于直接可以互相攻击的状态)。如果用户放置的棋子不符合上面要求,则程序给出错误显示,并请设计某种比较直观的方式标出可以互相攻击的两个皇后,然后要求重新放置该棋子。当8个皇后全部放在棋盘上,且任意两个皇后不能互相攻击,则显示成功的信息和所用的时间。
package 八皇后;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.security.PublicKey;
import java.util.*;
import javax.security.auth.PrivateCredentialPermission;
import javax.swing.*;
import org.omg.CORBA.PRIVATE_MEMBER;
public class Queen extends JFrame{
private JButton[][] button=new JButton[8][8];
boolean gameOver;
private int num=0;
long time1=new Date().getTime();
boolean full=true;
public Queen(){
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
button[i][j]=new JButton("");
}
}
Container c=this.getContentPane();
c.setLayout(new GridLayout(8, 8));
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
c.add(button[i][j]);
button[i][j].addActionListener(new Handler(i,j));
}
}
}
class Handler implements ActionListener{
private int i,j;
public Handler(int row,int col){
i=row;
j=col;
}
public void paint(int i,int j){
//水平线画绿线
for(int x=0;x<8;x++){
button[x][j].setBackground(Color.GREEN);
}
//竖直线画绿线
for(int y=0;y<8;y++){
button[i][y].setBackground(Color.GREEN);
}
//斜线上画绿线
for(int x=0;x<8;x++){
for(int y=0;y<8;y++){
if(Math.abs(x-i)==Math.abs(y-j)){
button[x][y].setBackground(Color.GREEN);
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(gameOver)
JOptionPane.showMessageDialog(null, "游戏已结束");
else if(button[i][j].getBackground()==Color.GREEN||button[i][j].getBackground()==Color.BLACK){
JOptionPane.showMessageDialog(null, "位置冲突或位置重复");
}else{
full=true;
num++;
paint(i,j);
button[i][j].setBackground(Color.BLACK);
for(int x=0;x<8;x++){
for(int y=0;y<8;y++){
// System.out.println(button[x][y].getBackground());
if(button[x][y].getBackground()==Color.GREEN||button[x][y].getBackground()==Color.BLACK)
continue;
else{
full=false;
System.out.println(x+" "+y);
break;
}
}
}
System.out.println(full);
if(full&&num!=8)
JOptionPane.showMessageDialog(null, "游戏失败!");
if(num==8){
gameOver=true;
long time2=new Date().getTime();
String time=String.valueOf(time2-time1);
JOptionPane.showMessageDialog(null, "恭喜获胜!用时: "+time);
}
}
}
}
public static void main(String[] args){
Queen queen=new Queen();
queen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
queen.setSize(400,400);
queen.setVisible(true);
}
}
效果图: