贪吃蛇小游戏(Java)

需要游戏素材和jar包加

V:17347064818

Q:1784965341

1.初始化界面:

2.按下空格键游戏开始,同时音乐开始播放(再次按下游戏暂停,音乐暂停),小蛇开始移动,按键盘上下左右方向键控制小蛇的移动,每吃掉一个食物,小蛇身体会长一截,分数会加10分,长度加1,当小蛇咬到身体或超出上下左右游戏窗口边界时,弹出游戏结束提示,再次按下空格键游戏重新开始:

GamePanel画界面画蛇类:

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

//画界面画蛇
public class GamePanel extends JPanel implements ActionListener {
    //创建图片素材对象
    ImageIcon header = new ImageIcon("src\\images\\header.png");//头部标题
    ImageIcon body = new ImageIcon("src\\images\\body.png");//蛇的身体
    ImageIcon food = new ImageIcon("src\\images\\food.png");//蛇的食物
    ImageIcon up = new ImageIcon("src\\images\\up.png");//蛇的上头部
    ImageIcon down = new ImageIcon("src\\images\\down.png");//蛇的下头部
    ImageIcon left = new ImageIcon("src\\images\\left.png");//蛇的左头部
    ImageIcon right = new ImageIcon("src\\images\\right.png");//蛇的右头部

    int length;//蛇的长度
    int[] snakeX = new int[600];//蛇的X坐标
    int[] snakeY = new int[500];//蛇的Y坐标

    //蛇行驶的头部方向,上->up 下->down 左->left 右->right
    String fx = null;

    //游戏运行状态
    boolean isStart = false;

    //定时器
    Timer timer = new Timer(400,this);//控制蛇移动的速度

    //定义食物坐标及随机数来随机生成食物
    int foodX = 0;
    int foodY = 0;
    Random random = new Random();

    //死亡判断
    boolean isFail = false;

    //分数统计
    int score;

    //播放音乐
    MusicThread m = new MusicThread();

    //构造器调用初始化方法
    public GamePanel(){
        init();
        this.setFocusable(true);//获取焦点
        this.addKeyListener(listener);//添加键盘事件
        timer.start();//运行时间时蛇动起来
    }

    //初始化
    public void init(){
        length = 3;//初始化两截身体加一个头部
        fx = "right";//默认右边
        snakeX[0] = 100;snakeY[0] = 100;//头部坐标
        snakeX[1] = 75;snakeY[1] = 100;//第一个身体坐标
        snakeX[2] = 50;snakeY[2] = 100;//第二个身体坐标

        //初始化随机生成食物
        foodX = 25 + 25 * random.nextInt(34);//X轴边界850
        foodY = 75 + 25 * random.nextInt(24);//Y轴边界650

        score = 0;//初始化分数
    }

    @Override
    public void paintComponent(Graphics g) {//画板
        super.paintComponent(g);//清屏
        this.setBackground(Color.white);//设置背景颜色
        //绘制头部的广告栏
        header.paintIcon(this,g,25,11);
        //绘制游戏行动区域
        g.fillRect(25,75,850,600);

        //绘制蛇的头部
        if(fx.equals("up")){
            up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(fx.equals("down")){
            down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(fx.equals("left")){
            left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(fx.equals("right")){
            right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }

        //蛇的身体长度需减1,通过length来控制
        for(int i = 1; i < length; i++){
            body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }

        //画食物
        food.paintIcon(this,g,foodX,foodY);

        //画分数
        g.setColor(Color.blue);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度:"+(length-1),210,35);
        g.drawString("分数:"+score,210,55);

        //游戏提示是否开始
        if(isStart == false){
            g.setColor(Color.white);//文字颜色
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//文字字体
            g.drawString("按下空格键开始游戏",270,350);//输出文字及所在位置
        }

        //失败提醒
        if (isFail){
            g.setColor(Color.red);//文字颜色
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//文字字体
            g.drawString("游戏失败,按下空格键重新开始",220,330);//输出文字及所在位置
        }
    }

    //接收键盘按下事件
    KeyListener listener = new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if(keyCode == 32){//按下空格键
                if (isFail){//失败游戏重新开始
                    isFail = false;
                    init();//初始化游戏
                    m = new MusicThread();//重新播放音乐
                    m.start();
                }else{
                    isStart = !isStart;
                    if (isStart == true) {
                        m = new MusicThread();
                        m.start();
                    }
                    if (isStart == false) {
                        m.stop();
                    }
                }
                repaint();//刷新界面
            }
            //控制蛇的头部的走向
            if (fx.equals("up")){//向上移动时只能向左右移动
                if (keyCode == KeyEvent.VK_LEFT){
                    fx = "left";//向左
                }
                if (keyCode == KeyEvent.VK_RIGHT){
                    fx = "right";//向右
                }
            }
            if (fx.equals("down")){//向下移动时只能向左右移动
                if (keyCode == KeyEvent.VK_LEFT){
                    fx = "left";//向左
                }
                if (keyCode == KeyEvent.VK_RIGHT){
                    fx = "right";//向右
                }
            }
            if (fx.equals("left")){//向左移动时只能向上下移动
                if (keyCode == KeyEvent.VK_UP){
                    fx = "up";//向上
                }
                if (keyCode == KeyEvent.VK_DOWN){
                    fx = "down";//向下
                }
            }
            if (fx.equals("right")){//向右移动时只能向上下移动
                if (keyCode == KeyEvent.VK_UP){
                    fx = "up";//向上
                }
                if (keyCode == KeyEvent.VK_DOWN){
                    fx = "down";//向下
                }
            }
        }
    };

    //Timer时间事件,执行定时操作
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && isFail == false){//游戏开始状态,并且游戏没有失败
            for(int i = length-1; i > 0; i--){//蛇的身体往右移动
                snakeX[i] = snakeX[i - 1];//使其跟着头的坐标移动
                snakeY[i] = snakeY[i - 1];
            }
            //通过控制方向让蛇的头部移动
            //边界控制:上边界:75   下边界:650   左边界:25    右边界:850
            if (fx.equals("up")){//向上
                snakeY[0] -= 25;
                if(snakeY[0] < 75){//边界控制
                    isFail = true;//超过上边界游戏结束
                    m.stop();
                }
            }
            if (fx.equals("down")){//向下
                snakeY[0] += 25;
                if(snakeY[0] > 650){
                    isFail = true;//超过下边界游戏结束
                    m.stop();
                }
            }
            if (fx.equals("left")){//向左
                snakeX[0] -= 25;
                if (snakeX[0] < 25){
                    isFail = true;//超过左边界游戏结束
                    m.stop();
                }
            }
            if (fx.equals("right")){//向右
                snakeX[0] += 25;
                if (snakeX[0] > 850){
                    isFail = true;//超过右边界游戏结束
                    m.stop();
                }
            }

            //蛇的头碰到食物时身体长度加一
            if (snakeX[0] == foodX && snakeY[0] == foodY){
                length++;//长度加1
                score += 10;//分数加10
                //重新生成食物
                foodX = 25 + 25 * random.nextInt(34);//X轴边界850
                foodY = 75 + 25 * random.nextInt(24);//Y轴边界650
            }

            //结束判断
            for (int i = 1; i < length; i++){
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
                    isFail = true;//游戏结束
                    m.stop();
                }
            }

            repaint();//刷新界面
        }
        //timer.start();//让时间动起来
    }
}

 构建游戏主窗口和运行游戏类:

import javax.swing.*;

