java實現貪吃蛇小游戲


java實現貪吃蛇

游戲的各個類存放的位置如圖所示

 

 

備注:

  • header圖片為窗口上部分圖片,像素為850*64

  • body圖片為小蛇的身體圖片,像素為25*25

  • food圖片為小蛇的食物圖片,像素為25*25

  • up,down,right,lift圖片均為小蛇的頭部圖片,因為小蛇要由鍵盤控制轉向,所以up,down,right,lift圖片分別代表了小蛇的頭部朝向。

 

讀者可以根據所提供的像素自己制作小蛇的相關圖片。

 

 

游戲的啟動程序

package EatSnake;

import javax.swing.*;
//開始游戲主程序
public class StartGame {
   public static void main(String[] args) {
       JFrame frame=new JFrame();

       frame.setResizable(false);
       frame.setBounds(10,10,900,720);
       frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

       frame.add(new GamePanel());
       frame.setVisible(true);
  }
}

游戲的圖片資源

package EatSnake;
import javax.swing.*;
import java.net.URL;

//獲得各個圖片資源
public class Data {
   public static URL headerURl=Data.class.getResource("statics/header.png");
   public static ImageIcon header=new ImageIcon(headerURl);    //頭部封面

   public static URL rightURl=Data.class.getResource("statics/right.png");
   public static ImageIcon right=new ImageIcon(rightURl);

   public static URL leftURL=Data.class.getResource("statics/lift.png");
   public static ImageIcon left=new ImageIcon(leftURL);

   public static URL upURL=Data.class.getResource("statics/up.png");
   public static ImageIcon up=new ImageIcon(upURL);

   public static URL downURL=Data.class.getResource("statics/down.png");
   public static ImageIcon down=new ImageIcon(downURL);

   public static URL bodyURL=Data.class.getResource("statics/body.png");
   public  static ImageIcon body=new ImageIcon(bodyURL);

   public static URL foodURL=Data.class.getResource("statics/food.png");
   public static ImageIcon food=new ImageIcon(foodURL);   //食物圖標

}

游戲的繪制面板

package EatSnake;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class GamePanel extends JPanel implements KeyListener,ActionListener {
   //定義蛇的數據結構
   int length;
   int[] snakeX=new int[600];
   int[] snakeY=new int[500];
   String fx;      //初始化蛇頭方向
   //設置食物的相關屬性
   int foodX,foodY;
   Random random=new Random();
   int score;      //定義在游戲中獲得的積分.


   //設置游戲當前狀態為不開始
   boolean isStart=false;      //設置游戲的初始狀態是沒開始
   boolean isFail=false; //判斷游戲是否失敗,默認沒失敗
   //設置定時器--->通過時間監聽來完成
   //以毫秒為單位,一秒刷新十次
   Timer timer=new Timer(100,this);
   //構造器
   public GamePanel(){

       init();
       this.setFocusable(true);        //獲取焦點事件
       this.addKeyListener(this);      //添加鍵盤監聽事件
       timer.start();
  }
   public void init(){
       length=3;
       snakeX[0]=100;snakeY[0]=100; //腦袋的坐標
       snakeX[1]=75;snakeY[1]=100; //第一個身體的坐標
       snakeX[2]=50;snakeY[2]=100; //第二個身體的坐標
       fx="R";
       //把食物隨機分布在界面上
       foodX=25+25* random.nextInt(34);    //random隨機產生一個[0,34)的數字
       foodY=75+25*random.nextInt(24);     //random隨機產生一個[0,24)的數字
       score=0;
  }
   @Override
   //繪制畫板,游戲中的所有東西都通過這個畫筆來畫(實現的抽象方法)
   protected void paintComponent(Graphics g) {
       super.paintComponent(g);        //清屏
       this.setBackground(Color.WHITE);
       Data.header.paintIcon(this,g,25,11);//頭部廣告欄。
       g.fillRect(25,75,850,600);

       g.setColor(Color.black);
       g.setFont(new Font("微軟雅黑",Font.BOLD,20));   //設置畫筆的字體屬性
       g.drawString("長度:"+length,650,35);
       g.drawString("分數:"+score,650,55);

       Data.food.paintIcon(this,g,foodX,foodY);//用g畫筆畫到當前(this)頁面上,坐標為(foodX,foodY)
       //吧小蛇畫上去
       if(fx.equals("R")) {
           Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);//蛇頭初始化方向向右
      }else if(fx.equals("L")){
           Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);
      }else if(fx.equals("U")){
           Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
      }else if(fx.equals("D")){
           Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
      }

       for(int i=1;i<length;i++){
           Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//第一個身體的坐標
      }



       if(isStart==false){
           g.setColor(Color.WHITE);   //設置畫筆的顏色
           g.setFont(new Font("微軟雅黑",Font.BOLD,40));   //設置畫筆的字體屬性
           g.drawString("按下空格開始游戲",300,300);   //設置要顯示的字體
      }
       if(isFail){
           g.setColor(Color.RED);   //設置畫筆的顏色
           g.setFont(new Font("微軟雅黑",Font.BOLD,40));   //設置畫筆的字體屬性
           g.drawString("GAME OVER",300,300);   //設置要顯示的字體
      }

  }

   //設置鍵盤監聽時間
   @Override
   public void keyPressed(KeyEvent e) {
       int keyCode=e.getKeyCode();
       if(keyCode==KeyEvent.VK_SPACE){   //如果按下的鍵位為空格,則讓小蛇動起來,再一次按下空格小蛇停止移動。
          if(isFail){                      //如果isFail為true,重新開始游戲
              isFail=false;
              init();
          }else{
              isStart=!isStart;
          }
           repaint();      //讓面板重新畫一遍
      }
       if(keyCode==KeyEvent.VK_UP){
           fx="U";
      }else if(keyCode==KeyEvent.VK_DOWN){
           fx="D";
      }else if(keyCode==KeyEvent.VK_RIGHT){
           fx="R";
      }else if(keyCode==KeyEvent.VK_LEFT){
           fx="L";
      }

  }

   @Override
   //通過固定的時間來刷新
   public void actionPerformed(ActionEvent e) {
       if(isStart &&isFail==false){      //如果游戲是開始狀態就讓小蛇移動

           //吃食物
           if(snakeX[0]==foodX&&snakeY[0]==foodY){
               length++;       //吃到食物身體自動加一
               score=score+10;  //吃到一個食物分數加十
               //再次隨機生成食物
               foodX=25+25* random.nextInt(34);    //random隨機產生一個[0,34)的數字
               foodY=75+25*random.nextInt(24);     //random隨機產生一個[0,24)的數字
          }



           //控制移動
           for(int i=length-1;i>0;i--){
               snakeX[i]=snakeX[i-1];
               snakeY[i]=snakeY[i-1];
          }
           if(fx.equals("R")){
               snakeX[0]=snakeX[0]+25;
               if(snakeX[0]>850)       //邊界判斷
                   snakeX[0]=25;
          }else if(fx.equals("L")){
               snakeX[0]=snakeX[0]-25;
               if(snakeX[0]<25)
                   snakeX[0]=850;
          }else if(fx.equals("D")){
               snakeY[0]=snakeY[0]+25;
               if(snakeY[0]>650)
                   snakeY[0]=75;
          }else if(fx.equals("U")){
               snakeY[0]=snakeY[0]-25;
               if(snakeY[0]<75)
                   snakeY[0]=650;
          }
           //失敗判定,撞到自己算是失敗
           for(int i=1;i<length;i++){
               if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
                   isFail=true;
              }
          }

           repaint();
      }
       timer.start();

  }




   @Override
   public void keyReleased(KeyEvent e) {

  }
   @Override
   public void keyTyped(KeyEvent e) {

  }

}
​本文也可以在公眾號中查看了解




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM