java 贪吃蛇 源码+图片

本人也是个初学者,有什么不对的地方,请大佬指点!!!
一、涉及到的知识点如下:

  1. 循环,分支
  2. 方法的抽取
  3. 数组的使用
  4. 面向对象
  5. 继承,子类方法的重写
  6. 接口,接口的实现

二、游戏图形化界面编程----》GUI图形化界面编程
注意:GUI 已经被很少使用 主要是理解监听思维 帮助刚学java的同学提升兴趣。

GUI的组件:

  1. 窗口
  2. 弹窗
  3. 面板
  4. 文本框
  5. 列表框
  6. 按钮
  7. 交互的时间:监听事件(鼠标事件,键盘事件)

里面的代码 随着学习 随着使用 不必再去细扣每个代码是什么意思。

准备工作

在这里插入图片描述
新建俩个文件夹

  1. com.msb.game 我用来存放代码
  2. images 用来存放图片
    图片我会放在最后,有需要的小伙伴自行下载,下载不下来开启网页审查元素下载。

新建java文件
在这里插入图片描述

代码如下:

package com.msb.game;

import javax.swing.*;
import java.awt.*;
public class StartGame {
    public static void main(String[] args) {
        //创建一个窗体:
        JFrame jf = new JFrame();

        //给窗体设置一个标题:
        jf.setTitle("贪吃蛇 v0.1版本  by:十一");

        //获取屏幕宽高
        int height = Toolkit.getDefaultToolkit().getScreenSize().height;
        int wight = Toolkit.getDefaultToolkit().getScreenSize().width;

        //设置窗体弹出的坐标,对应的窗体的宽高:
        jf.setBounds(((wight-800)/2),((height-800)/2),800,800);

        //设置窗体不可调
        jf.setResizable(false);

        //关闭窗口的同时 程序必须随之关闭
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //创建面板:
        GamePanel gp= new GamePanel();

        //将面板放入窗体
        jf.add(gp);

        //默认的窗体是隐藏效果,必须将它显现
        jf.setVisible(true);
    }
}

注意下面代码
(“/images/body.png”); 必须为你存放图片的地址

package com.msb.game;

import javax.swing.*;
import java.net.URL;

//专门获取游戏中所涉及的图片
    /*
    *必须将图片封装成一个对象,才能操作对象 来使用图片
    * */
public class Images {
    //将图片的路径封装成一个对象
    public static URL bodyURL = Images.class.getResource("/images/body.png");
    //将图片封装成为程序中的一个对象:
    public static ImageIcon bodyImg = new ImageIcon(bodyURL);

    public static URL downURL = Images.class.getResource("/images/down.png");
    public static ImageIcon downImg = new ImageIcon(downURL);

    public static URL foodURL = Images.class.getResource("/images/food.png");
    public static ImageIcon foodImg = new ImageIcon(foodURL);

    public static URL leftURL = Images.class.getResource("/images/left.png");
    public static ImageIcon leftImg = new ImageIcon(leftURL);

    public static URL rightURL = Images.class.getResource("/images/right.png");
    public static ImageIcon rightImg = new ImageIcon(rightURL);

    public static URL upURL = Images.class.getResource("/images/up.png");
    public static ImageIcon upImg = new ImageIcon(upURL);

    public static URL headerURL = Images.class.getResource("/images/header.png");
    public static ImageIcon headerImg = new ImageIcon(headerURL);

}

package com.msb.game;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import javafx.scene.input.KeyCode;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;

/*
 * 继承JPanel 才具备面板功能
 * */
public class GamePanel extends JPanel {
    //定义俩个数组 一个专门存蛇的X轴坐标,一个专门存y轴坐标
    //蛇的长度:
    int length;
    //x轴
    int[] snakeX = new int[200];
    //y
    int[] snakeY = new int[200];
    //游戏状态  开始,暂停
    boolean isStart = false;//默认暂停
    //加入定时器
    Timer timer;
    //定义食物的坐标
    int foodX;
    int foodY;
    //积分
    int score;
    //判断小蛇是否死亡
    boolean isDie = false;//默认活着
    //定义蛇行走的方向:
    String direction;

    public void init() {
        //初始化蛇的长度:
        length = 3;
        //图片大小为25x25
        //初始化蛇头轴坐标:
        snakeX[0] = 175;
        snakeY[0] = 175;
        //初始化第一节身子坐标:
        snakeX[1] = 150;
        snakeY[1] = 175;
        //初始化第二节身子坐标:
        snakeX[2] = 125;
        snakeY[2] = 175;
        //初始化蛇头的方向:
        direction = "R";
        //食物初始的坐标
        foodX = 300;
        foodY = 200;
        //积分
        score = 0;
    }