//游戏主类
public class StartGames {
    public static void main(String[] args) {
        //创建窗口对象
        JFrame frame = new JFrame("贪吃蛇");

        //设置窗口图标
        frame.setIconImage(new ImageIcon("src\\images/Icon.png").getImage());

        //设置窗口位置和大小
        frame.setBounds(500,150,900,720);
        //设置窗口大小不可变
        frame.setResizable(false);

        //将画界面画蛇的面板添加到窗口中
        frame.add(new GamePanel());

        //设置窗口可见
        frame.setVisible(true);
        //设置单击右上角的关闭按钮程序停止运行
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
//创建线程播放音乐
class MusicThread extends Thread{
    @Override
    public void run() {
        while(true){
            new Music("C:\\Users\\滕宇豪\\IdeaProjects\\贪吃蛇\\src\\Music\\music.mp3");//循环播放音乐
        }
    }
}

播放音乐类,也可以不需要,因为播放音乐类需要导入一个jar包:

import javazoom.jl.player.Player;
import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class Music {
    public Music(String music){
        try {
            BufferedInputStream musicPath = new BufferedInputStream(new FileInputStream(music));
            Player player = new Player(musicPath);
            player.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
很高兴回答你的问题。以下是一个简单的贪吃蛇小游戏JAVA代码实现: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SnakeGame extends JPanel implements ActionListener { private final int WIDTH = 300; private final int HEIGHT = 300; private final int DOT_SIZE = 10; private final int ALL_DOTS = 900; private final int RAND_POS = 29; private final int DELAY = 140; private int x[] = new int[ALL_DOTS]; private int y[] = new int[ALL_DOTS]; private int dots; private int apple_x; private int apple_y; private boolean leftDirection = false; private boolean rightDirection = true; private boolean upDirection = false; private boolean downDirection = false; private boolean inGame = true; private Timer timer; private Image ball; private Image apple; private Image head; public SnakeGame() { addKeyListener(new TAdapter()); setBackground(Color.black); setPreferredSize(new Dimension(WIDTH, HEIGHT)); ImageIcon iid = new ImageIcon(this.getClass().getResource("dot.png")); ball = iid.getImage(); ImageIcon iia = new ImageIcon(this.getClass().getResource("apple.png")); apple = iia.getImage(); ImageIcon iih = new ImageIcon(this.getClass().getResource("head.png")); head = iih.getImage(); initGame(); } public void initGame() { dots = 3; for (int z = ; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } locateApple(); timer = new Timer(DELAY, this); timer.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } public void doDrawing(Graphics g) { if (inGame) { g.drawImage(apple, apple_x, apple_y, this); for (int z = ; z < dots; z++) { if (z == ) { g.drawImage(head, x[z], y[z], this); } else { g.drawImage(ball, x[z], y[z], this); } } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } public void gameOver(Graphics g) { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2); } public void checkApple() { if ((x[] == apple_x) && (y[] == apple_y)) { dots++; locateApple(); } } public void move() { for (int z = dots; z > ; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } if (leftDirection) { x[] -= DOT_SIZE; } if (rightDirection) { x[] += DOT_SIZE; } if (upDirection) { y[] -= DOT_SIZE; } if (downDirection) { y[] += DOT_SIZE; } } public void checkCollision() { for (int z = dots; z > ; z--) { if ((z > 4) && (x[] == x[z]) && (y[] == y[z])) { inGame = false; } } if (y[] >= HEIGHT) { inGame = false; } if (y[] < ) { inGame = false; } if (x[] >= WIDTH) { inGame = false; } if (x[] < ) { inGame = false; } if (!inGame) { timer.stop(); } } public void locateApple() { int r = (int) (Math.random() * RAND_POS); apple_x = ((r * DOT_SIZE)); r = (int) (Math.random() * RAND_POS); apple_y = ((r * DOT_SIZE)); } public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } private class TAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) { rightDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_UP) && (!downDirection)) { upDirection = true; rightDirection = false; leftDirection = false; } if ((key == KeyEvent.VK_DOWN) && (!upDirection)) { downDirection = true; rightDirection = false; leftDirection = false; } } } } ``` 希望这个代码能够帮助到你。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T何必当初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值