1. 程式人生 > 程式設計 >java實現對對碰小遊戲

java實現對對碰小遊戲

本文例項為大家分享了java實現對對碰的具體程式碼,供大家參考,具體內容如下

- 遊戲實現功能:分別點選兩張相鄰的影象按鈕進行交換(重點相鄰),交換後的兩個影象按鈕的相鄰水平或者垂直方向上,與之相同的影象超過規定個數後(這裡規定為3個)就將其全部消除(置為空白按鈕),上面的影象按鈕也分別隨之向下移動,將空白補齊(這裡我們可以理解為影象按鈕和空白按鈕進行交換)。

- 遊戲設計思路:

1.建立影象按鈕陣列,設定其基本屬性;
2.給每個影象按鈕配置相應的ID,用來標記影象資訊,對於ID相同的按鈕,影象也相同;
3.設定遍歷全域性判斷是否可以建立相連按鈕的函式;
4.設定遍歷全域性將可以建立相連的按鈕影象ID置為EMPTY,將按鈕置為空白按鈕;

5.設定移動函式,將空白按鈕與上層非空白按鈕相互交換的函式,將空白按鈕移動到上層;
6.設定更新函式,將移動到上層的空白按鈕再隨機匹配影象,繼續使用;
7.設定交換按鈕函式;
8.記錄遊戲得分,給一個確定的目標成績,達到即可贏得遊戲;
9.設定一個進度條,記錄遊戲進行的時間;
10.設定一個時間記錄器(定時器);
11.設計遊戲介面基本資訊(根據個人愛好設計即可);

- 遊戲程式碼

---mybutton類,設定了每個按鈕物件的基本資訊
package supperzzle;

import javax.swing.Icon;
import javax.swing.JButton;

public class MyButton extends JButton{
  private final int Width = 30;//設定按鈕的寬度
  private final int Height = 30;
  private int ID;//設定按鈕的ID-----ID代表每一個按鈕裡面存放的資料

  private int buttonPosX = 0;
  private int buttonPosY = 0;

  public MyButton(int id,Icon icon)//建構函式
  {
    this.setIcon(icon);
    this.ID = id;
    this.setSize(Width,Height);//設定按鈕的邊框大小
    this.setFocusable(true);//去掉按鈕的聚焦框
    this.setBorderPainted(false);//去掉邊框
    this.setContentAreaFilled(false);//不顯示外圍矩形邊框
  }

  public int GetID()
  {
    return ID;
  }
  public void SetID(int id)
  {
    this.ID = id;
  }
}
//-----這是遊戲的重點了,基本遊戲介面設計--GamePanel類---對遊戲的介面進行了基本的設定(寫的有點挫,,有什麼好的建議請盡情提的不要拘謹,哈哈)
package supperzzle;

