扫雷java代码思路 java实现扫雷游戏( 二 )


}
if(i+1allButtons.length){
num+=(allButtons[i+1][j].getCountOfSurroundMines()==-1?1:0);
}
if(i+1allButtons.lengthj+1allButtons[0].length){
num+=(allButtons[i+1][j+1].getCountOfSurroundMines()==-1?1:0);
}
return num;
}
/**
* 生成按钮
*
*/
private void createButtons(){
for(int i=0;iallButtons.length;i++){
for(int j=0;jallButtons[i].length;j++){
allButtons[i][j]=new MineButton(i,j);
allButtons[i][j].setSize(6,6);
allButtons[i][j].addActionListener(this);//添加点击事件监听
allButtons[i][j].addMouseListener(new MouseAdapter(){//添加鼠标右键事件监听
public void mouseClicked(MouseEvent e) {
if(e.getButton()==MouseEvent.BUTTON3){
int remain=Integer.parseInt(CleanMine.remainMine.getText());
JButton b=(JButton)e.getSource();
if(b.getText().equals("")){
remain--;
CleanMine.remainMine.setText(remain+"");
b.setText("");
}else if(b.getText().equals("")){
remain++;
CleanMine.remainMine.setText(remain+"");
b.setText("");
}
}
}
});
}
}
}
public void actionPerformed(ActionEvent e) {//点击事件监听的方法
MineButton b=(MineButton)e.getSource();
int r=b.getRow();
int c=b.getCol();
if(allButtons[r][c].getCountOfSurroundMines()==-1){//如果是地雷
for(int i=0;iallButtons.length;i++){//把所有按钮都显示出来
for(int j=0;jallButtons[i].length;j++){
if(allButtons[i][j].getCountOfSurroundMines()==-1){//如果该位置是地雷
allButtons[i][j].setText("$");
}else if(allButtons[i][j].getCountOfSurroundMines()==0){//如果该位置为空(该位置不是地雷 , 周围8个位置也没有地雷)
allButtons[i][j].setText("");
allButtons[i][j].setBackground(Color.CYAN);
}else{//如果该位置不是地雷,但周围8个位置中有地雷
allButtons[i][j].setText(allButtons[i][j].getCountOfSurroundMines()+"");
allButtons[i][j].setBackground(Color.CYAN);
}
}
}
}else{//如果不是地雷
showEmpty(r,c);//执行排空操作
}
}
/**
* 排空方法,若(i,j)位置为空,则显示空白 。然后依次递归找它周围的8个位置 。
* @param data
* @param i
* @param j
*/
private void showEmpty(int i,int j){
MineButton b=allButtons[i][j];
if(b.isCleared()){
return;
}
if(allButtons[i][j].getCountOfSurroundMines()==0){
b.setBackground(Color.CYAN);
b.setCleared(true);
if(i-1=0j-1=0){
showEmpty(i-1,j-1);
}
if(i-1=0){
showEmpty(i-1,j);
}
if(i-1=0j+1allButtons[0].length){
showEmpty(i-1,j+1);
}
if(j-1=0){
showEmpty(i,j-1);
}
if(j+1allButtons[0].length){
showEmpty(i,j+1);
}
if(i+1allButtons.lengthj-1=0){
showEmpty(i+1,j-1);
}
if(i+1allButtons.length){
showEmpty(i+1,j);
}
if(i+1allButtons.lengthj+1allButtons[0].length){
showEmpty(i+1,j+1);
}
}else if(allButtons[i][j].getCountOfSurroundMines()0){
b.setText(allButtons[i][j].getCountOfSurroundMines()+"");
b.setBackground(Color.CYAN);
b.setCleared(true);
}
}
}
第二个JAVA文件
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 扫雷游戏主界面
* @author tony.tang
*
*/
public class CleanMine extends JFrame implements ActionListener{
private JLabel text1,text2;
public static JLabel remainMine;//剩余地雷数
private JLabel time;//消耗时间
private JButton reset;//重新开始
private JPanel center;
private int row,col,mine;
public CleanMine(){
text1=new JLabel("剩余地雷:");

推荐阅读