Java實現(xiàn)簡單的貪吃蛇小游戲
本文實例為大家分享了Java實現(xiàn)簡單的貪吃蛇小游戲的具體代碼,供大家參考,具體內(nèi)容如下
1. 程序結(jié)構(gòu)程序結(jié)構(gòu)圖如圖:
2.1 Data類
作用:連接statics文件夾,將靜態(tài)資源包中的圖片轉(zhuǎn)化為圖標 方便在面板上繪制。
實現(xiàn):使用class.getResource(String path)方法。
代碼如下:
package com.snake;import javax.swing.*;import java.net.URL;public class Data { //貪吃蛇頭部 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 leftUrl = Data.class.getResource('/statics/left.png'); public static ImageIcon left = new ImageIcon(leftUrl); public static URL rightUrl = Data.class.getResource('/statics/right.png'); public static ImageIcon right = new ImageIcon(rightUrl); //貪食蛇身體 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);}
2.2 StartGame類
作用:創(chuàng)建游戲窗口,在窗口中添加一個游戲面板。實現(xiàn):使用JFrame類創(chuàng)建游戲窗口,利用其add()方法添加一個GamePanel類實例化對象。
代碼如下:
package com.snake;import javax.swing.*;import java.awt.*;public class StartGame { public static void main(String[] args){//建立游戲窗口JFrame frame = new JFrame('Java-貪吃蛇小游戲');//標題frame.setSize(900,720);//窗口大小frame.setLocationRelativeTo(null);//窗口顯示屏幕中間frame.setResizable(false);//固定窗口大小frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設(shè)置窗體關(guān)閉事件frame.add(new GamePanel());//添加游戲內(nèi)容frame.setVisible(true);//設(shè)置窗體可見 }}
2.3 GamePanel類
作用:實現(xiàn)游戲的動態(tài)頁面。
實現(xiàn):
(1)init()方法:初始化小蛇位置;(2)eat()方法:用隨機種子隨機食物的位置,并進行判定,食物位置不能和小蛇位置重合;(3)繼承JPanel類,重寫paintComponent(Graphics g)方法,在方法中繪制標題欄、小蛇的位置(根據(jù)direction小蛇頭部方向變量繪制小蛇頭部)、小蛇身體、積分欄、游戲提醒項與失敗判斷項;(4)實現(xiàn)KeyListener 接口中的keyPressed(KeyEvent e)方法,獲取鍵盤輸入,根據(jù)鍵盤輸入對游戲狀態(tài)或者小蛇頭部方向direction變量進行更改;(5)實現(xiàn)ActionListener接口中的actionPerformed(ActionEvent e)方法,根據(jù)游戲狀態(tài)和direction變量進行小蛇移動操作(注意禁用直接回頭操作),進行吃食物判定和死亡判定。使用Timer計時器讓游戲動態(tài)變化,用repaint()方法實時更新界面。
代碼如下:
package com.snake;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.util.Random;public class GamePanel extends JPanel implements KeyListener, ActionListener { int[] snakeX = new int[500];//貪吃蛇橫坐標 int[] snakeY = new int[500];//貪吃蛇縱坐標 int foodX;//食物橫坐標 int foodY;//食物蛇縱坐標 int length;//貪吃蛇的長度 String direction;//貪吃蛇頭方向 int score;//積分 Random r = new Random(); Timer timer = new Timer(100,this); boolean isStart; boolean isFail; //構(gòu)造函數(shù) public GamePanel(){init();this.setFocusable(true);this.addKeyListener(this);timer.start(); } private void init(){length=3;snakeX[0]=100;snakeY[0]=100;snakeX[1]=75;snakeY[1]=100;snakeX[2]=50;snakeY[2]=100;direction = 'R';eat(foodX,foodY);isStart = false;isFail = false;score = 0; } private void eat(int x,int y){x= 25 + 25*r.nextInt(34);y= 75 + 25*r.nextInt(24);for (int i = 0; i < length; i++) { if(snakeX[i]==x&&snakeY[i]==y){x = 25 + 25*r.nextInt(34);y = 75 + 25*r.nextInt(24); }}foodX = x;foodY = y; } protected void paintComponent(Graphics g) {super.paintComponent(g);this.setBackground(Color.white);//設(shè)置背景板為白色//畫標題g.setColor(Color.GREEN);g.setFont(new Font('幼圓',Font.BOLD,50));g.drawString('貪吃蛇游戲',300,60);//繪制游戲區(qū)域g.setColor(Color.GRAY);g.fillRect(25,75,850,600);//畫貪吃蛇頭部if(direction=='R'){ Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);}else if(direction=='L'){ Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);}if(direction=='U'){ Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);}else if(direction=='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]);}//畫食物Data.food.paintIcon(this,g,foodX,foodY);//繪制積分欄g.setColor(Color.BLACK);g.setFont(new Font('幼圓',Font.BOLD,20));g.drawString('長度:'+length,730,30);g.drawString('得分:'+score,730,60);//游戲開始提醒if(isStart==false){ g.setColor(Color.BLACK); 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('游戲失敗,按空格鍵重新開始',300,300);} } @Override public void keyPressed(KeyEvent e) {int keyCode = e.getKeyCode();//獲取按下的按鍵//判斷空格if(keyCode==KeyEvent.VK_SPACE){ if(isFail){isFail = false;init(); } else{isStart = !isStart; } repaint();}//判斷方向if(keyCode==KeyEvent.VK_LEFT&&direction!='R'){ direction = 'L';}else if(keyCode==KeyEvent.VK_RIGHT&&direction!='L'){ direction = 'R';}else if(keyCode==KeyEvent.VK_UP&&direction!='D'){ direction = 'U';}else if(keyCode==KeyEvent.VK_DOWN&&direction!='U'){ direction = 'D';} } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) {//判斷游戲狀態(tài)if(isStart&&!isFail){ //移動身體 for (int i = length-1; i > 0 ; i--) {snakeX[i] = snakeX[i-1];snakeY[i] = snakeY[i-1]; } //移動頭部 if(direction=='R'){snakeX[0] += 25;if(snakeX[0]>850){ snakeX[0] = 25;} } else if(direction=='L'){snakeX[0] -= 25;if(snakeX[0]<25){ snakeX[0] = 850;} } else if(direction=='U'){snakeY[0] -= 25;if(snakeY[0]<75){ snakeY[0] = 650;} } else if(direction=='D'){snakeY[0] += 25;if(snakeY[0]>650){ snakeY[0] = 75;} } //吃食物 if(snakeX[0]==foodX&&snakeY[0]==foodY){length++;score += 10;eat(foodX,foodY); } //死亡判定 for (int i = 1; i < length; i++) {if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){ isFail=true;} } repaint();}timer.start(); }}3. 游戲展示
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究2. 三個不常見的 HTML5 實用新特性簡介3. Angular獲取ngIf渲染的Dom元素示例4. php面向?qū)ο蟪绦蛟O(shè)計介紹5. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp6. 無線標記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. 使用.net core 自帶DI框架實現(xiàn)延遲加載功能8. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析9. php測試程序運行速度和頁面執(zhí)行速度的代碼10. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析