    public GamePanel() {
        init();
        //将焦点定位在当前操作面板上
        this.setFocusable(true);
        //加入监听
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {//监听键盘按键的按下操作
                super.keyPressed(e);
                int keyCode = e.getKeyCode();
                //System.out.println(keyCode);  32
                if (keyCode == KeyEvent.VK_SPACE) {//监听空格
                    if (isDie) {
                        init();
                        isDie = false;
                    } else {
                        isStart = !isStart;
                    }
                    repaint();//重绘游戏
                } else if (keyCode == KeyEvent.VK_UP) {//上
                    direction = "U";
                } else if (keyCode == KeyEvent.VK_DOWN) {//下
                    direction = "D";
                } else if (keyCode == KeyEvent.VK_LEFT) {//左
                    direction = "L";
                } else if (keyCode == KeyEvent.VK_RIGHT) {//右
                    direction = "R";
                }
            }
        });
        //对定时器进行初始化操作
        timer = new Timer(100, new ActionListener() {

            /*
            ActionListener 是事件监听
               相当于每100ms监听一下你是否发生了一个动作
               将具体的动作放入actionPerformed
             */
            @Override
            public void actionPerformed(ActionEvent e) {
                //后一节走向前一节
                if (isStart && isDie == false) {//
                    //身子
                    for (int i = length - 1; i > 0; i--) {
                        snakeX[i] = snakeX[i - 1];
                        snakeY[i] = snakeY[i - 1];
                    }
                    if ("R".equals(direction)) {
                        snakeX[0] += 25;
                    } else if ("U".equals(direction)) {
                        snakeY[0] -= 25;
                    } else if ("D".equals(direction)) {
                        snakeY[0] += 25;
                    } else if ("L".equals(direction)) {
                        snakeX[0] -= 25;
                    }

                    //防止蛇超出边界:
                    if (snakeX[0] > 750) {
                        snakeX[0] = 25;
                    } else if (snakeY[0] < 100) {
                        snakeY[0] = 725;
                    } else if (snakeX[0] < 25) {
                        snakeX[0] = 750;
                    } else if (snakeY[0] > 725) {
                        snakeY[0] = 100;
                    }
                    //检测碰撞的动作:
                    if (snakeX[0] == foodX && snakeY[0] == foodY) {
                        //长度加+
                        length++;
                        //随机生存坐标
                        foodX = ((int) (Math.random() * 30) + 1) * 25;//[25,750]

                        foodY = (new Random().nextInt(26) + 4) * 25;//[100,750]
                        score += 10;
                    }
                    //死亡判断
                    for (int i = 1; i < length; i++) {
                        if (snakeX[i] == snakeX[0] && snakeY[i] == snakeY[0]) {
                            isDie = true;
                        }
                    }
                    repaint();


                }
            }
        });
        //定时器必须要启动
        timer.start();
    }

    /*
     * paintComponent这个方法比较特殊,这个方法属于图形版的main方法
     * 自动调用
     *
     * */
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        //自动填充背景颜色
        this.setBackground(new Color(200, 246, 243));
        //画头部图片
        //paintIcon 四个参数:this 指的是当前面板 g:知道是画笔 x,y 指的是对应坐标
//        Images.headerImg.paintIcon(this, g, 1, 2);
        //调画笔颜色
        g.setColor(new Color(0xE3FFF6));
        //画一个矩形
        g.fillRect(10, 70, 760, 685);

        //画蛇头
        if ("R".equals(direction)) {
            Images.rightImg.paintIcon(this, g, snakeX[0], snakeY[0]);
        } else if ("L".equals(direction)) {
            Images.leftImg.paintIcon(this, g, snakeX[0], snakeY[0]);
        } else if ("U".equals(direction)) {
            Images.upImg.paintIcon(this, g, snakeX[0], snakeY[0]);
        } else if ("D".equals(direction)) {
            Images.downImg.paintIcon(this, g, snakeX[0], snakeY[0]);
        }
//          Images.rightImg.paintIcon(this, g, snakeX[0], snakeY[0]);
//        //第一节身子
//        Images.bodyImg.paintIcon(this, g, snakeX[1], snakeY[1]);
//        //第二节身子
//        Images.bodyImg.paintIcon(this, g, snakeX[2], snakeY[2]);

        //身子
        for (int i = 1; i < length; i++) {
            Images.bodyImg.paintIcon(this, g, snakeX[i], snakeY[i]);
        }

        //游戏提示语
        if (isStart == false) {
            //画一个文字
            g.setColor(new Color(0xFF7373));
            //字体 字号 大小
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            //文字内容 出现的位置
            g.drawString("点击空格开始/暂停游戏", 200, 330);
        }

        Images.foodImg.paintIcon(this, g, foodX, foodY);
        g.setColor(new Color(255, 76, 76));
        g.setFont(new Font("微软雅黑", Font.BOLD, 40));
        g.drawString("积分" + ":" + score, 600, 40);

        if (isDie) {
            g.setColor(new Color(255, 76, 76));
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("小蛇死亡,按空格重新开始", 200, 330);
        }
    }
}

所需要的图片如下:
up
body
down
left
right
food
下载不下来开启网页审查元素下载。

  • 13
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

周粥粥ya

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

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

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

打赏作者

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

抵扣说明:

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

余额充值