Java实现简单的贪吃蛇小游戏

本文实例为大家分享了Java实现简单的贪吃蛇小游戏的具体代码,供大家参考,具体内容如下

1. 程序结构

程序结构图如图:

2. 程序设计思路

2.1 Data类

作用:连接statics文件夹,将静态资源包中的图片转化为图标 方便在面板上绘制。

实现:使用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类

作用:创建游戏窗口,在窗口中添加一个游戏面板。实现:使用JFrame类创建游戏窗口,利用其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);//设置窗体关闭事件        frame.add(new GamePanel());//添加游戏内容        frame.setVisible(true);//设置窗体可见    }}

2.3 GamePanel类

作用:实现游戏的动态页面。

实现:

(1)init()方法:初始化小蛇位置;(2)eat()方法:用随机种子随机食物的位置,并进行判定,食物位置不能和小蛇位置重合;(3)继承JPanel类,重写paintComponent(Graphics g)方法,在方法中绘制标题栏、小蛇的位置(根据direction小蛇头部方向变量绘制小蛇头部)、小蛇身体、积分栏、游戏提醒项与失败判断项;(4)实现KeyListener 接口中的keyPressed(KeyEvent e)方法,获取键盘输入,根据键盘输入对游戏状态或者小蛇头部方向direction变量进行更改;(5)实现ActionListener接口中的actionPerformed(ActionEvent e)方法,根据游戏状态和direction变量进行小蛇移动操作(注意禁用直接回头操作),进行吃食物判定和死亡判定。使用Timer计时器让游戏动态变化,用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;    //构造函数    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);//设置背景板为白色        //画标题        g.setColor(Color.GREEN);        g.setFont(new Font("幼圆",Font.BOLD,50));        g.drawString("贪吃蛇游戏",300,60);        //绘制游戏区域        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) {        //判断游戏状态        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. 游戏展示

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

却又小到连一粒嫉妒的沙石也不能容纳

Java实现简单的贪吃蛇小游戏

相关文章:

你感兴趣的文章:

标签云: