Java實(shí)現(xiàn)簡(jiǎn)單的貪吃蛇小游戲
本文實(shí)例為大家分享了Java實(shí)現(xiàn)簡(jiǎn)單的貪吃蛇小游戲的具體代碼,供大家參考,具體內(nèi)容如下
1. 程序結(jié)構(gòu)程序結(jié)構(gòu)圖如圖:
2.1 Data類
作用:連接statics文件夾,將靜態(tài)資源包中的圖片轉(zhuǎn)化為圖標(biāo) 方便在面板上繪制。
實(shí)現(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)建游戲窗口,在窗口中添加一個(gè)游戲面板。實(shí)現(xiàn):使用JFrame類創(chuàng)建游戲窗口,利用其add()方法添加一個(gè)GamePanel類實(shí)例化對(duì)象。
代碼如下:
package com.snake;import javax.swing.*;import java.awt.*;public class StartGame { public static void main(String[] args){//建立游戲窗口JFrame frame = new JFrame('Java-貪吃蛇小游戲');//標(biāo)題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類
作用:實(shí)現(xiàn)游戲的動(dòng)態(tài)頁(yè)面。
實(shí)現(xiàn):
(1)init()方法:初始化小蛇位置;(2)eat()方法:用隨機(jī)種子隨機(jī)食物的位置,并進(jìn)行判定,食物位置不能和小蛇位置重合;(3)繼承JPanel類,重寫paintComponent(Graphics g)方法,在方法中繪制標(biāo)題欄、小蛇的位置(根據(jù)direction小蛇頭部方向變量繪制小蛇頭部)、小蛇身體、積分欄、游戲提醒項(xiàng)與失敗判斷項(xiàng);(4)實(shí)現(xiàn)KeyListener 接口中的keyPressed(KeyEvent e)方法,獲取鍵盤輸入,根據(jù)鍵盤輸入對(duì)游戲狀態(tài)或者小蛇頭部方向direction變量進(jìn)行更改;(5)實(shí)現(xiàn)ActionListener接口中的actionPerformed(ActionEvent e)方法,根據(jù)游戲狀態(tài)和direction變量進(jìn)行小蛇移動(dòng)操作(注意禁用直接回頭操作),進(jìn)行吃食物判定和死亡判定。使用Timer計(jì)時(shí)器讓游戲動(dòng)態(tài)變化,用repaint()方法實(shí)時(shí)更新界面。
代碼如下:
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];//貪吃蛇橫坐標(biāo) int[] snakeY = new int[500];//貪吃蛇縱坐標(biāo) int foodX;//食物橫坐標(biāo) int foodY;//食物蛇縱坐標(biāo) int length;//貪吃蛇的長(zhǎng)度 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è)置背景板為白色//畫標(biāo)題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('長(zhǎng)度:'+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){ //移動(dòng)身體 for (int i = length-1; i > 0 ; i--) {snakeX[i] = snakeX[i-1];snakeY[i] = snakeY[i-1]; } //移動(dòng)頭部 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. 游戲展示
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python uuid生成唯一id或str的最簡(jiǎn)單案例2. 如何用python開發(fā)Zeroc Ice應(yīng)用3. python 根據(jù)列表批量下載網(wǎng)易云音樂的免費(fèi)音樂4. python+requests+pytest接口自動(dòng)化的實(shí)現(xiàn)示例5. python用pyecharts實(shí)現(xiàn)地圖數(shù)據(jù)可視化6. ASP編碼必備的8條原則7. python軟件測(cè)試Jmeter性能測(cè)試JDBC Request(結(jié)合數(shù)據(jù)庫(kù))的使用詳解8. npm下載慢或下載失敗問題解決的三種方法9. ASP錯(cuò)誤捕獲的幾種常規(guī)處理方式10. 五分鐘學(xué)會(huì)怎么用python做一個(gè)簡(jiǎn)單的貪吃蛇
