📄 mines.java
字号:
/*
该类实现了本实例的基本逻辑,它通过指定的大小构造了游戏区域
并且将适当数目的雷埋入该区域中,
同时,该类还实现了设置变量的公有方法
注意:虽然Mines类支持不同数目和大小的雷,但是本实例不支持
*/
import java.util.*;
import java.awt.*;
class mines {
final static int MINE=16;
final static int SCOPERTA=32;
final static int MASK=31;
/* 下面解释了每个数字所表示的意义:
5 4 3 2 1 0
. . . . . .
32 16 8 4 2 1
| | | | | |
| | -------------- 作为cell的保留值(从o到8)
| ------------------表示雷
----------------------表示该cell已经被用户访问过
*/
// play_field 是游戏区数组
private int[] play_field=null;
public Vector toShow = new Vector();
// 区域大小以及雷的数目
private int rows,cols,num_mines;
// 构造函数
public mines(int rows,int cols,int num_mines) {
this.rows=rows;
this.cols=cols;
this.num_mines=num_mines;
play_field=new int[rows*cols];
FillPlayfield();
}
public int Rows() { return rows; }
public int Cols() { return cols; }
public int Mines() { return num_mines; }
public int get_play_field(int i,int j){
if (i<0 || i>rows-1 || j<0 || j>cols-1){ return 0; }
return play_field[i*rows+j];
}
public int get_play_field(int i){
return play_field[i];
}
public void set_play_field(int i,int j,int value){
play_field[i*rows+j]=value;
}
public void set_play_field(int i,int value){
play_field[i]=value;
}
// 填充游戏区域
private void FillPlayfield() {
int i=0,j=0,r=0;
// 产生雷
while (i<num_mines){
do {
r=(int)(Math.random()*rows*cols);
} while (play_field[r]==MINE);
play_field[r]=MINE;
i++;
}
int howmuch=0;
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
if (get_play_field(i,j)!=MINE){
try {if (get_play_field(i-1,j-1)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
try {if (get_play_field(i-1,j)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
try {if (get_play_field(i-1,j+1)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
try {if (get_play_field(i,j-1)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
try { if (get_play_field(i,j+1)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
try {if (get_play_field(i+1,j-1)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
try {if (get_play_field(i+1,j)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
try { if (get_play_field(i+1,j+1)==MINE) howmuch++;}catch(ArrayIndexOutOfBoundsException e){};
set_play_field(i,j,howmuch);
howmuch=0;
}
}
}
}
/*
显示每个cell周围情况的方法
*/
public void Show(int i,int j){
if (i>=0 && i<rows && j>=0 && j<cols){
if ((get_play_field(i,j) & SCOPERTA) != SCOPERTA){
if (get_play_field(i,j) ==0) {
toShow.addElement(new Integer(i*rows+j));
set_play_field(i,j,get_play_field(i,j)|SCOPERTA);
Show(i-1,j-1);
Show(i-1,j);
Show(i-1,j+1);
Show(i,j-1);
Show(i,j+1);
Show(i+1,j-1);
Show(i+1,j);
Show(i+1,j+1);
}else{
toShow.addElement(new Integer(i*rows+j));
set_play_field(i,j,get_play_field(i,j)|SCOPERTA);
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -