Java實戰之貪吃蛇小遊戲(源碼+註釋)
一、工程文件
二、Main.java
package com.company; import javax.swing.*; public class Main { public static void main(String[] args) { //創建窗體對象 JFrame frame = new JFrame(); //創建窗體參數() frame.setBounds(10,10,900,720); //設置不允許更改大小 //frame.setResizable(false); //設置關閉方式 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //添加主題邏輯框架 frame.add(new Mpanel()); //設置窗體可見 frame.setVisible(true); } }
三、Mpanel.java
package com.company; import javax.imageio.ImageIO; import javax.sound.sampled.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Random; //基本套路,繼承JPanel,實現KeyListener, ActionListener接口 public class Mpanel extends JPanel implements KeyListener, ActionListener { //定義所需要的圖片元素 //標題 ImageIcon title; //蛇的身體部位 ImageIcon body; //蛇向上方向的頭 ImageIcon up; //蛇向下方向的頭 ImageIcon down; //蛇向左方向的頭 ImageIcon left; //蛇向右方向的頭 ImageIcon right; //食物元素 ImageIcon food; //定義初始長度 int len = 3; //定義初始分數 int score = 0; //存放蛇位置坐標的數組 int[] snakex = new int[750]; int[] snakey = new int[750]; //定義方向 String fx = "R"; //定義遊戲是否開始 Boolean isStart = false; //定義遊戲是否失敗 Boolean isFailed = false; //定義遊戲時鐘,在此可以設置蛇移動速度,默認100ms Timer timer = new Timer(100,this); //定義食物的坐標 int foodx; int foody; //引入隨機數,用於生成食物的隨機位置 Random random = new Random(); //定義背景音樂 Clip bgm; //構造方法 public Mpanel(){ //加載圖片元素 loadImages(); //初始化數據 initSnake(); //設置聚焦 this.setFocusable(true); //設置鍵盤監聽 this.addKeyListener(this); //開始計時 timer.start(); //加載背景音樂 loadBGM(); } //設置繪圖元素 public void paintComponent(Graphics g){ //調用父類方法 super.paintComponent(g); //設置背景顏色為白色 this.setBackground(Color.white); //設置標題元素位置 title.paintIcon(this,g,25,11); //設置白色背景填充位置 g.fillRect(25,75,850,600); //設置畫筆顏色為白色 g.setColor(Color.white); //設置長度顯示 g.drawString("Len: " + len,750,35); //設置分數顯示 g.drawString("Score: " + score,750,50); //根據方向調用相應的蛇頭元素 if(fx == "R"){ right.paintIcon(this,g,snakex[0],snakey[0]); } else if(fx == "L"){ left.paintIcon(this,g,snakex[0],snakey[0]); } else if(fx == "U"){ up.paintIcon(this,g,snakex[0],snakey[0]); } else if(fx == "D"){ down.paintIcon(this,g,snakex[0],snakey[0]); } for(int i=1;i<len;i++){ body.paintIcon(this,g,snakex[i],snakey[i]); } //調用食物元素 food.paintIcon(this,g,foodx,foody); //遊戲開始的處理 if(isStart == false){ //設置畫筆顏色 g.setColor(Color.white); //設置字體 g.setFont(new Font("arial",Font.BOLD,40)); //設置具體文字 g.drawString("Press Space To Start",250,300); } //遊戲失敗的處理 if(isFailed){ //設置畫筆顏色 g.setColor(Color.red); //設置字體 g.setFont(new Font("arial",Font.BOLD,40)); //設置具體文字 g.drawString("Failed: Press Space To Start",250,300); } } //初始化數據 public void initSnake(){ len = 3; snakex[0] = 100; snakey[0] = 100; snakex[1] = 75; snakey[1] = 100; snakex[2] = 50; snakey[2] = 100; //設置食物的初始隨機生成位置 foodx = 25 + 25 * random.nextInt(34); foody = 75 + 25 * random.nextInt(24); //設置初始值 fx = "R"; score = 0; } //接口要求的實現方法 @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { //獲取鍵盤監聽 int keyCode = e.getKeyCode(); //空格 if(keyCode == KeyEvent.VK_SPACE){ //如果失敗則重置信息 if(isFailed){ isFailed = !isFailed; //重新開始 initSnake(); } //設置開始 else { isStart = !isStart; } //判斷開始後循環播放背景音樂 if(isStart){ bgm.loop(Clip.LOOP_CONTINUOUSLY); } //未開始和暫停則不播放背景音樂 else { bgm.stop(); } //重新繪圖 repaint(); } //右鍵處理並設置不能回頭 else if(keyCode == KeyEvent.VK_LEFT && fx != "R"){ fx = "L"; } //左鍵 else if(keyCode == KeyEvent.VK_RIGHT && fx != "L"){ fx = "R"; } //上鍵 else if(keyCode == KeyEvent.VK_UP && fx != "D"){ fx = "U"; } //下鍵 else if(keyCode == KeyEvent.VK_DOWN && fx != "U"){ fx = "D"; } } //接口要求的實現方法 @Override public void keyReleased(KeyEvent e) { } //事件監聽 @Override public void actionPerformed(ActionEvent e) { //開始且沒有失敗的情況 if(isStart && !isFailed){ //循環移動蛇身 for(int i=len-1;i>0;i--){ snakex[i]=snakex[i-1]; snakey[i]=snakey[i-1]; } //向右移動並判斷是否撞墻,撞墻則失敗 if(fx == "R"){ snakex[0]=snakex[0]+25; if(snakex[0]>825)isFailed=true; } //向左移動並判斷是否撞墻,撞墻則失敗 else if(fx == "L"){ snakex[0]=snakex[0]-25; if(snakex[0]<50)isFailed=true; } //向上移動並判斷是否撞墻,撞墻則失敗 else if(fx == "U"){ snakey[0]=snakey[0]-25; if(snakey[0]<100)isFailed=true; } //向下移動並判斷是否撞墻,撞墻則失敗 else if(fx == "D"){ snakey[0]=snakey[0]+25; if(snakey[0]>625)isFailed=true; } //吃到食物的判斷 if(snakex[0]==foodx&&snakey[0]==foody){ //身體加長,分加多,並且隨機生成新食物 len++; score += 10; foodx = 25 + 25 * random.nextInt(34); foody = 75 + 25 * random.nextInt(24); } //撞到自身的處理 for(int i=1;i<len;i++){ if(snakex[i]==snakex[0] && snakey[i]==snakey[0]){ isFailed = true; } } //重新繪圖 repaint(); } //事件刷新 timer.start(); } //加載背景音樂 public void loadBGM(){ try { //從類所在文件引入 bgm = AudioSystem.getClip(); InputStream is = this.getClass().getClassLoader().getResourceAsStream("com/company/sound/bgm.wav"); AudioInputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(is)); bgm.open(ais); //bgm.loop(Clip.LOOP_CONTINUOUSLY); } //相應的異常處理 catch (LineUnavailableException e) { e.printStackTrace(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //加載圖片 public void loadImages(){ InputStream is; try { //依次添加響應元素 is = getClass().getClassLoader().getResourceAsStream("com/company/img/title.jpg"); title = new ImageIcon(ImageIO.read(is)); is = getClass().getClassLoader().getResourceAsStream("com/company/img/body.png"); body = new ImageIcon(ImageIO.read(is)); is = getClass().getClassLoader().getResourceAsStream("com/company/img/up.png"); up = new ImageIcon(ImageIO.read(is)); is = getClass().getClassLoader().getResourceAsStream("com/company/img/down.png"); down = new ImageIcon(ImageIO.read(is)); is = getClass().getClassLoader().getResourceAsStream("com/company/img/left.png"); left = new ImageIcon(ImageIO.read(is)); is = getClass().getClassLoader().getResourceAsStream("com/company/img/right.png"); right = new ImageIcon(ImageIO.read(is)); is = getClass().getClassLoader().getResourceAsStream("com/company/img/food.png"); food = new ImageIcon(ImageIO.read(is)); } catch (IOException e) { e.printStackTrace(); } } }
四、效果
到此這篇關於Java實戰之貪吃蛇小遊戲(源碼+註釋)的文章就介紹到這瞭,更多相關java貪吃蛇小遊戲內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- None Found