⑴ 求高手幫忙一個「掃雷」游戲的java的程序代碼
import javax.swing.ImageIcon; //程序入口
public class Block {
String name; //名字,比如"雷"或數字
int aroundMineNumber; //周圍雷的數目
ImageIcon mineIcon; //雷的圖標
boolean isMine=false; //是否是雷
boolean isMark=false; //是否被標記
boolean isOpen=false; //是否被挖開
public void setName(String name) {
this.name=name;
}
//設置周圍的雷數
public void setAroundMineNumber(int n) {
aroundMineNumber=n;
}
//獲得周圍的雷數
public int getAroundMineNumber() {
return aroundMineNumber;
}
public String getName() {
return name;
}
//判斷是否是雷
public boolean isMine() {
return isMine;
}
//設置是否為雷
public void setIsMine(boolean b) {
isMine=b;
}
//設置雷的圖標
public void setMineIcon(ImageIcon icon){
mineIcon=icon;
}
//獲得雷的圖標
public ImageIcon getMineicon(){
return mineIcon;
}
//確定雷是否被挖開
public boolean getIsOpen() {
return isOpen;
}
//設置為已經被挖開
public void setIsOpen(boolean p) {
isOpen=p;
}
//返回此處是否已經被標記
public boolean getIsMark() {
return isMark;
}
//設置此處是否已經被標記
public void setIsMark(boolean m) {
isMark=m;
}
import javax.swing.*;
import java.awt.*;
public class BlockView extends JPanel{
JLabel blockNameOrIcon; //用來顯示Block對象的name、number和mineIcon屬性
JButton blockCover; //用來遮擋blockNameOrIcon.
CardLayout card; //卡片式布局
BlockView(){
card=new CardLayout();
setLayout(card);
blockNameOrIcon=new JLabel("",JLabel.CENTER);
blockNameOrIcon.setHorizontalTextPosition(AbstractButton.CENTER);
blockNameOrIcon.setVerticalTextPosition(AbstractButton.CENTER);
blockCover=new JButton();
add("cover",blockCover);
add("view",blockNameOrIcon);
}
//給出視覺效果變化
public void giveView(Block block){
// 如果是雷,將對應的圖標和文字更改
if(block.isMine){
blockNameOrIcon.setText(block.getName());
blockNameOrIcon.setIcon(block.getMineicon());
}
else {
int n=block.getAroundMineNumber();
if(n>=1)
blockNameOrIcon.setText(""+n);
else
blockNameOrIcon.setText(" ");
}
}
public void seeBlockNameOrIcon(){
card.show(this,"view");
validate();
}
public void seeBlockCover(){
card.show(this,"cover");
validate();
}
public JButton getBlockCover(){
return blockCover;
}
}
⑵ 怎樣用JAVA實現掃雷游戲
要詳細代碼?還是只要啟動?
java編寫實現,代碼如下:import Java.awt.*;
import java.awt.event.*;
import javax.Swing.*;
/*按扭類*/
class Bomb extends JButton
{
public int num_x,num_y; //第幾號方塊
public int BombRoundCount; //周圍雷數
public boolean isBomb; //是否為雷
public boolean isClicked; //是否被點擊
public int BombFlag; //探雷標記
public boolean isRight; //是否點擊右鍵
public Bomb(int x,int y)
{
BombFlag = 0;
num_x = x;
num_y = y;
BombRoundCount = 0;
isBomb = false;
isClicked = false;
isRight = false;
}
}
/*窗口及演算法實現類*/
class MainBomb extends JFrame implements ActionListener,MouseListener
{
public JTextField text;
public Label nowBomb,setBomb;
public int BlockNum,BombNum; //當前方塊數當前雷數
public Icon icon_bomb = new ImageIcon("Bomb.gif"); //踩雷
public Icon icon_bomb_big = new ImageIcon("bomb_big.gif"); //踩雷標記
public Icon icon_flag = new ImageIcon("flag.gif"); //雷標記
public Icon icon_question = new ImageIcon("question.gif"); //疑惑是否有雷
public JButton start = new JButton(" 開始 ");
public Panel MenuPamel = new Panel();
public Panel mainPanel = new Panel();
public Bomb[][] bombButton;
/*界面設計*/
public MainBomb()
{
super("掃雷 Aaron2004製作 2004.8 ");
BlockNum = 64;
BombNum = 10;
Container c=getContentPane();
c.setBackground(Color.gray);
c.setLayout(new BorderLayout());
text=new JTextField("10 ",3);
nowBomb = new Label("當前雷數"+" "+BombNum+"");
setBomb= new Label("設置地雷數");
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
BombNum = Integer.parseInt(text.getText().trim());
if(BombNum >= 10 && BombNum < 50 )
replay();
else
{
JOptionPane msg = new JOptionPane();
JOptionPane.showMessageDialog(null,"您設置的地雷數太多了,請重設!","錯誤",2);
}
}
} );
MenuPamel.add(setBomb);
MenuPamel.add(text);
MenuPamel.add(start);
MenuPamel.add(nowBomb);
c.add(MenuPamel,"North");
mainPanel.setLayout(new GridLayout( (int)Math.sqrt(BlockNum) , (int)Math.sqrt(BlockNum)) );
bombButton=new Bomb[ (int)Math.sqrt(BlockNum) ][];
for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++)
{
bombButton[ i ]=new Bomb[ (int)Math.sqrt(BlockNum) ];
}
for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++ )
for(int j = 0 ; j < (int)Math.sqrt(BlockNum) ; j++ )
{
bombButton[ i ][ j ]=new Bomb(i,j);
bombButton[ i ][ j ].setForeground( Color.gray);
bombButton[ i ][ j ].addActionListener(this);
bombButton[ i ][ j ].addMouseListener(this);
}
for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++ )
for(int j = 0 ; j < (int)Math.sqrt(BlockNum) ; j++ )
mainPanel.add(bombButton[ i ][ j ]);
c.add(mainPanel,"Center");
startBomb();
setSize(400,400);
setLocation(350,200);
setResizable(false);
}
/*布雷*/
public void startBomb()
{
for(int i=0;i<BombNum;i++)
{
int x =(int)(Math.random()*(int)(Math.sqrt(BlockNum)-1));
int y =(int)(Math.random()*(int)(Math.sqrt(BlockNum)-1));
if(bombButton[ x ][ y ].isBomb==true)
i--;
else
bombButton[ x ][ y ].isBomb=true ;
}
}
/*重新開始*/
public void replay()
{
nowBomb.setText("當前雷數"+" "+BombNum+"");
for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++)
for(int j = 0 ; j < (int)Math.sqrt(BlockNum) ; j++)
{
bombButton[ i ][ j ].isBomb=false;
bombButton[ i ][ j ].isClicked=false;
bombButton[ i ][ j ].setEnabled(true);
bombButton[ i ][ j ].setText("");
bombButton[ i ][ j ].setIcon(null);
}
startBomb();
}
/*是否挖完了所有的雷*/
public void isWin()
{
int findBomb=0; //找到的地雷數
for(int i = 0;i < (int)Math.sqrt(BlockNum) ; i++)
for(int j = 0;j < (int)Math.sqrt(BlockNum ); j++)
{
if(bombButton[ i ][ j ].isBomb == true && bombButton[ i ][ j ].isRight == true)
findBomb++;
}
if( findBomb == Integer.parseInt(text.getText().trim()) )
{
JOptionPane msg = new JOptionPane();
JOptionPane.showMessageDialog(this,"您挖完了所有的雷,您勝利了!","您勝利了",2);
}
}
/*計算方塊周圍雷數 */
public void CountRoundBomb()
{
for (int i = 0; i < (int)Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int)Math.sqrt(BlockNum); j++) {
int count = 0;
//當需要檢測的單元格本身無地雷的情況下,統計周圍的地雷個數
if (bombButton[ i ][ j ].isBomb != true) {
if ( (i - 1 >= 0) && (j - 1 >= 0)) {
if (bombButton[i - 1][j - 1].isBomb == true) {
count += 1; //檢測左上方空格是否是地雷
}
}
if ( (i - 1 >= 0)) {
if (bombButton[i - 1][ j ].isBomb == true) {
count += 1; //檢測上方空格是否為地雷
}
}
if ( (i - 1 >= 0) && (j + 1 <= (int)Math.sqrt(BlockNum)-1)) {
if (bombButton[i - 1][j + 1] .isBomb == true) {
count += 1; //檢測右上方是否為地雷
}
}
if ( (j - 1 >= 0)) {
if (bombButton[ i ][j - 1] .isBomb == true) {
count += 1; //檢測左邊是否為地雷
}
}
if ( (i >= 0) && (j + 1 <= (int)Math.sqrt(BlockNum)-1)) {
if (bombButton[ i ][j + 1].isBomb == true) {
count += 1; //右邊
}
}
if ( (j - 1 >= 0) && (i + 1 <= (int)Math.sqrt(BlockNum)-1)) {
if (bombButton[i + 1][j - 1].isBomb == true) {
count += 1; //左下
}
}
if ( (i + 1 <= (int)Math.sqrt(BlockNum)-1)) {
if (bombButton[i + 1][ j ].isBomb == true) {
count += 1; //下
}
}
if ( (j + 1 <= (int)Math.sqrt(BlockNum)-1) && (i + 1 <= Math.sqrt(BlockNum)-1)) {
if (bombButton[i + 1][j + 1].isBomb == true) {
count += 1; //右下
}
}
bombButton[ i ][ j ].BombRoundCount = count;
}
}
}
}
/**當選中的位置為空,則翻開周圍的地圖**/
public void isNull(Bomb[][] bombButton,Bomb ClickecButton)
{
int i,j;
i=ClickecButton.num_x;
j=ClickecButton.num_y;
if (ClickecButton.isBomb==true) {
}
else {
if ( (i - 1 >= 0) && (j - 1 >= 0)) { //檢測左上方空格是否是空
if (bombButton[i - 1][j - 1].isBomb == false && bombButton[i - 1][j - 1].isClicked == false && bombButton[i - 1][j - 1].isRight == false) {
bombButton[i - 1][j - 1].setText((bombButton[i - 1][j - 1].BombRoundCount)+"");
bombButton[i - 1][j - 1].setEnabled(false);
bombButton[i - 1][j - 1].isClicked=true;
}
}
if ( (i - 1 >= 0)) { //檢測上方空格是否為空
if (bombButton[i - 1][ j ] .isBomb == false && bombButton[i - 1][ j ].isClicked == false && bombButton[i - 1][ j ].isRight == false) {
bombButton[i - 1][ j ].setText((bombButton[i - 1][ j ].BombRoundCount)+"");
bombButton[i - 1][ j ].setEnabled(false);
bombButton[i - 1][ j ].isClicked=true;
}
}
if ( (i - 1 >= 0) && (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //檢測右上方是否為空
if (bombButton[i - 1][j + 1] .isBomb == false && bombButton[i - 1][j + 1].isClicked == false && bombButton[i - 1][j + 1].isRight == false) {
bombButton[i - 1][j + 1].setText((bombButton[i - 1][j + 1].BombRoundCount)+"");
bombButton[i - 1][j + 1].setEnabled(false);
bombButton[i - 1][j + 1].isClicked=true;
}
}
if ( (j - 1 >= 0)) { //檢測左邊是否為空
if (bombButton[ i ][j - 1].isBomb == false && bombButton[ i ][j - 1].isClicked == false && bombButton[ i ][j - 1].isRight == false) {
bombButton[ i ][j - 1].setText((bombButton[ i ][j - 1].BombRoundCount)+"");
bombButton[ i ][j - 1].setEnabled(false);
bombButton[ i ][j - 1].isClicked=true;
}
}
if ( (i >= 0) && (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //檢測右邊空格是否是空
if (bombButton[ i ][j + 1].isBomb == false && bombButton[ i ][j + 1].isClicked == false && bombButton[ i ][j + 1].isRight == false) {
bombButton[ i ][j + 1].setText((bombButton[ i ][j + 1].BombRoundCount)+"");
bombButton[ i ][j + 1].setEnabled(false);
bombButton[ i ][j + 1].isClicked=true;
}
}
if ( (j - 1 >= 0) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //檢測左下空格是否是空
if (bombButton[i + 1][j - 1].isBomb == false && bombButton[i + 1][j - 1].isClicked == false && bombButton[i + 1][j - 1].isRight == false) {
bombButton[i + 1][j - 1].setText((bombButton[i + 1][j - 1].BombRoundCount)+"");
bombButton[i + 1][j - 1].setEnabled(false);
bombButton[i + 1][j - 1].isClicked=true;
}
}
if ( (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //檢測下邊空格是否是空
if (bombButton[i + 1][ j ].isBomb == false && bombButton[i + 1][ j ].isClicked == false && bombButton[i + 1][ j ].isRight == false) {
bombButton[i + 1][ j ].setText((bombButton[i + 1][ j ].BombRoundCount)+"");
bombButton[i + 1][ j ].setEnabled(false);
bombButton[i + 1][ j ].isClicked=true;
}
}
if ( (j + 1 <= ((int)Math.sqrt(BlockNum)-1) ) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) { //檢測右下邊空格是否是空
if (bombButton[i + 1][j + 1].isBomb == false && bombButton[i + 1][j + 1].isClicked == false && bombButton[i + 1][j + 1].isRight == false) {
bombButton[i + 1][j + 1].setText((bombButton[i + 1][j + 1].BombRoundCount)+"");
bombButton[i + 1][j + 1].setEnabled(false);
bombButton[i + 1][j + 1].isClicked=true;
}
}
if ( (i - 1 >= 0) && (j - 1 >= 0))//檢測左上
isNull(bombButton,bombButton[i - 1][j - 1]);
if ( (i - 1 >= 0))
isNull( bombButton,bombButton[i - 1][ j ]);//檢測上方
if ( (i - 1 >= 0) && (j + 1 <= (int)Math.sqrt(BlockNum)-1))
isNull( bombButton,bombButton[i - 1][j + 1]);//檢測右上
if ( (j - 1 >= 0))
isNull(bombButton,bombButton[i][j - 1]);//檢測左邊
if ( (i >= 0) && (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) )
isNull(bombButton,bombButton[i][j + 1]);//檢測右邊
if ( (j - 1 >= 0) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) )
isNull(bombButton,bombButton[i + 1][j - 1]); //檢測左下
if ( (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) //檢測下
isNull(bombButton,bombButton[i + 1][ j ]);
if ( (j + 1 <= ((int)Math.sqrt(BlockNum)-1)) && (i + 1 <= ((int)Math.sqrt(BlockNum)-1)) ) //檢測右下
isNull(bombButton,bombButton[i + 1][j + 1]);
}
}
public void actionPerformed(ActionEvent e)
{
CountRoundBomb();
if(((Bomb)e.getSource()).isBomb==false && ((Bomb)e.getSource()).isClicked == false)
{
((Bomb)e.getSource()).setText(( ((Bomb)e.getSource()).BombRoundCount )+"");
((Bomb)e.getSource()).isClicked=true;
((Bomb)e.getSource()).setIcon(null);
((Bomb)e.getSource()).setEnabled(false);
if((((Bomb)e.getSource()).BombRoundCount) == 0)
isNull(bombButton,(Bomb)e.getSource());
isWin();
}
else if(((Bomb)e.getSource()).isBomb == true)
{
for(int i=0;i<(int)Math.sqrt(BlockNum);i++)
for(int j=0;j<(int)Math.sqrt(BlockNum);j++)
{
if(bombButton[ i ][ j ].isBomb == true)
bombButton[ i ][ j ].setIcon(icon_bomb);
}
((Bomb)e.getSource()).setIcon(icon_bomb_big);
JOptionPane msg = new JOptionPane();
JOptionPane.showMessageDialog(this,"你踩到地雷了,按確定重來","你踩到地雷了",2);
replay();
}
}
public void mouseClicked(MouseEvent e)
{
Bomb bombSource = (Bomb)e.getSource();
boolean right = SwingUtilities.isRightMouseButton(e);
if((right == true) && (bombSource.isClicked == false))
{
bombSource.BombFlag = (bombSource.BombFlag + 1)%3;
if(bombSource.BombFlag == 1)
{
if(BombNum > 0 && bombSource.isRight == false ){
bombSource.setIcon(icon_flag);
bombSource.isRight = true;
BombNum--;
}
isWin();
nowBomb.setText("當前雷數"+" "+BombNum+"");
}
else if(bombSource.BombFlag == 2)
{
if( (BombNum !=0 ) ||(BombNum ==0 &&(bombSource.getIcon()==icon_flag)) )
BombNum++;
bombSource.setIcon(icon_question);
nowBomb.setText("當前雷數"+" "+BombNum+"");
}
else if(bombSource.BombFlag == 0)
{
bombSource.setIcon(null);
bombSource.isRight = false;
}
}
}
public void mouseEntered(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mousePressed(MouseEvent e)
{}
}
/*主類*/
public class Main
{
public static void main(String args[])
{
(new MainBomb()).show();
}
}
⑶ 運行在Eclipse環境下的java掃雷游戲的初級代碼是什麼
import java.awt.Button;x0dx0aimport java.util.Set;x0dx0a// 每一個小方塊類x0dx0apublic class Diamond extends Button {x0dx0aprivate Diamond[] diamonds;x0dx0ax0dx0a// 該小方塊周圍的八個方向上的小方塊x0dx0aprivate Diamond east;x0dx0aprivate Diamond north;x0dx0aprivate Diamond northEast;x0dx0aprivate Diamond northWest;x0dx0aprivate Diamond south;x0dx0aprivate Diamond southEast;x0dx0aprivate Diamond southWest;x0dx0aprivate Diamond west;x0dx0ax0dx0aprivate boolean isBomb;// 是否是雷x0dx0aprivate boolean isChange;// 又沒有被翻過x0dx0aprivate int no;// 產生的方塊的編號x0dx0ax0dx0a// 持有所有小方塊的引用,方便進行操作x0dx0apublic Diamond(Diamond[] diamonds) {x0dx0athis.diamonds = diamonds;x0dx0a}x0dx0ax0dx0a// 按鍵時方塊發生改變x0dx0apublic boolean change() {x0dx0athis.isChange = true;// 說明已經翻過了x0dx0aif(isBomb) {// 觸雷x0dx0a//this.setBackground(Color.red);x0dx0areturn true;x0dx0a} else {// 不是雷,就顯示周圍雷的數目x0dx0a//this.setLabel(this.getNearBombNo() + "");x0dx0athis.setLabel(this.getNearBombNo() + "");x0dx0a//if(this.getNearBombNo() == 0) {x0dx0a//this.moveon();x0dx0a//}x0dx0areturn false;x0dx0a}x0dx0a}x0dx0ax0dx0a// 獲得該小方塊周圍雷的數量x0dx0apublic int getNearBombNo() {x0dx0aint no = 0;x0dx0aif(this.northWest != null && this.northWest.isBomb) no++;x0dx0aif(this.north != null && this.north.isBomb) no++;x0dx0aif(this.northEast != null && this.northEast.isBomb) no++;x0dx0aif(this.east != null && this.east.isBomb) no++;x0dx0aif(this.southEast != null && this.southEast.isBomb) no++;x0dx0aif(this.south != null && this.south.isBomb) no++;x0dx0aif(this.southWest != null && this.southWest.isBomb) no++;x0dx0aif(this.west != null && this.west.isBomb) no++;x0dx0ax0dx0areturn no;x0dx0a}x0dx0ax0dx0a// 獲得該小方塊周圍的小方塊x0dx0apublic Diamond getNearDimaond(int i) {x0dx0aint index = -1;x0dx0aswitch (i) {x0dx0acase 1:// 1表示西北,2,表示北,以此類推x0dx0aindex = no - 10;x0dx0aif(index < 1 || no == 19 || no == 28 || no == 37 || no == 46 || no == 55 || no == 64 || no == 73) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0acase 2:x0dx0aindex = no - 9;x0dx0aif(index < 1) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0acase 3:x0dx0aindex = no - 8;x0dx0aif(index < 1 || no == 9 || no == 18 || no == 27 || no == 36 || no == 45 || no == 54 || no == 63 || no == 72) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0acase 4:x0dx0aindex = no + 1;x0dx0aif(no == 9 || no == 18 || no == 27 || no == 36 || no == 45 || no == 54 || no == 63 || no == 72 || no == 81) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0acase 5:x0dx0aindex = no + 10;x0dx0aif(index >= 81 ||no == 9 || no == 18 || no == 27 || no == 36 || no == 45 || no == 54 || no == 63 || no == 72 || no == 81) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0acase 6:x0dx0aindex = no + 9;x0dx0aif(index > 81) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0acase 7:x0dx0aindex = no + 8;x0dx0aif(index >= 81 || no==1 || no == 10 || no == 19 || no == 28 || no == 37 || no == 46 || no == 55 || no == 64 || no == 73) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0acase 8:x0dx0aindex = no - 1;x0dx0aif(no==1 || no==10 || no == 19 || no == 28 || no == 37 || no == 46 || no == 55 || no == 64 || no == 73) {x0dx0areturn null;x0dx0a} else {x0dx0areturn diamonds[index];x0dx0a}x0dx0a}x0dx0areturn null;x0dx0a}x0dx0ax0dx0a// 遞歸,set是用來裝已經翻過的小方塊的,不然會死循環,為什麼用set,因為set是不重復的x0dx0apublic void moveon(Set
⑷ 用java怎麼寫掃雷程序
首先要寫一個UI,也就是操作界面,使用java.swing.*內的東西就可以搞定;
其次寫一個hander,也就是具體的按鈕響應,UI的初始化(哪裡有雷),怎麼觸發雷和其他的;
一般來說簡單的掃雷模型就好了,如果需要更有意思點,可以寫一些資料庫的操作內容的tool類具體的就是處理歷史操作記錄,場均數據或多人競技的特點。
如果你是說你沒有設計思路,我可以給你個提示:遞歸演算法是觸發掃雷的方法,初始化用隨機數來做。
⑸ 高分求一個運行在Eclipse環境下的java 掃雷游戲的初級代碼 越小越好 越短越好 運行就好,就是初級就好了,
import java.awt.Button;
import java.util.Set;
// 每一個小方塊類
public class Diamond extends Button {
private Diamond[] diamonds;
// 該小方塊周圍的八個方向上的小方塊
private Diamond east;
private Diamond north;
private Diamond northEast;
private Diamond northWest;
private Diamond south;
private Diamond southEast;
private Diamond southWest;
private Diamond west;
private boolean isBomb;// 是否是雷
private boolean isChange;// 又沒有被翻過
private int no;// 產生的方塊的編號
// 持有所有小方塊的引用,方便進行操作
public Diamond(Diamond[] diamonds) {
this.diamonds = diamonds;
}
// 按鍵時方塊發生改變
public boolean change() {
this.isChange = true;// 說明已經翻過了
if(isBomb) {// 觸雷
//this.setBackground(Color.red);
return true;
} else {// 不是雷,就顯示周圍雷的數目
//this.setLabel(this.getNearBombNo() + "");
this.setLabel(this.getNearBombNo() + "");
//if(this.getNearBombNo() == 0) {
// this.moveon();
//}
return false;
}
}
// 獲得該小方塊周圍雷的數量
public int getNearBombNo() {
int no = 0;
if(this.northWest != null && this.northWest.isBomb) no++;
if(this.north != null && this.north.isBomb) no++;
if(this.northEast != null && this.northEast.isBomb) no++;
if(this.east != null && this.east.isBomb) no++;
if(this.southEast != null && this.southEast.isBomb) no++;
if(this.south != null && this.south.isBomb) no++;
if(this.southWest != null && this.southWest.isBomb) no++;
if(this.west != null && this.west.isBomb) no++;
return no;
}
// 獲得該小方塊周圍的小方塊
public Diamond getNearDimaond(int i) {
int index = -1;
switch (i) {
case 1:// 1表示西北,2,表示北,以此類推
index = no - 10;
if(index < 1 || no == 19 || no == 28 || no == 37 || no == 46 || no == 55 || no == 64 || no == 73) {
return null;
} else {
return diamonds[index];
}
case 2:
index = no - 9;
if(index < 1) {
return null;
} else {
return diamonds[index];
}
case 3:
index = no - 8;
if(index < 1 || no == 9 || no == 18 || no == 27 || no == 36 || no == 45 || no == 54 || no == 63 || no == 72) {
return null;
} else {
return diamonds[index];
}
case 4:
index = no + 1;
if(no == 9 || no == 18 || no == 27 || no == 36 || no == 45 || no == 54 || no == 63 || no == 72 || no == 81) {
return null;
} else {
return diamonds[index];
}
case 5:
index = no + 10;
if(index >= 81 ||no == 9 || no == 18 || no == 27 || no == 36 || no == 45 || no == 54 || no == 63 || no == 72 || no == 81) {
return null;
} else {
return diamonds[index];
}
case 6:
index = no + 9;
if(index > 81) {
return null;
} else {
return diamonds[index];
}
case 7:
index = no + 8;
if(index >= 81 || no==1 || no == 10 || no == 19 || no == 28 || no == 37 || no == 46 || no == 55 || no == 64 || no == 73) {
return null;
} else {
return diamonds[index];
}
case 8:
index = no - 1;
if(no==1 || no==10 || no == 19 || no == 28 || no == 37 || no == 46 || no == 55 || no == 64 || no == 73) {
return null;
} else {
return diamonds[index];
}
}
return null;
}
// 遞歸,set是用來裝已經翻過的小方塊的,不然會死循環,為什麼用set,因為set是不重復的
public void moveon(Set<Diamond> set) {
set.add(this);// 先把自己加上
if(this.getNorthWest() != null && this.getNorthWest().isBomb == false) {
this.getNorthWest().change();
if(this.getNorthWest().getNearBombNo() == 0) {
if(set.contains(this.getNorthWest()) == false)
this.getNorthWest().moveon(set);
}
set.add(this.getNorthWest());
}
if(this.getNorth() != null && this.getNorth().isBomb == false) {
this.getNorth().change();
if(this.getNorth().getNearBombNo() == 0) {
if(set.contains(this.getNorth()) == false)
this.getNorth().moveon(set);
}
set.add(this.getNorth());
}
if(this.getNorthEast() != null && this.getNorthEast().isBomb == false) {
this.getNorthEast().change();
if(this.getNorthEast().getNearBombNo() == 0) {
if(set.contains(this.getNorthEast()) == false)
this.getNorthEast().moveon(set);
}
set.add(this.getNorthEast());
}
if(this.getEast() != null && this.getEast().isBomb == false) {
this.getEast().change();
if(this.getEast().getNearBombNo() == 0) {
if(set.contains(this.getEast()) == false)
this.getEast().moveon(set);
}
set.add(this.getEast());
}
if(this.getSouthEast() != null && this.getSouthEast().isBomb == false) {
this.getSouthEast().change();
if(this.getSouthEast().getNearBombNo() == 0) {
if(set.contains(this.getSouthEast()) == false)
this.getSouthEast().moveon(set);
}
set.add(this.getSouthEast());
}
if(this.getSouth() != null && this.getSouth().isBomb == false) {
this.getSouth().change();
if(this.getSouth().getNearBombNo() == 0) {
if(set.contains(this.getSouth()) == false)
this.getSouth().moveon(set);
}
set.add(this.getSouth());
}
if(this.getSouthWest() != null && this.getSouthWest().isBomb == false) {
this.getSouthWest().change();
if(this.getSouthWest().getNearBombNo() == 0) {
if(set.contains(this.getSouthWest()) == false)
this.getSouthWest().moveon(set);
}
set.add(this.getSouthWest());
}
if(this.getWest() != null && this.getWest().isBomb == false) {
this.getWest().change();
if(this.getWest().getNearBombNo() == 0) {
if(set.contains(this.getWest()) == false)
this.getWest().moveon(set);
}
set.add(this.getWest());
}
}
/*public Diamond[] getDiamonds() {
return diamonds;
}*/
public Diamond getEast() {
return east;
}
public int getNo() {
return no;
}
public Diamond getNorth() {
return north;
}
public Diamond getNorthEast() {
return northEast;
}
public Diamond getNorthWest() {
return northWest;
}
public Diamond getSouth() {
return south;
}
public Diamond getSouthEast() {
return southEast;
}
public Diamond getSouthWest() {
return southWest;
}
public Diamond getWest() {
return west;
}
public boolean isBomb() {
return isBomb;
}
public boolean isChange() {
return isChange;
}
public void setBomb(boolean isBomb) {
this.isBomb = isBomb;
}
public void setChange(boolean isChange) {
this.isChange = isChange;
}
public void setDiamonds(Diamond[] diamonds) {
this.diamonds = diamonds;
}
public void setEast(Diamond east) {
this.east = east;
}
public void setNo(int no) {
this.no = no;
}
public void setNorth(Diamond north) {
this.north = north;
}
public void setNorthEast(Diamond northEast) {
this.northEast = northEast;
}
public void setNorthWest(Diamond northWest) {
this.northWest = northWest;
}
public void setSouth(Diamond south) {
this.south = south;
}
public void setSouthEast(Diamond southEast) {
this.southEast = southEast;
}
public void setSouthWest(Diamond southWest) {
this.southWest = southWest;
}
public void setWest(Diamond west) {
this.west = west;
}
}
⑹ 怎麼用Java做一個掃雷程序,要原創。。。 做好了給加100
第一個JAVA文件
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 顯示所有按鈕的面板
* @author Administrator
*
*/
public class AllButtonPanel extends JPanel implements ActionListener{
private int row;//行數
private int col;//列數
private int mineCount;//地雷數
private MineButton[][] allButtons;//所有按鈕
public AllButtonPanel(int row,int col,int mineCount){
this.row=row;
this.col=col;
this.mineCount=mineCount;
allButtons=new MineButton[row][col];
createButtons();
createMine();
init();
}
private void init(){
this.setLayout(new GridLayout(row,col));
for(int i=0;i<allButtons.length;i++){
for(int j=0;j<allButtons[i].length;j++){
this.add(allButtons[i][j]);
}
}
}
/**
* 隨機佈雷的方法
*
*/
private void createMine(){
int n=0;
while(n<mineCount){//隨機生成mineCount個地雷
int i=(int)(Math.random()*row);
int j=(int)(Math.random()*col);
if(allButtons[i][j].getCountOfSurroundMines()!=-1){
allButtons[i][j].setCountOfSurroundMines(-1);
n++;
}
}
for(int i=0;i<allButtons.length;i++){//計算每個位置的周圍地雷數
for(int j=0;j<allButtons[i].length;j++){
if(allButtons[i][j].getCountOfSurroundMines()!=-1){
allButtons[i][j].setCountOfSurroundMines(getSurroundMineCount(i,j));
}
}
}
}
/**
* 統計(i,j)坐標周圍8個位置的地雷數
* @param data
* @param i
* @param j
* @return
*/
private int getSurroundMineCount(int i,int j){
int num=0;//統計周圍的雷數
if(i-1>=0&&j-1>=0){
num+=(allButtons[i-1][j-1].getCountOfSurroundMines()==-1?1:0);
}
if(i-1>=0){
num+=(allButtons[i-1][j].getCountOfSurroundMines()==-1?1:0);
}
if(i-1>=0&&j+1<allButtons[0].length){
num+=(allButtons[i-1][j+1].getCountOfSurroundMines()==-1?1:0);
}
if(j-1>=0){
num+=(allButtons[i][j-1].getCountOfSurroundMines()==-1?1:0);
}
if(j+1<allButtons[0].length){
num+=(allButtons[i][j+1].getCountOfSurroundMines()==-1?1:0);
}
if(i+1<allButtons.length&&j-1>=0){
num+=(allButtons[i+1][j-1].getCountOfSurroundMines()==-1?1:0);
}
if(i+1<allButtons.length){
num+=(allButtons[i+1][j].getCountOfSurroundMines()==-1?1:0);
}
if(i+1<allButtons.length&&j+1<allButtons[0].length){
num+=(allButtons[i+1][j+1].getCountOfSurroundMines()==-1?1:0);
}
return num;
}
/**
* 生成按鈕
*
*/
private void createButtons(){
for(int i=0;i<allButtons.length;i++){
for(int j=0;j<allButtons[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;i<allButtons.length;i++){//把所有按鈕都顯示出來
for(int j=0;j<allButtons[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>=0&&j-1>=0){
showEmpty(i-1,j-1);
}
if(i-1>=0){
showEmpty(i-1,j);
}
if(i-1>=0&&j+1<allButtons[0].length){
showEmpty(i-1,j+1);
}
if(j-1>=0){
showEmpty(i,j-1);
}
if(j+1<allButtons[0].length){
showEmpty(i,j+1);
}
if(i+1<allButtons.length&&j-1>=0){
showEmpty(i+1,j-1);
}
if(i+1<allButtons.length){
showEmpty(i+1,j);
}
if(i+1<allButtons.length&&j+1<allButtons[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("剩餘地雷:");
text2=new JLabel("消耗時間:");
remainMine=new JLabel("10");
time=new JLabel("0");
reset=new JButton("重新開始");
reset.addActionListener(this);
JMenuBar bar=new JMenuBar();
JMenu game=new JMenu("游戲");
JMenu help=new JMenu("幫助");
JMenuItem item;
game.add(item=new JMenuItem("開局"));item.addActionListener(this);
game.addSeparator();
ButtonGroup bg=new ButtonGroup();
game.add(item=new JCheckBoxMenuItem("初級",true));bg.add(item);item.addActionListener(this);
game.add(item=new JCheckBoxMenuItem("中級"));bg.add(item);item.addActionListener(this);
game.add(item=new JCheckBoxMenuItem("高級"));bg.add(item);item.addActionListener(this);
game.add(item=new JCheckBoxMenuItem("自定義..."));bg.add(item);item.addActionListener(this);
game.addSeparator();
game.add(item=new JMenuItem("退出"));item.addActionListener(this);
help.add(item=new JMenuItem("查看幫助"));item.addActionListener(this);
help.add(item=new JMenuItem("關於掃雷..."));item.addActionListener(this);
bar.add(game);
bar.add(help);
this.setJMenuBar(bar);
init();
}
private void init(){
JPanel north=new JPanel();
north.add(text1);
north.add(remainMine);
north.add(reset);
north.add(text2);
north.add(time);
this.add(north,BorderLayout.NORTH);
this.row=9;
this.col=9;
this.mine=10;
restart();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Thread(){
public void run(){
while(Integer.parseInt(remainMine.getText())>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
time.setText((Integer.parseInt(time.getText())+1)+"");
}
}
}.start();
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("初級")){
this.row=9;
this.col=9;
this.mine=10;
restart();
return;
}
if(e.getActionCommand().equals("中級")){
this.row=16;
this.col=16;
this.mine=40;
restart();
return;
}
if(e.getActionCommand().equals("高級")){
this.row=16;
this.col=30;
this.mine=99;
restart();
return;
}
if(e.getActionCommand().equals("重新開始")){
restart();
return;
}
}
private void restart(){
if(center!=null){
this.remove(center);
}
center=new AllButtonPanel(row,col,mine);
this.add(center,BorderLayout.CENTER);
this.remainMine.setText(mine+"");
this.time.setText("0");
this.setSize(col*30,row*30+10);
this.setResizable(false);
this.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
new CleanMine();
}
}
第三個JAVA文件.
import javax.swing.JButton;
import java.awt.*;
public class MineButton extends JButton {
private int row;
private int col;
private boolean cleared=false;
private int countOfSurroundMines;//周圍地雷數,如果本按鈕是雷,則為-1;
public MineButton(int row,int col){
this.row=row;
this.col=col;
this.setMargin(new Insets(0,0,0,0));
}
public int getCol() {
return col;
}
public int getRow() {
return row;
}
public boolean isCleared() {
return cleared;
}
public void setCleared(boolean cleared) {
this.cleared = cleared;
}
public int getCountOfSurroundMines() {
return countOfSurroundMines;
}
public void setCountOfSurroundMines(int countOfSurroundMines) {
this.countOfSurroundMines = countOfSurroundMines;
}
}
全部編譯以後就可以執行了
⑺ java編寫掃雷程序的流程圖,哪位大俠幫下,小弟急用~~~
我有源代碼:絕對可以通過,不過比較簡單而已,對學生而言應該可以了吧,這是以前寫的:
一下兩個文件放在一個包里就行了
/*
This class defines a class that contains some useful
attributions and some methods to set or get these attributions
*/
import javax.swing.JButton;
public class ExButton extends JButton
{
//if the button is a mine,the isMine will be true
private boolean isMine;
//to check if a button has been visited is useful
//when using the recursion in the Game class
private boolean isVisited;
//the row number of the button
int btnRowNumber;
//the column number of the button
int btnColumnNumber;
//the mines around a button
int minesAround=0;
public void setIndex(int btnRowNumber,int btnColumnNumber)
{
this.btnRowNumber=btnRowNumber;
this.btnColumnNumber=btnColumnNumber;
}
public int getRowNumber()
{
return this.btnRowNumber;
}
public int getColumnNumber()
{
return this.btnColumnNumber;
}
public void setVisited(boolean isVisited)
{
this.isVisited=isVisited;
}
public boolean getVisited()
{
return this.isVisited;
}
public void setMine(boolean isMine)
{
this.isMine=isMine;
}
public boolean getMine()
{
return this.isMine;
}
//the attribute of minesAround add one each
//time a mine is put down around the button
public void addMinesAround()
{
this.minesAround++;
}
public int getMinesAround()
{
return this.minesAround;
}
}
-------------------------------------------------
/*
File Name: Game.java
Author: Tian Wei Student Number: Email: [email protected]
Assignment number: #4
Description: In this program ,a frame will be created which contains
ten "mines".When you click a button ,it will present the
number of mines around or a message of losing the game
(if the button is a mine).You can make a right click to
sign a dengerous button as well.When all the mines have
been signed ,a message box of winning the game will jump
to the screen.And the the message of the time you used in
the game.More over,you can click the button on the bottom
to restart the game.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.util.Timer;
public class Game extends JFrame{
//define some menber variables
private long minute=0,second=0;//take down time used int the game
private ExButton[][] btn;//two-dimension array present the buttons
private JLabel label;
private JButton restart;//restart button
private int minesRemained;//remained mines that you have not signed
private boolean thisTry=true;
private JLabel timeUsed=new JLabel ();
private Random rand=new Random();
private final int ROWS,COLUMNS;
private final int MINES;
// the constuctor
public Game(int rows,int columns,int mines)
{
super("Find mines");
this.ROWS=rows;
this.COLUMNS=columns;
this.MINES=mines;
minesRemained=MINES;
Timer timer=new Timer();//Timer's object to timer the game
timer.schele(new MyTimer(), 0, 1000);//do the function every second
Container container=getContentPane();
container.setLayout(new BorderLayout());
//Jpanel in the Container
JPanel jpanel=new JPanel();
jpanel.setLayout(new GridLayout(ROWS,COLUMNS));
restart=new JButton("click me to restart the game");
JPanel jpanel2=new JPanel();
//Another JPanel in the Container
jpanel2.setLayout(new FlowLayout());
jpanel2.add(timeUsed);
jpanel2.add(restart);
ButtonListener restartHandler=new ButtonListener();
restart.addActionListener(restartHandler);
container.add(jpanel2,BorderLayout.SOUTH);
btn=new ExButton[ROWS+2][COLUMNS+2];
//initialize the buttons
for(int i=0;i<=ROWS+1;i++)
{
for(int j=0;j<=COLUMNS+1;j++)
{
btn[i][j]=new ExButton();
btn[i][j].addMouseListener(new MouseClickHandler());
btn[i][j].setIndex(i,j);
btn[i][j].setVisited(false);
}
}
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
jpanel.add(btn[i][j]);
container.add(jpanel,BorderLayout.CENTER);
JPanel jpanel3=new JPanel ();
label=new JLabel();
label.setText("Mines remaining "+MINES);
jpanel3.add(label);
container.add(jpanel3,BorderLayout.NORTH );
this.addMines();
this.addMinesAround();
}
//randomly put ten mines
private void addMines()
{
for(int i=1;i<=MINES;i++)
{
int raInt1=rand.nextInt(ROWS);
int raInt2=rand.nextInt(COLUMNS);
if((raInt1==0)||(raInt2==0)||btn[raInt1][raInt2].getMine())
i--;
else
btn[raInt1][raInt2].setMine(true);
}
}
//take down the mines around a button
private void addMinesAround()
{
for(int i=1;i<=ROWS;i++)
{
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine())
{
btn[i][j-1].addMinesAround();
btn[i][j+1].addMinesAround();
btn[i-1][j-1].addMinesAround();
btn[i-1][j].addMinesAround();
btn[i-1][j+1].addMinesAround();
btn[i+1][j-1].addMinesAround();
btn[i+1][j].addMinesAround();
btn[i+1][j+1].addMinesAround();
}
}
}
}
//if a button clicked is a empty one,then use a recursion
//to find all the empty buttons around
private void checkEmpty(ExButton button)
{
button.setVisited(true);
int x=button.getRowNumber();
int y=button.getColumnNumber();
button.setBackground(Color.white);
if((button.getMinesAround()==0)&&(x>=1)&&(x<=ROWS)
&&(y>=1)&&(y<=COLUMNS))
{
if(!btn[x][y-1].getVisited())
checkEmpty(btn[x][y-1]);
if(!btn[x][y+1].getVisited())
checkEmpty(btn[x][y+1]);
if(!btn[x-1][y].getVisited())
checkEmpty(btn[x-1][y]);
if(!btn[x+1][y].getVisited())
checkEmpty(btn[x+1][y]);
if(!btn[x-1][y-1].getVisited())
checkEmpty(btn[x-1][y-1]);
if(!btn[x-1][y+1].getVisited())
checkEmpty(btn[x-1][y+1]);
if(!btn[x+1][y-1].getVisited())
checkEmpty(btn[x+1][y-1]);
if(!btn[x+1][y+1].getVisited())
checkEmpty(btn[x+1][y+1]);
}
else if(button.getMinesAround()>0)
button.setText(""+button.getMinesAround());
}
//the main function
public static void main(String args[])
{
String rows,columns,mines;
int rowNumber,columnNumber,mineNumber;
rows=JOptionPane.showInputDialog("Enter the rows of the game");
columns=JOptionPane.showInputDialog("Enter the columns of the game");
mines=JOptionPane.showInputDialog("Enter the mines of the game");
rowNumber=Integer.parseInt(rows);
columnNumber=Integer.parseInt(columns);
mineNumber=Integer.parseInt(mines);
Game frame=new Game(rowNumber,columnNumber,mineNumber);
frame.setTitle("Find Mines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(220, 80);
frame.setSize(600, 600 );
frame.setVisible(true);
}
//there are three inner class below
//The first inner class is used to do the mouse listener's
//function.When you click a button ,it will present the
//number of mines around or a message of losing the game
//(if the button is a mine).You can make a right click to
//sign a dengerous button as well.When ten mines have been
//signed,it will check whether all the signed ones are mines
private class MouseClickHandler extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
{
//get the button that been clicked
ExButton eventButton=new ExButton();
eventButton=(ExButton)event.getSource();
eventButton.setVisited(true);
//when it is a right click
if(event.isMetaDown())
{
if(eventButton.getText()=="#")
{
minesRemained++;
eventButton.setText("");
}
else
{
if((eventButton.getBackground()==Color.white)||
(eventButton.getText()!=""))
{
//do nothing
}
else
{
minesRemained--;
eventButton.setText("#");
}
}
label.setText("Mines remaining "+minesRemained);
//check if all the signed buttons are mines
if(minesRemained==0)
{
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine()&&btn[i][j].getText()!="#")
thisTry=false;
if(!btn[i][j].getMine()&&btn[i][j].getText()=="#")
thisTry=false;
}
if(thisTry)
{
//win the game
JOptionPane.showMessageDialog(null, "You succeed" +
" in this experience!");
JOptionPane.showMessageDialog(null, "Time used:"+
timeUsed.getText());
}
else//you have wrongly signed one or more mines
JOptionPane.showMessageDialog(null, "You have wrongly " +
"signed one or more mines,please check it and go on!");
}
}
else if(event.isAltDown())
{
//do nothing
}
else
{//normally click(left click)
if(eventButton.getText()=="#")
{
//do nothing
}
else if(eventButton.getMine())
{
//lose the game
JOptionPane.showMessageDialog(null, "What a pity!" +
"You failed!" );
//show all the mines to the loser
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine())
btn[i][j].setBackground(Color.BLACK);
}
JOptionPane.showMessageDialog(null, "Time used: 0"+
minute+":"+second);
}
else
{
if(eventButton.getMinesAround()==0)
{
//call the function to find all the empty buttons around
checkEmpty(eventButton);
}
else
eventButton.setText(""+eventButton.getMinesAround());
}
}
}
}
//The second class is to listen to the button which used to
//restart the game.In this class,it will dispose the old frame
//and create a new one(Of course,the mines's position have
//been changed).
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//what to dispose is the object of Game class
Game.this.dispose();
//the same code as in the main function
Game frame=new Game(ROWS,COLUMNS,MINES);
frame.setTitle("Find Mines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600 );
//make sure the frame is at the center of the screen
frame.setLocation(220, 80);
frame.setVisible(true);
}
}
//The last class is the class that will be used in the
//Timer's object timer.It should inherit the class TimerTask
//It is the task that the Timer will do every second
private class MyTimer extends TimerTask
{
public void run()
{
second+=1;
minute+=second/60;
second=second%60;
//change the text of the time used in the game
timeUsed.setText("Time used 0"+minute+":"+second);
}
}
}//end of the class Game
⑻ 求助Java掃雷源碼注釋
import java.awt.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import javax.swing.border.*;
/**
* <p>Title:掃雷</p>
*
* <p>Description:學JAVA以來做的第一個游戲,程序中可能還有些BUG,希望大家提出來供一起探討,
* 如果要測試記錄文件,可以把雷的數量改的少一點,
* arithmetic中的while(landmintTally<99), button_mouseClicked中的
* if((landmineNum-1)==0),有3處,表示還剩的雷數.completeGame中的
* for (int i=0; i<99; i++)</p>
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: private </p>
*
* @author cqp
* @version demo
*/
public class shaolei extends JFrame {
/**類的屬性和控制項實例化*/
ImageIcon ButtonIcon; //按鈕的圖片;
HashMap map = new HashMap(); //雷和數字的狀態,鍵為位置(0-479),值為狀態,0-6為數字,7為雷;
HashMap flag_landmine = new HashMap(); //按鈕上打的標記,如問號,對勾和取消,8為標記雷,9為問號,10為默認值空;
JMenuBar file = new JMenuBar(); //菜單欄;
JMenu game = new JMenu(); //菜單按鈕;
JMenuItem start = new JMenuItem(); //菜單項;
JMenuItem record = new JMenuItem(); //菜單項;
JMenuItem quit = new JMenuItem(); //菜單項;
JMenuItem clearReocrd = new JMenuItem();//菜單項;
JMenu help = new JMenu(); //菜單按鈕;
JButton[] cardsBtn = new JButton[480]; //480個按鈕;
JButton beginBtn = new JButton(); //開始按鈕;
JPanel pane = new JPanel(); //雷區面板;
JPanel paneTime = new JPanel(); //記數器所在的面板;
JOptionPane saveRecord = new JOptionPane(); //保存記錄對話框;
JTextField landmineTally = new JTextField("99");//所剩雷的計數器;
JTextField timeTally = new JTextField("0"); //時間計數器;
GridLayout gridLayout1 = new GridLayout(); //網格布局;
Timer timer; //線程設施;
String[] landmine = new String[99]; //存放雷的位置,用來判斷雷的位置是否重復;
slFrame_button_actionAdatper[] buttonClick =new slFrame_button_actionAdatper[480];//雷區按鈕的事件類;
int mouseKey=0; //得到滑鼠先按下的哪個鍵,用來判斷滑鼠是否同時按下了左右鍵;
int timeCount = 0; //時間計數器;
/**構造方法*/
public shaolei() {
try {
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**界面設置*/
private void jbInit() throws Exception {
getContentPane().setLayout(null);
this.setJMenuBar(file);
game.setText("游戲");
start.setText("開局");
start.addActionListener(new slFrame_start_actionAdapter(this));
record.setText("排行榜");
record.addActionListener(new slFrame_record_actionAdapter(this));
quit.setText("退出");
quit.addActionListener(new slFrame_quit_actionAdapter(this));
help.setText("幫助");
clearReocrd.setText("清除記錄");
clearReocrd.addActionListener(new slFrame_clearReocrd_actionAdapter(this));
landmineTally.setBounds(new Rectangle(5, 5, 40, 25));
landmineTally.setBackground(new Color(0,0,0));
landmineTally.setForeground(new Color(255,0,0));
landmineTally.setFont(new java.awt.Font("Times New Roman", Font.BOLD, 20));
landmineTally.setBorder(BorderFactory.createBevelBorder(1));
landmineTally.setEditable(false);
timeTally.setBounds(new Rectangle(520, 5, 50, 25));
timeTally.setBackground(new Color(0,0,0));
timeTally.setForeground(new Color(255,0,0));
timeTally.setHorizontalAlignment(4);
timeTally.setFont(new java.awt.Font("Times New Roman", Font.BOLD, 20));
timeTally.setBorder(BorderFactory.createBevelBorder(0));
timeTally.setEditable(false);
beginBtn.setBounds(new Rectangle(250, 5, 25, 25));
beginBtn.setBorder(BorderFactory.createBevelBorder(0));
beginBtn.addActionListener(new slFrame_beginBtn_actionAdatper(this));
beginBtn.setIcon(createImageIcon("images/laugh.jpg"));
paneTime.setBounds(new Rectangle(0, 0, 585, 35));
paneTime.setBorder(BorderFactory.createEtchedBorder());
paneTime.setLayout(null);
paneTime.add(landmineTally);
paneTime.add(timeTally);
paneTime.add(beginBtn);
pane.setBounds(new Rectangle(0, 35, 590, 320));
pane.setLayout(gridLayout1);
gridLayout1.setColumns(30);
gridLayout1.setRows(16);
file.add(game);
file.add(help);
game.add(start);
game.add(record);
game.add(quit);
help.add(clearReocrd);
this.getContentPane().add(pane);
this.getContentPane().add(paneTime);
ActionListener listener = new ActionListener(){ //自定義線程
public void actionPerformed(ActionEvent e){
timeCount++;
timeTally.setText(Integer.toString(timeCount));
}
};
timer = new Timer(1000, listener); //增加線程,並每1秒執行一次;
for (int i=0;i<480;i++) //實例化480個小按鈕加到面板pane中
{
cardsBtn[i] = new JButton();
cardsBtn[i].setText(""); //按鈕上的文字去掉;
cardsBtn[i].setBorder(null); //按鈕的邊框去掉;
pane.add(cardsBtn[i]);
}
}
/**主方法*/
public static void main(String[] args) {
shaolei frame = new shaolei();
frame.setSize(580,410);
frame.setTitle("掃雷");
frame.show();
frame.setResizable(false); //不能修改窗體大小
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //點關閉按鈕時直
}
/**自定義方法,用來給按鈕增加圖片*/
protected static ImageIcon createImageIcon(String path){
java.net.URL imgURL = shaolei.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**菜單按鈕的事件,開始游戲*/
public void start_actionPerformed(ActionEvent e) {
start(); //初始化;
arithmetic(); //計算雷的位置;
calculate(); //計算雷的分布情況;
timer.start(); //時間線程開始;
}
/**開始游戲按鈕的事件*/
public void beginBtn_mouseClicked(ActionEvent e){
start_actionPerformed(e); //直接調用菜單的事件;
}
/**自定義方法,游戲從這里開始,方法里對按鈕的屬性和狀態進行初始化;*/
void start(){
timeCount=0; //時間從0開始;
landmineTally.setText("99");//所剩雷數為99;
for (int i = 0; i<480; i++){
cardsBtn[i].setIcon(null); //清除按鈕上的圖片;
map.put( Integer.toString(i),Integer.toString(10)); //分布狀態全為10,表示為空;
flag_landmine.put( Integer.toString(i),Integer.toString(10)); //標記狀態全為10;
cardsBtn[i].removeMouseListener(buttonClick[i]); //去除雷區所有按鈕的滑鼠事件;
}
}
/**自定義方法,用來計算雷的分布位置*/
void arithmetic(){
Calendar time = Calendar.getInstance(); //日歷類,得到當前時間;
int leed = time.get(Calendar.SECOND); //得到當前時間的秒;
Random rand = new Random(leed); //把秒數當個隨機數的種子;
int tempRand; //臨時隨機數;
int landmintTally=0; //得到多少雷的計數器;
boolean flag=false; //標記是否重復;
int tempNum;
while(landmintTally < 99){ //最多隻能有99顆雷;
tempRand = (int)(rand.nextFloat()*480); //得隨機數;
tempNum = Integer.parseInt(map.get(Integer.toString(tempRand)).toString());
if (tempNum == 7) continue; //如果重復執行一個數字;
landmine[landmintTally] = Integer.toString(tempRand); //把得到的位置放進字元串;
map.put(Integer.toString(tempRand),Integer.toString(7)); //把得到的位置放到map集合里,值為7,表示有雷;
landmintTally++; //計數器加1;
}
}
/**計算雷的分部情況,指一個按鈕周圍有多少雷;*/
void calculate()
{
int num; //按鈕的狀態;
int sum=0; //計數器,計算周圍有幾顆雷;
int leftUp, up, rightUp, left, right, leftDown, down, rightDown; //定義了8個位置
for (int i = 0; i<480; i++)
{
leftUp = i-31;
up = i-30;
rightUp = i-29;
left = i-1;
right = i+1;
leftDown = i+29;
down = i+30;
rightDown= i+31;
cardsBtn[i].setBorder(BorderFactory.createBevelBorder(0)); //設置按鈕的邊框樣式;
buttonClick[i] = new slFrame_button_actionAdatper(this,i); //實例化事件類;
cardsBtn[i].addMouseListener(buttonClick[i]); //給當前按鈕添加滑鼠事件;
num = Integer.parseInt(map.get(Integer.toString(i)).toString());//得到當前按鈕的狀態;
if (num == 7){
continue; //如果這個按鈕的狀態為雷,跳到下個按鈕;
}
if (i == 0) { //左上角第一顆雷;
num = Integer.parseInt(map.get(Integer.toString(i)).toString());
if ( Integer.parseInt(map.get(Integer.toString(right)).toString()) == 7 ) sum++; //如果是雷計數器加1;
if ( Integer.parseInt(map.get(Integer.toString(down)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightDown)).toString()) == 7 ) sum++;
map.put(Integer.toString(0),Integer.toString(sum)); //把得到的數字放到當前的位置;
sum=0; //計數器清零;
continue; //下個按鈕;
}else if (i == 29) { //右上角第一顆雷;
if ( Integer.parseInt(map.get(Integer.toString(left)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(leftDown)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(down)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
continue;
}else if (i == 450) { //左下角第一顆雷;
if ( Integer.parseInt(map.get(Integer.toString(right)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(up)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightUp)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
continue;
}else if (i == 479) { //右下角第一顆雷;
if ( Integer.parseInt(map.get(Integer.toString(left)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(leftUp)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(up)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
return;
}else if (i<29){ //第一行;
if ( Integer.parseInt(map.get(Integer.toString(left)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(leftDown)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(down)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(right)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightDown)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
continue;
}else if (i>450){ //最後一行;
if ( Integer.parseInt(map.get(Integer.toString(leftUp)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(up)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightUp)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(left)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(right)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
continue;
}else if ( (i%30) == 0 ){ //第一列;
if ( Integer.parseInt(map.get(Integer.toString(up)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightUp)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(right)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(down)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightDown)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
continue;
}else if ( ((i+1)%30) == 0 ){ //最後一列;
if ( Integer.parseInt(map.get(Integer.toString(leftUp)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(up)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(left)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(leftDown)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(down)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
continue;
}else{ //除去四周剩下的;
if ( Integer.parseInt(map.get(Integer.toString(leftUp)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(up)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightUp)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(left)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(right)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(leftDown)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(down)).toString()) == 7 ) sum++;
if ( Integer.parseInt(map.get(Integer.toString(rightDown)).toString()) == 7 ) sum++;
map.put(Integer.toString(i),Integer.toString(sum));
sum=0;
continue;
}
}
}
/**滑鼠點擊事件,參數i為點擊按鈕的位置 */
public void button_mouseClicked(MouseEvent e,int i){
int mKey = e.getButton(); //點擊的哪個鍵;
int landmineNum = Integer.parseInt(landmineTally.getText().toString()); //所剩的雷數;
int num = Integer.parseInt(map.get(Integer.toString(i)).toString()); //當前按鈕的狀態;
int flag = Integer.parseInt(flag_landmine.get(Integer.toString(i)).toString());//當前按鈕的標記狀態;
if ( (mKey == 3) && ( cardsBtn[i].getBorder()!= null)){ //點擊為滑鼠右鍵,並且邊框不為空(空的表示已按亮開的);
if (flag == 10){ //如果沒有標記,則改為標記狀態;
flag_landmine.put(Integer.toString(i),Integer.toString(8));
ButtonIcon = createImageIcon("images/8.jpg");
cardsBtn[i].setIcon(ButtonIcon);
landmineTally.setText( Integer.toString(landmineNum - 1) );
if ( (landmineNum-1) == 0) //如果標記的雷數為99;
completeGame(); //完成游戲;
}else if (flag == 8){ //如果為標記狀態,則改為問號;
flag_landmine.put(Integer.toString(i),Integer.toString(9));
ButtonIcon = createImageIcon("images/9.jpg");
cardsBtn[i].setIcon(ButtonIcon);
landmineTally.setText( Integer.toString(landmineNum + 1) );
if ( (landmineNum+1) == 0) //如果標記的雷數為99;
completeGame(); //完成游戲;
}else if (flag == 9){ //如果為問號,則取消標記;
flag_landmine.put(Integer.toString(i),Integer.toString(10));
cardsBtn[i].setIcon(null);
}
}else if (mKey == 1){ //如果點擊為滑鼠左鍵;
flag_landmine.put(Integer.toString(i),Integer.toString(10)); //先清除所點擊按鈕的標記狀態;
if ( (landmineNum+1) == 0) //如果標記的雷數為99;
completeGame(); //完成游戲;
if (num == 7){ //如果銨鈕的狀態為雷,則結束游戲;
overGame(i);
}else if (num == 0){ //如果雷數為空
if ( flag == 8 ){ //如果已經標記為雷,計數器加1;
landmineTally.setText( Integer.toString(landmineNum + 1) );
}
ButtonIcon = createImageIcon("images/0.jpg");
cardsBtn[i].setIcon(ButtonIcon);
cardsBtn[i].setBorder(null);
display(i); //亮開周圍的按鈕;
}else { //數字為1-6之間,亮開按鈕,並顯示數字所對應的圖片;
if ( flag == 8 ){ //如果已經標記為雷,計數器加1;
landmineTally.setText( Integer.toString(landmineNum + 1) );
}
ButtonIcon = createImageIcon("images/"+num+".jpg");
cardsBtn[i].setIcon(ButtonIcon);
cardsBtn[i].setBorder(null);
}
}
if ( (mouseKey==1 && mKey == 3) || (mouseKey==3 && mKey == 1) ){ //滑鼠左右鍵同時點按下;
open(i); //亮開周圍的按鈕(先判斷);
}
mouseKey = 0;
}
/**自定義方法,用來判斷是否要亮開周圍的按鈕*/
void open(int i){
int landmineAmount = 0; //實際的雷數;
int flagAmount=0; //標記的雷數;
int landmine_leftUp=0, landmine_up=0, landmine_rightUp=0, landmine_left=0, landmine_right=0,
landmine_leftDown=0, landmine_down=0, landmine_rightDown=0; //定義了實際雷的8個位置
int flag_leftUp=0, flag_up=0, flag_rightUp=0, flag_left=0, flag_right=0,
flag_leftDown=0, flag_down=0, flag_rightDown=0; //定義了標記雷的8個位置
//實際雷所在的8個位置和標記雷的8個位置,如果不加判斷則hashMap集合會越界;
if (i > 31) landmine_leftUp = Integer.parseInt(map.get(Integer.toString(i-31)).toString());
if (i > 30) landmine_up = Integer.parseInt(map.get(Integer.toString(i-30)).toString());
if (i > 29) landmine_rightUp = Integer.parseInt(map.get(Integer.toString(i-29)).toString());
if (i > 1) landmine_left = Integer.parseInt(map.get(Integer.toString(i-1)).toString());
if (i < 479) landmine_right = Integer.parseInt(map.get(Integer.toString(i+1)).toString());
if (i < 450) landmine_leftDown = Integer.parseInt(map.get(Integer.toString(i+29)).toString());
if (i < 449) landmine_down = Integer.parseInt(map.get(Integer.toString(i+30)).toString());
if (i < 448) landmine_rightDown = Integer.parseInt(map.get(Integer.toString(i+31)).toString());
if (i > 31) flag_leftUp = Integer.parseInt(flag_landmine.get(Integer.toString(i-31)).toString());
if (i > 30) flag_up = Integer.parseInt(flag_landmine.get(Integer.toString(i-30)).toString());
if (i > 29) flag_rightUp = Integer.parseInt(flag_landmine.get(Integer.toString(i-29)).toString());
if (i > 1) flag_left = Integer.parseInt(flag_landmine.get(Integer.toString(i-1)).toString());
if (i < 479) flag_right = Integer.parseInt(flag_landmine.get
太長了寫不完,我把壓縮包發給你吧,49905518注意查收
⑼ JAVA,編一個游戲小游戲,比如掃雷,這個程序大概的代碼是什麼,誰能教教我我比較笨,但是我認學。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main
{
public static void main(String[] argus)
{
Landmine Zhang = new Landmine();
}
}
//
// Landmine類 主界面
class Landmine extends JFrame
{
static Resources resources = new Resources();
Playing listener = new Playing(this); //主要監聽者,監聽地雷面板的動作
Help helpListener = new Help(this); //輔助監聽者,監聽「幫助」、「關於」
JPanel landminePanel = new JPanel(); //創建地雷面板
JPanel topPanel = new JPanel(); //創建頂部面板
JPanel lowerPanel = new JPanel(); //創建底部面板
public static MyButton [][] lei; //主區按鈕組
public static int numberOfUnflaged ; //剩餘的雷數,顯示在topPanel上,用於提示用戶
public static int numberOfClicked; //已經翻開的格子數,當數字數字到"總格子數—雷數"時,即勝利
public static int usedTime; //已用時間
public static JLabel numberOfUnflagedLabel = new JLabel(); //創建剩雷數標簽
public static JLabel timeLabel = new JLabel();//創建時間標簽
public static Timer timer; //創建計時
Keylistener keyListener = new Keylistener(this);
public Landmine()
{
super("掃雷__1.2版__小老頭"); //標題
setBounds(300,90,800,800); //設置窗口位置和大小
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//最大化、最小化、關閉按鈕
BorderLayout ff = new BorderLayout(); //創建布局管理器
setLayout(ff); //關聯布局管理器
setResizable(false); //禁止改變窗口大小
/*初始化一些數據*/
numberOfClicked = 0;
numberOfUnflaged = 40;
usedTime = 0;
/*設置頂部面板*/
numberOfUnflagedLabel.setText("剩餘雷數:"+numberOfUnflaged);//顯示剩餘雷數
numberOfUnflagedLabel.setFont(resources.fontOne);//設置剩雷數標簽字體
numberOfUnflagedLabel.setIcon(resources.bombIconForLabel);//剩雷數標簽圖標(地雷形)
topPanel.add(numberOfUnflagedLabel); //剩雷數標簽加入topPanel
timeLabel.setText("用時:" + usedTime); //顯示剩餘時間
timeLabel.setFont(resources.fontOne); //設置時間標簽字體
timeLabel.setIcon(resources.clockIcon); //設置時間標簽圖標
topPanel.add(timeLabel); //時間標簽加入topPanel
add(topPanel,BorderLayout.NORTH); //加入主面板上部
timer = new Timer(1000,new TimerListener());//計算器注冊監聽者
/*設置底部面板*/
JButton aboutJB = new JButton("關於"); //創建「關於」按鈕
JButton helpJB = new JButton("求救"); //創建「求救」按鈕
helpJB.addActionListener(helpListener); //"求救"按鈕加入監聽者
aboutJB.addActionListener(helpListener);//"關於"按鈕加入監聽者
helpJB.addKeyListener(keyListener);
aboutJB.addKeyListener(keyListener); //注冊按鍵監聽
lowerPanel.add(aboutJB); //「關於」按鈕加入lowerPanel
lowerPanel.add(helpJB); //「幫助」按鈕加入lowerPanel
add(lowerPanel,BorderLayout.SOUTH);
/*設置地雷面板*/
GridLayout dd = new GridLayout(16,16);
landminePanel.setLayout(dd); //布局管理
lei = new MyButton[18][18];
for(int i=0; i<18; ++i)
{//創建下標0—17的按鈕,18*18矩陣
for(int j=0; j<18; ++j)
{
lei[i][j] = new MyButton(i,j);
}
}
for(int i=1; i<17; ++i)
{//將下標1-16的按鈕,加入面板、設置圖標、翻開標記為假、加入監聽者
for(int j=1; j<17; ++j)
{
landminePanel.add(lei[i][j]); //按鈕加入地雷面板
lei[i][j].setIcon(resources.smallIcon); //設置按鈕圖標
lei[i][j].isClicked = false; //翻開標記設置為 假lei[i][j].setIcon(dead);
lei[i][j].addActionListener(listener); //加入監聽者
lei[i][j].addMouseListener(listener); //加入滑鼠事件監聽者
lei[i][j].addKeyListener(keyListener); //按鈕注冊按鍵監聽,當焦點在按鈕上是能監聽按鍵
}
}
add(landminePanel,BorderLayout.CENTER); //landminePanel加入主框架中央
addLandmine(); //布雷
timer.start(); //啟動計時器
setVisible(true);//顯示之
}
/*布雷*/
public static void addLandmine()
{//隨機將40的按鈕的是否為雷的標記isBomb設為真
for(int count = 0; count<40; /*blank*/)
{
int i = (int)(Math.random()*100 % 16 +1 ) ;
int j = (int)(Math.random()*100 % 16 +1 ) ;
if(lei[i][j].isBomb == false)
{
lei[i][j].isBomb = true;
count++;
}
}
}
class TimerListener implements ActionListener
{//內部類,時間監聽
public void actionPerformed(ActionEvent e)
{
usedTime++;
timeLabel.setText("用時:" + usedTime);
}
}
}
//
// Playing類 執行主要游戲操作
class Playing implements ActionListener,MouseListener
{
static Resources resources = new Resources();
public static Landmine gui;
public Playing(Landmine in )
{
gui = in;
}
public void actionPerformed(ActionEvent event)
{
MyButton receive = (MyButton)event.getSource();
if(receive.isBomb)
{//如果翻到了雷。。
for(int i=1; i<17; ++i)
{//將所有的雷圖標設為 「地雷」
for(int j=1; j<17; ++j)
{
if(gui.lei[i][j].isBomb)
gui.lei[i][j].setIcon(resources.bombIcon);
}
}
receive.setIcon(resources.deadIcon);//將踩到的地雷圖標設為 「衰」
gui.timer.stop(); //停止計時器
JOptionPane.showMessageDialog(null,"小朋友,你掛了…","失敗!",
JOptionPane.INFORMATION_MESSAGE,
resources.deadIcon);//提示失敗
int yourChose = JOptionPane.showConfirmDialog(null,"你可能是一不小心點錯了,再來一局?" );
if(yourChose == JOptionPane.OK_OPTION)
{//點擊「是」時
replay();
}
else
{//點擊 「否」 或 「取消」 時退出程序
System.exit(0);
}
}
else if(receive.isClicked ==false)
{//未翻到雷
showBombNumber(receive);
}
}
public static void showBombNumber(MyButton in)
{//翻開點擊的按鈕
int numberOfLandmine = 0;//記錄雷的個數
in.isClicked = true; //翻開標記設為真
/*檢測周圍8個方塊是否為雷*/
if(gui.lei[in.num_x-1][in.num_y-1].isBomb == true) numberOfLandmine++;//左上
if(gui.lei[in.num_x][in.num_y-1].isBomb == true) numberOfLandmine++; //上
if(gui.lei[in.num_x+1][in.num_y-1].isBomb == true) numberOfLandmine++;//右上
if(gui.lei[in.num_x+1][in.num_y].isBomb == true) numberOfLandmine++; //右
if(gui.lei[in.num_x+1][in.num_y+1].isBomb == true) numberOfLandmine++;//右下
if(gui.lei[in.num_x][in.num_y+1].isBomb == true) numberOfLandmine++; //下
if(gui.lei[in.num_x-1][in.num_y+1].isBomb == true) numberOfLandmine++;//左下
if(gui.lei[in.num_x-1][in.num_y].isBomb == true) numberOfLandmine++; //左
in.setIcon(new ImageIcon("images/"+numberOfLandmine+".png"));//根據周圍的雷數顯示數字圖標
gui.numberOfClicked++;//翻開格子數+1
if(gui.numberOfClicked==216)
{//翻開216個格子時游戲成功,用戶選擇是否再來一局
int yourChoice = JOptionPane.showConfirmDialog(null,"恭喜你成功了!再來一盤嗎?");
if(yourChoice == JOptionPane.OK_OPTION)
replay();
else
System.exit(0);
}
if(numberOfLandmine==0)
{//如果周圍無雷,則將周圍未翻開格子的全部翻開
if(gui.lei[in.num_x-1][in.num_y-1].isClicked == false)
showBombNumber(gui.lei[in.num_x-1][in.num_y-1]);
if(gui.lei[in.num_x][in.num_y-1].isClicked == false)
showBombNumber(gui.lei[in.num_x][in.num_y-1]);
if(gui.lei[in.num_x+1][in.num_y-1].isClicked == false)
showBombNumber(gui.lei[in.num_x+1][in.num_y-1]);
if(gui.lei[in.num_x+1][in.num_y].isClicked == false)
showBombNumber(gui.lei[in.num_x+1][in.num_y]);
if(gui.lei[in.num_x+1][in.num_y+1].isClicked == false)
showBombNumber(gui.lei[in.num_x+1][in.num_y+1]);
if(gui.lei[in.num_x][in.num_y+1].isClicked == false)
showBombNumber(gui.lei[in.num_x][in.num_y+1]);
if(gui.lei[in.num_x-1][in.num_y+1].isClicked == false)
showBombNumber(gui.lei[in.num_x-1][in.num_y+1]);
if(gui.lei[in.num_x-1][in.num_y].isClicked == false)
showBombNumber(gui.lei[in.num_x-1][in.num_y]);
}
}
public static void replay()
{//重新開始
gui.dispose(); //釋放框架資源
gui.timer.stop(); //終止計時器
Landmine ff = new Landmine();//重新創建一個主類的實例
//這幾條語句實現了重新開始————關閉上一個窗口,重新開啟一個
//但是這種方法會造成內存的浪費,一個改進的方法是不關閉當年窗口,而是將當前窗口重新初始化
}
public void mousePressed(MouseEvent e)
{//當滑鼠右鍵點擊時自動調用此函數
int mods = e.getModifiers();
MyButton receive = (MyButton)e.getSource();
if((mods & InputEvent.BUTTON3_MASK) != 0)
{//滑鼠右鍵
if(receive.isClicked == false)
{
receive.isRight = receive.isRight ? false : true;//改變receive.isRight的值
if(receive.isRight)
{//如果添加標記,則剩餘雷數-1,設置標簽為「旗幟」
gui.numberOfUnflaged--;
receive.setIcon(resources.flagIcon);
}
else
{//如果清除標記,則剩餘雷數+1,設置標簽為「未翻開」
gui.numberOfUnflaged++;
receive.setIcon(resources.smallIcon);
}
gui.numberOfUnflagedLabel.setText("剩餘雷數:"+gui.numberOfUnflaged);
//更新剩餘雷數標簽
}
}
}
public void mouseReleased(MouseEvent e){}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
}
//
// Help類,響應「關於」、「求救」
class Help implements ActionListener
{
static Resources resources = new Resources();
public static Landmine gui;
public Help(Landmine in)
{
gui = in ;
}
public void actionPerformed(ActionEvent event)
{
if(event.getActionCommand()=="關於")
JOptionPane.showMessageDialog(null,"掃雷1.2版。。小老頭出品");
if(event.getActionCommand()=="求救")
help();
}
public static void help()
{//求救
int stopNumber = (int)(Math.random() * gui.numberOfUnflaged + 1 );
int count = 0;
for(int i=1; i<17;++i )
{
for(int j=1; j<17; ++j)
{
if( gui.lei[i][j].isBomb && !gui.lei[i][j].isClicked && !gui.lei[i][j].isRight )
{
count++;
}
if(count == stopNumber)
{
gui.lei[i][j].setIcon(resources.badIcon);
return;
}
}
}
}
}
//
// Keylistener類,響應鍵盤事件
class Keylistener implements KeyListener
{
static Resources resources = new Resources();
Landmine gui;
public Keylistener(Landmine in)
{
gui = in;
}
public void keyPressed(KeyEvent e)
{//有鍵按下時自動執行該方法
if(e.getKeyCode() == KeyEvent.VK_UP)
{//按鍵為 向上 時,將所有未標記的地雷顯示出
for(int i=1; i<17; ++i)
{
for(int j=1; j<17; ++j)
{
if(gui.lei[i][j].isBomb && !gui.lei[i][j].isRight)
gui.lei[i][j].setIcon(resources.badIcon);
}
}
}
if(e.getKeyCode() == KeyEvent.VK_DOWN)
{//按鍵為 向下 時,將所有未標記的地雷恢復為未點擊的圖標
for(int i=1; i<17; ++i)
{
for(int j=1; j<17; ++j)
{
if(gui.lei[i][j].isBomb && !gui.lei[i][j].isRight)
gui.lei[i][j].setIcon(resources.smallIcon);
}
}
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
//
// 按鈕類 MyBtton
class MyButton extends JButton
{
public int num_x,num_y; //第幾號方塊
public boolean isBomb; //是否為雷
public boolean isClicked; //是否被點擊
public int BombFlag; //探雷標記
public boolean isRight; //是否點擊右鍵
public MyButton(int x, int y)
{
BombFlag = 0;
num_x = x;
num_y = y;
isBomb = false;
isClicked = true;
isRight = false;
}
}
//
// 資源類 其他類中用到的圖標,字體等
class Resources
{
public static ImageIcon deadIcon;
public static ImageIcon smallIcon;
public static ImageIcon clockIcon;
public static ImageIcon bombIcon;
public static ImageIcon flagIcon;
public static ImageIcon badIcon;
public static ImageIcon bombIconForLabel;
public static Font fontOne;
public Resources()
{
deadIcon = new ImageIcon("images/dead.gif");
smallIcon = new ImageIcon("images/smallIcon.png");
clockIcon = new ImageIcon("images/clock2.png");
bombIcon = new ImageIcon("images/bomb.png");
flagIcon = new ImageIcon("images/flag_2.png");
badIcon = new ImageIcon("images/bad.gif");
bombIconForLabel = new ImageIcon("images/bombForLabel.gif");
fontOne = new Font("null",Font.BOLD,20);
}
}
⑽ 求一個java掃雷游戲的程序源代碼,盡量多點注釋,要確實可用的!急急急急急急急急急急急急!!!!!
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ScanLei1 extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private Container contentPane;
private JButton btn;
private JButton[] btns;
private JLabel b1;
private JLabel b2;
private JLabel b3;
private Timer timer;
private int row=9;
private int col=9;
private int bon=10;
private int[][] a;
private int b;
private int[] a1;
private JPanel p,p1,p2,p3;
public ScanLei1(String title){
super(title);
contentPane=getContentPane();
setSize(297,377);
this.setBounds(400, 100, 400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timer =new Timer(1000,(ActionListener) this);
a = new int[row+2][col+2];
initGUI();
}
public void initGUI(){
p3=new JPanel();
b=bon;
JMenuBar menuBar=new JMenuBar();
JMenu menu1=new JMenu("游戲");
JMenu menu2=new JMenu("幫助");
JMenuItem mi1=new JMenuItem("初級");
JMenuItem mi2 = new JMenuItem("中級");
JMenuItem mi3 =new JMenuItem("高級");
mi1.addActionListener(this);
menu1.add(mi1);
mi2.addActionListener(this);
menu1.add(mi2);
mi3.addActionListener(this);
menu1.add(mi3);
menuBar.add(menu1);
menuBar.add(menu2);
p3.add(menuBar);
b1=new JLabel(bon+"");
a1=new int[bon];
btn =new JButton("開始");
btn.addActionListener(this);
b2=new JLabel("0");
b3=new JLabel("");
btns=new JButton[row*col];
p=new JPanel();
p.setLayout(new BorderLayout());
contentPane.add(p);
p.add(p3,BorderLayout.NORTH);
//combo=new JComboBox(new Object[]{"初級","中級","高級"} );
//加監聽
/*combo.addItemListener(new ItemListener(){
}});*/
p1=new JPanel();
//在那個位置
//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);
p1.add(b1);
p1.add(btn);
p1.add(b2);
p1.add(b3);
p.add(p3,BorderLayout.NORTH);
p.add(p1,BorderLayout.CENTER);
p2=new JPanel();
p2.setLayout(new GridLayout(row,col,0,0));
for(int i=0;i<row*col;i++){
btns[i]=new JButton("");
btns[i].setMargin(new Insets(0,0,0,0));
btns[i].setFont(new Font(null,Font.BOLD,25));
btns[i].addActionListener(this);
btns[i].addMouseListener(new NormoreMouseEvent());
p2.add(btns[i]);
}
contentPane.add(p,BorderLayout.NORTH);
contentPane.add(p2,BorderLayout.CENTER);
}
public void go(){
setVisible(true);
}
public static void main(String[] args){
new ScanLei1("掃雷").go();
}
public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){
int p=1;
if(a[x][y]==0){
a[x][y]=10;
btns[i].setEnabled(false); //33
for(int l=y-1;l<=y+1;l++){
int m=x-1-1;
int n=l-1;
p=1;
System.out.println(a[1][2]);
if(n>-1&&n<col&&m>-1&&m<row)
{
for(int q=0;q<row&&p==1;q++){//col-->row;
if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){
if(a[x-1][l]!=0&&a[x-1][l]!=10){
btns[n+col*q].setText(a[x-1][l]+"");
a[x-1][l]=10;
btns[n+col*q].setEnabled(false);
}
else if(a[x-1][l]==0){
//a[x-1][l]=10;
btns[n+col*q].setEnabled(false);
out(a,btns,e,n+col*q,x-1,l); ////55////
a[x-1][l]=10;
btns[n+col*q].setEnabled(false);
}
p=0;
}
}
}
p=1;
m=x;
if(n>-1&&n<col&&m>-1&&m<col)
{
for(int q=0;q<row&&p==1;q++){
if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){
if(a[x+1][l]!=0&&a[x+1][l]!=10){
btns[n+col*q].setText(a[x+1][l]+"");
a[x+1][l]=10;
btns[n+col*q].setEnabled(false);
}
else if(a[x+1][l]==0){
out(a,btns,e,n+col*q,x+1,l);///55////
a[x+1][l]=10;
btns[n+col*q].setEnabled(false);
}
p=0;
}
}
}
}
int m=x-1;
int n=y-1-1;
p=1;
if(n>-1&&n<col&&m>-1&&m<col)
{
for(int q=0;q<row&&p==1;q++){
if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){
if(a[x][y-1]!=0&&a[x][y-1]!=10){
btns[n+col*q].setText(a[x][y-1]+"");
a[x][y-1]=10;
btns[n+col*q].setEnabled(false);
}
else if(a[x][y-1]==0){
out(a,btns,e,n+col*q,x,y-1);
a[x][y-1]=10;
btns[n+col*q].setEnabled(false);
}
p=0;
}
}
}
p=1;
m=x-1;
n=y+1-1;
if(n>-1&&n<col&&m>-1&&m<col)
{
for(int q=0;q<row&&p==1;q++){
if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){
if(a[x][y+1]!=0&&a[x][y+1]!=10){
btns[n+col*q].setText(a[x][y+1]+"");
a[x][y+1]=10;
btns[n+col*q].setEnabled(false);
}
else if(a[x][y+1]==0){
out(a,btns,e,n+col*q,x,y+1);
a[x][y+1]=10;
btns[n+col*q].setEnabled(false);
}
p=0;
}
}
}
}
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="初級"){
row=9;
col=9;
bon=10;
a1=new int[bon];
b=bon;
//setSize(297,377);
a = new int[row+2][col+2];
this.remove(p2);
timer.stop();
b1.setText("10");
b2.setText("0");
b3.setText("");
btns=new JButton[row*col];
p2=new JPanel();
p2.setLayout(new GridLayout(row,col,0,0));
for(int i=0;i<row*col;i++){
btns[i]=new JButton(" ");
btns[i].setMargin(new Insets(0,0,0,0));
btns[i].setFont(new Font(null,Font.BOLD,25));
btns[i].addActionListener(this);
btns[i].addMouseListener(new NormoreMouseEvent());
p2.add(btns[i]);
}
contentPane.add(p2,BorderLayout.CENTER);
//setSize(297,377);
this.pack();
for(int i=0;i<row*col;i++){
btns[i].setText(" ");
btns[i].setEnabled(true);
}
for(int i=0;i<row+2;i++){
for(int j=0;j<col+2;j++){
a[i][j]=0;
}
}
}else if(e.getActionCommand()=="中級"){
row=16;
col=16;
bon=40;
//setSize(33*col,33*row+80);
a1=new int[bon];
a = new int[row+2][col+2];
b=bon;
this.remove(p2);
timer.stop();
b1.setText("40");
b2.setText("0");
b3.setText("");
btns=new JButton[row*col];
p2=new JPanel();
p2.setLayout(new GridLayout(row,col,0,0));
for(int i=0;i<row*col;i++){
btns[i]=new JButton(" ");
btns[i].setMargin(new Insets(0,0,0,0));
btns[i].setFont(new Font(null,Font.BOLD,25));
btns[i].addActionListener(this);
btns[i].addMouseListener(new NormoreMouseEvent());
p2.add(btns[i]);
}
contentPane.add(p2,BorderLayout.CENTER);
this.pack();
//setSize(33*col,33*row+80);
for(int i=0;i<row*col;i++){
btns[i].setText("");
btns[i].setEnabled(true);
}
for(int i=0;i<row+2;i++){
for(int j=0;j<col+2;j++){
a[i][j]=0;
}
}
}else if(e.getActionCommand()=="高級"){
row=16;
col=32;
bon=99;
setSize(33*col,33*row+80);
a1=new int[bon];
a = new int[row+2][col+2];
b=bon;
this.remove(p2);
timer.stop();
b1.setText("99");
b2.setText("0");
b3.setText("");
btns=new JButton[row*col];
p2=new JPanel();
p2.setLayout(new GridLayout(row,col,0,0));
for(int i=0;i<row*col;i++){
btns[i]=new JButton(" ");
btns[i].setMargin(new Insets(0,0,0,0));
btns[i].setFont(new Font(null,Font.BOLD,25));
btns[i].addActionListener(this);
btns[i].addMouseListener(new NormoreMouseEvent());
p2.add(btns[i]);
}
contentPane.add(p2,BorderLayout.CENTER);
//setSize(33*col,33*row+80);
this.pack();
for(int i=0;i<row*col;i++){
btns[i].setText("");
btns[i].setEnabled(true);
}
for(int i=0;i<row+2;i++){
for(int j=0;j<col+2;j++){
a[i][j]=0;
}
}
}
if(e.getSource()==btn){
timer.start();
b=bon;
b3.setText("");
//System.out.println(bon);
//清空
for(int i=0;i<row*col;i++){
btns[i].setText("");
btns[i].setEnabled(true);
}
for(int i=0;i<row+2;i++){
for(int j=0;j<col+2;j++){
a[i][j]=0;
}
}
//產生隨機數
for(int i=0;i<bon;i++)
{ int p=1;
int m=(int)(Math.random()*row*col);
while(p==1){
int l=1;
int j;
for( j=0;j<i&&l==1;j++){
if(a1[j]==m){
m=(int)(Math.random()*row*col);
l=0;
}
}
if(j==i){
a1[i]=m;
p=0;
}
}
}
b1.setText(bon+"");
b2.setText("0");
//布雷
for(int i=0;i<bon;i++){
int x=(a1[i]/col+1);
int y=(a1[i]%col+1);
a[x][y]=100;
}
for(int i=0;i<row+2;i++){
for(int j=0;j<col+2;j++){
if(i==0||j==0||i==row+1||j==col+1){
a[i][j]=0;
}
}
}
for(int i=1;i<=row;i++){
for(int j=1;j<=col;j++){
if(a[i][j]!=100){
for(int l=j-1;l<=j+1;l++){
if(a[i-1][l]==100){
a[i][j]++;
}
if(a[i+1][l]==100){
a[i][j]++;
}
}
if(a[i][j-1]==100){
a[i][j]++;
}
if(a[i][j+1]==100){
a[i][j]++;
}
}
}
}
}
if(e.getSource()==timer)
{
String time=b2.getText().trim();
int t=Integer.parseInt(time);
//System.out.println(t);
if(t>=600){
timer.stop();
}else{
t++;
b2.setText(t+"");
}
}
for(int i=0;i<col*row;i++){
if(btns[i].getText()!="★")
{
int x=i/col+1;
int y=i%col+1;
if(e.getSource()==btns[i]&&a[x][y]==100){
btns[i].setText("★");
btns[i].setEnabled(false);
a[x][y]=10;
for(int k=0;k<col*row;k++){
int m1=k/col+1;
int n1=k%col+1;
if(a[m1][n1]!=10&&btns[k].getText()=="★"){
btns[k].setText("*o*");
}
}
for(int j=0;j<col*row;j++){
int m=j/col+1;
int n=j%col+1;
if(a[m][n]==100){
btns[j].setText("★");
btns[j].setEnabled(false);
b3.setText("你輸了 !!");
}
btns[j].setEnabled(false);
a[m][n]=10;
}
timer.stop();
}
else if(e.getSource()==btns[i]){
if(a[x][y]==0){
out(a,btns,e,i,x,y);
a[x][y]=10;
btns[i].setEnabled(false);
}
if(a[x][y]!=0&&a[x][y]!=10){
btns[i].setText(a[x][y]+"");
btns[i].setEnabled(false);
a[x][y]=10;
}
}
}else if(btns[i].getText()=="★"){
}
}
}
class NormoreMouseEvent extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
System.out.println(b);
for(int i=0;i<col*row;i++){
int x1=i/col+1;
int y1=i%col+1;
if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10)
{
if(e.getButton()==MouseEvent.BUTTON3){
btns[i].setText("★");
b--;
if(b==0){
int flag=0;
for(int j=0;j<col*row;j++){
int x=j/col+1;
int y=j%col+1;
if(a[x][y]==100&&btns[j].getText()=="★"){
flag++;
}
}
if(flag==bon){
timer.stop();
b3.setText("你贏了!");
}
}
b1.setText(b+"");
}
}else if(e.getSource()==btns[i]&&btns[i].getText()=="★"&&a[x1][y1]!=-1){
if(e.getButton()==MouseEvent.BUTTON3){
btns[i].setText("");
b++;
if(b>bon){
b1.setText(bon+"");
}
else{
b1.setText(b+"");
}
btns[i].setEnabled(true);
}
}
}
}
}
}