import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventListener;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class GamePanel extends JPanel implements ActionListener{
  private final int row = 10;
  private final int col = 10;
  private final int lineCount = 3;//設定幾連可碰消除
  private int grade = 0;//記錄得分
  private final int score = 10;//設定每次消去一個方塊獲得的分數

  public MyButton mybutton[] = new MyButton[row*col];//這裡只是開闢了相應的空間

  private final int countImage = 7;
  private ImageIcon imageIcon[] = new ImageIcon[countImage];//設定圖示陣列
  private final int EMPTY = -1;

  private Random random = new Random();

  private int posx = 0;
  private int posy = 0;//儲存第一次按鈕按下去的座標
  private boolean IsSecond = false;


  public GamePanel()//遊戲面板的建構函式----實現圖片載入,陣列圖示的載入,以及按鈕的基本設定
  {
    this.setLayout(new GridLayout(row,col,0));//建立一個網路佈局管理格式---row行col列
    for(int i = 0; i < countImage; i++)//圖示陣列初始化
    {
//     Image image = Toolkit.getDefaultToolkit().getImage("F:/Image/supperzzle/angrybird"+i+".png");
      Image image = Toolkit.getDefaultToolkit().getImage("F:/Image/LinkGame/pic"+i+".png");
      imageIcon[i] = new ImageIcon(image);//每一個數組元素都得到了相應的圖示
    }
    for(int i = 0; i < row; i++)
    {
      for(int j = 0; j < col; j++)
      {
        int index = random.nextInt(countImage);//隨機生成一個數作為圖示陣列的下標
        mybutton[i*col+j] = new MyButton(index,imageIcon[index]);//給每個元素都進行了初始化
        mybutton[i*col+j].addActionListener(this);//按鈕新增監聽機制
        mybutton[i*col+j].setEnabled(false);//設定按鈕為無效
        this.add(mybutton[i*col+j]);//將按鈕載入在該面板中
      }
    }
  }

  public boolean YesOrNoThreeLink(int x,int y)//判斷該座標同一個方向上是否可以建立連續相同id的方塊按鈕
  {
    int linked = 1;
    //判斷垂直方向上面是否有連續相同的
    for(int i = x-1; i >= 0; i--)
    {
      if(mybutton[i*col+y].GetID() == mybutton[x*col+y].GetID())
      {
        linked++;
      }
      else
      {
        break;
      }
    }
    for(int i = x+1; i < row; i++)//判斷該座標的下面
    {
      if(mybutton[i*col+y].GetID() == mybutton[x*col+y].GetID())
      {
        linked++;
      }
      else
      {
        break;
      }
    }
    if(linked >= lineCount)
    {
      return true;
    }
    //判斷水平方向上面是否有裡連續相同的方塊
    linked = 1;
    for(int i = y-1; i >= 0; i--)//判斷水平向左
    {
      if(mybutton[x*col+i].GetID() == mybutton[x*col+y].GetID())
      {
        linked++;
      }
      else
        break;
    }
    for(int i = y+1; i < col; i++)//判斷水平向右
    {
      if(mybutton[x*col+i].GetID() == mybutton[x*col+y].GetID())
      {
        linked++;
      }
      else
        break;
    }
    if(linked >= lineCount)//說明滿足條件建立了連線
    {
      return true;
    }
    return false;
  }

  public void RemoveLink(int x,int y)//移除相同ID的方塊設定相同的方塊ID為EMPTY,並計算得分
  {
    int linked1 = 0;
    int linked2 = 0;
    int tempxStart = x;
    int tempxEnd = x;//分別儲存第一個和最後一個與該點ID相同的x座標
    int tempyStart = y;
    int tempyEnd = y;//分別儲存第一個和最後一個與該點ID相同的y座標
    //先判斷垂直方向上面的---上下行
    for(int i = x-1; i >= 0; i--)//判斷該座標的上面
    {
      if(mybutton[i*col+y].GetID() == mybutton[x*col+y].GetID())
      {
        linked1++;
        tempxStart = i;
      }
      else
      {
        break;
      }
    }
    for(int i = x+1; i < row; i++)//判斷該座標的下面
    {
      if(mybutton[i*col+y].GetID() == mybutton[x*col+y].GetID())
      {
        linked1++;
        tempxEnd = i;
      }
      else
      {
        break;
      }
    }
    if(linked1 + 1 >= lineCount)
    {
      for(int i = tempxStart; i <= tempxEnd; i++)
      {
        mybutton[i*col+y].SetID(EMPTY);
      }
//     grade += linked*score;
      grade += linked1*score;
    }
    //判斷水平方向上面的---左右列
    for(int i = y-1; i >= 0; i--)//判斷水平向左
    {
      if(mybutton[x*col+i].GetID() == mybutton[x*col+y].GetID())
      {
        linked2++;
        tempyStart = i;
      }
      else
        break;
    }
    for(int i = y+1; i < col; i++)//判斷水平向右
    {
      if(mybutton[x*col+i].GetID() == mybutton[x*col+y].GetID())
      {
        linked2++;
        tempyEnd = i;
      }
      else
        break;
    }
    if(linked2+1 >= lineCount)//說明滿足條件建立了連線
    {
      for(int i = tempyStart; i <= tempyEnd; i++)
      {
        mybutton[x*col+i].SetID(EMPTY);
      }
//     grade += score*linked;
      grade += score*linked2;
    }
    grade += score;
  }

  public int GetGrade()//獲取得分
  {
    return grade;
  }

  public void SetGrade(int n)
  {
    this.grade = n;
  }

  public void SwapElement(int x,int y)//交換元素
  {
    if(x >= 0 && x < row && y >= 0 && y < col)
    {
      if(!IsSecond)//第一次點選按鈕
      {
        posx = x;
        posy = y;
        IsSecond = true;
        System.out.println("第一次點選:posx->"+posx+" posy->"+posy);
      }
      else//第二次點選按鈕
      {
        //判斷是否是相鄰的兩個方塊
        System.out.println("第2次點選:x->"+x+" y->"+y);
        if(1 == Math.abs(posx - x) && posy == y
        || 1 == Math.abs(posy - y) && posx == x)//判斷是否是相鄰的座標
        {
          //先交換
          System.out.println("交換");
          int temp = mybutton[posx*col+posy].GetID();
          mybutton[posx*col+posy].SetID(mybutton[x*col+y].GetID()); 
          mybutton[x*col+y].SetID(temp);
//         showImageButton();
          mybutton[x*col+y].setIcon(imageIcon[temp]);
          mybutton[posx*col+posy].setIcon(imageIcon[mybutton[posx*col+posy].GetID()]);
          //再判斷
          if(YesOrNoThreeLink(x,y) || YesOrNoThreeLink(posx,posy))
          {
            if(YesOrNoThreeLink(x,y))
            {
              RemoveLink(x,y);
              GameFrame.texteara.setText(Integer.toString(GetGrade()));
            }
            if(YesOrNoThreeLink(posx,posy))
            {
              RemoveLink(posx,posy);
              GameFrame.texteara.setText(Integer.toString(GetGrade()));
            }
            //開始掉方塊,全盤處理所有下面的空白方塊
            DownButton();
            //更新
            UpDateButton();
            showImageButton();
            GameFrame.texteara.setText(Integer.toString(GetGrade()));
            while(GlobalSearch(1))//掃描全盤
            {
              GlobalSearch(0);//消除
              DownButton();
              UpDateButton();
              showImageButton();
              GameFrame.texteara.setText(Integer.toString(GetGrade()));
            }
          }
          else
          {
            //沒有相同的方塊就再換回來
            temp = mybutton[posx*col+posy].GetID();
            mybutton[posx*col+posy].SetID(mybutton[x*col+y].GetID()); 
            mybutton[x*col+y].SetID(temp);
//           showImageButton();
            mybutton[x*col+y].setIcon(imageIcon[temp]);
            mybutton[posx*col+posy].setIcon(imageIcon[mybutton[posx*col+posy].GetID()]);
          }
        }
        IsSecond = false;
      }
    }
  }

  public void DownButton()//將底層的空白的方塊全部上移,將上面的非空白方塊下移補齊
  {
    for(int i = row-1; i > 0; i--)//行--從最後一行開始
    {
      for(int j = 0; j < col; j++)//列---從第一列開始
      {
        if(mybutton[i*col+j].GetID() == EMPTY)//交換每個按鈕決定影象的ID號即可
        {
          //交換同列上面非EMPTY的結點
          for(int k = i-1; k >= 0; k--)
          {
            if(mybutton[k*col+j].GetID() != EMPTY)
            {
              int id = mybutton[i*col+j].GetID();
              mybutton[i*col+j].SetID(mybutton[k*col+j].GetID());
              mybutton[k*col+j].SetID(id);
              break;
            }
          }
        }
      }
    }
  }

  public boolean GlobalSearch(int flag)//全盤掃描
  {
    if(flag == 1)//----------只是掃描所有的元素是否存在相鄰的連續方塊
    {
      for(int i = 0; i < row; i++)
      {
        for(int j = 0; j < col; j++)
        {
          if(YesOrNoThreeLink(i,j))
          {
            return true;
          }
        }
      }
    }
    else if(flag == 0)//-------掃描加消除該節點置為EMPTY
    {
      for(int i = 0; i < row; i++)
      {
        for(int j = 0; j < col; j++)
        {
          RemoveLink(i,j);
        }
      }
      return true;
    }

    return false;
  }

  public void showImageButton()//將所有的按鈕的圖示重新繪製一次
  {
    for(int i = 0; i < row; i++)
    {
      for(int j = 0; j < col; j++)
      {
        mybutton[i*col+j].setIcon(imageIcon[mybutton[i*col+j].GetID()]);
      }
    }
  }

  public void UpDateButton()//更新按鈕裡面的座標id-----讓EMPTY的按鈕重新獲得隨機ID
  {
    for(int i = 0; i < row; i++)
    {
      for(int j = 0; j < col; j++)
      {
        if(mybutton[i*col+j].GetID() == EMPTY)
        {
          int index = random.nextInt(countImage);
          mybutton[i*col+j].SetID(index);
        }
      }
    }
  }

  public int GetRow()
  {
    return row;
  }
  public int GetCol()
  {
    return col;
  }

  public void actionPerformed(ActionEvent e)//監聽機制
  {
    for(int i = 0; i < row; i++)
    {
      for(int j = 0; j < col; j++)
      {
        if(e.getSource() == mybutton[i*col+j])//交換元素物件
        {
          SwapElement(i,j);
          GameFrame.texteara.setText(Integer.toString(GetGrade()));
          break;
        }
      }
    }
    if(grade > 8000 && GameFrame.timer.isRunning())
    {
      JOptionPane.showConfirmDialog(null,"恭喜您過關","Win",JOptionPane.CLOSED_OPTION);
      for(int i = 0; i < row; i++)
      {
        for(int j = 0; j < col; j++)
        {
          mybutton[i*col+j].setEnabled(false);
          GameFrame.buttonstart.setEnabled(true);
          GameFrame.timer.stop();
        }
      }
    }
  }

}
//遊戲走到這裡就是真正的遊戲介面了,遊戲開始的入口--GameFrame類,設計遊戲視窗和建立遊戲
package supperzzle;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.Timer;

public class GameFrame extends JFrame implements ActionListener{
  private JPanel paneone = new JPanel();
  public static JButton buttonstart = new JButton("遊戲開始");
  private JButton buttonend = new JButton("遊戲結束");
  private JLabel labelGrade = new JLabel("遊戲得分");
  private JLabel labelTime = new JLabel("遊戲時間");
  public static JTextField texteara = new JTextField(10);//設定文字編輯域
  GamePanel gamepanel = new GamePanel();
  private int gamerow = gamepanel.GetRow();
  private int gamecol = gamepanel.GetCol();
  private JProgressBar progressbar = new JProgressBar();//建立一個進度條
  public static Timer timer;//建立一個時間計時器


  public GameFrame()
  {
    Container con = this.getContentPane();
    con.setLayout(new BorderLayout());
    paneone.setLayout(new FlowLayout());
    paneone.add(buttonstart);//新增開始按鈕
    paneone.add(labelGrade);//新增得分編輯框
    paneone.add(texteara);//新增文字域
    paneone.add(labelTime);//新增時間編輯框
    paneone.add(progressbar);//新增一個進度條
    paneone.add(buttonend);//新增結束按鈕
    con.add(paneone,BorderLayout.NORTH);
    con.add(gamepanel,BorderLayout.CENTER);
    this.setBounds(300,600,700);
    this.setTitle("對對碰遊戲");
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定視窗關閉

    buttonstart.addActionListener(this);
    buttonend.addActionListener(this);

  }

  public void actionPerformed(ActionEvent e)
  {
    if(e.getSource() == buttonstart)//點選開始按鈕
    {
      gamepanel.SetGrade(0);//重新設定得分
      buttonstart.setEnabled(false);
      progressbar.setMaximum(100);//設定進度條的最大最小範圍
      progressbar.setMinimum(0);
      progressbar.setStringPainted(true);
      timer = new Timer(800,new TimeListener());
      timer.start();
      for(int i = 0; i < gamerow; i++)
      {
        for(int j = 0; j < gamecol; j++)
        {
          gamepanel.mybutton[i*gamecol+j].setEnabled(true);
        }
      }
      initGame();
      texteara.setText(Integer.toString(gamepanel.GetGrade()));
    }
    if(e.getSource() == buttonend)
    {
      System.exit(1);
    }
  }

  public void initGame()
  {
    while(gamepanel.GlobalSearch(1))
    {
      gamepanel.GlobalSearch(0);
      gamepanel.DownButton();
      gamepanel.UpDateButton();
      gamepanel.showImageButton();
    }
  }

  class TimeListener implements ActionListener//建立了一個自定義的時間監聽機制
  {
    int times = 0;
    public void actionPerformed(ActionEvent e)
    {
      progressbar.setValue(times++);
      if(times > 100)
      {
        timer.stop();
        for(int i = 0; i < gamerow; i++)
        {
          for(int j = 0; j < gamecol; j++)
          {
            gamepanel.mybutton[i*gamecol+j].setEnabled(false);
          }
        }
        buttonstart.setEnabled(true);
      }
    }
  }

  public static void main(String[] args) {
    GameFrame gameframe = new GameFrame();
  }

}

- 執行結果

這是執行後的遊戲開始介面:

這是點選開始以後的介面,這樣你就可以開始玩你的小遊戲了!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。