java贪吃蛇小游戏(详解+源码)

Java实战开发小游戏——(贪吃蛇)附源码下载 项目:贪吃蛇小游戏 目录 描述: 实现步骤: 效果图 源码下载:地址链接:https://pan.baidu.com/s/1JQESGI4GaZb3p5EqikrUhQ提取码:gzlp 描述: 用java开发,使用jdk1.8,使用eclipse开发 用到JFrame、Panel、画笔、Timer、数组...... 可以实现移动 自由转向、吃食物、幸运蛋、开始结束... 阅读详情

目录

1.实现效果:

​​2.游戏玩法

3.需求分析

4.代码实现

1.实现效果:

源码可以加微信领取哦,或者加群862461829自取

群只是作为一个学习交流的作用,还有一些资源分享

【群里还含有:Java80g学习视频+Java学习书籍+Java项目实战源码+安装软件等】

微信:

2.游戏玩法


该游戏用上下左右控制蛇的方向,寻找吃的东西,每吃一口就能得到一定的积分,而且蛇的身子会越吃越长,身子越长玩的难度就越大,不能碰墙,不能咬到自己的身体,更不能咬自己的尾巴,等到了一定的分数,就能过关,然后继续玩下一关。这次我们以一关的实现为例,关卡控制交给读者自行添加。

3.需求分析


方向控制


首先我们需要实现的是通过按键实现控制蛇的运动方向,需要注意的有两点:

1.蛇运动的时候不能向上一个状态的反方向运动,例如,原先向右,下一次改变的方向不能为左。

2.运动的时候如果按了一个方向键,再下一次按键之前将维持原先的方向运动。

2.如果蛇头和身体的图片不一样,那么蛇头要随着运动方向进行旋转。

蛇的绘制


蛇我这里分为了蛇头和蛇身两部分,当然你也可以加蛇尾。这里以蛇头和蛇身两部分为例: 

蛇头游戏开始就已经存在,之后吃到一个食物都会使蛇身长度加一。蛇身的每一部分都会沿着它的前一部分的轨迹运动,而每一部分都会沿着蛇头的轨迹运动。

食物绘制


食物绘制相对比较简单,当一个食物被吃掉以后,便在地图的其他随机的一个地方产生下一个食物。

蛇和食物的生命周期
蛇:当蛇碰到地图边界,碰到自己的身体和尾巴的时候,即判定为死亡。

食物:当蛇头碰到食物,则食物死亡。

4.代码实现


项目目录


Constant类,存储一些常量。

public class Constant {
    public static final int GAME_WIDTH = 1024;//窗体宽度
    public static final int GAME_HEIGHT = 578;//窗体高度
    
    public static final String IMG_PRE="com/zzk/snake/img/";//图片路径前缀
}


MyFrame类,用于加载游戏窗体和不断刷新绘制窗体内容:

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
 
import com.zzk.snake.constant.Constant;
 
public class MyFrame extends Frame{
    /**
     * 加载窗体
     */
    public void loadFrame(){
        this.setTitle("贪吃蛇");//设置窗体标题
        this.setSize(Constant.GAME_WIDTH, Constant.GAME_HEIGHT);//设置窗体大小
        this.setBackground(Color.BLACK);//设置背景
        this.setLocationRelativeTo(null);//居中
        //设置可关闭
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        //设置可见
        this.setVisible(true);
        //运行重绘线程
        new MyThread().start();
    }
    /**
     * 防止图片闪烁,使用双重缓存
     * 
     * @param g
     */
    Image backImg = null;
 
    @Override
    public void update(Graphics g) {
        if (backImg == null) {
            backImg = createImage(Constant.GAME_WIDTH, Constant.GAME_HEIGHT);
        }
        Graphics backg = backImg.getGraphics();
        Color c = backg.getColor();
        backg.setColor(Color.BLACK);
        backg.fillRect(0, 0, Constant.GAME_WIDTH, Constant.GAME_HEIGHT);
        backg.setColor(c);
        paint(backg);        
        g.drawImage(backImg, 0, 0, null);
    }
    /**
     * 这里创建一个不断重绘的线程内部类
     * 
     * @param args
     */
   &nb
基于Java的贪吃蛇小游戏 基于Java的贪吃蛇小游戏制作 阅读详情

相关推荐

Java经典小游戏——贪吃蛇简单实现(附源码)

在我们学习java的时候,为了提高我们的兴趣,我们经常会使用所学到的知识去做一些小游戏,这篇blog就介绍了一个经典而且好理解的小游戏-贪吃蛇。 文章目录一、使用知识二、使用工具三、开发过程3.1素材准备3.2 开发过程3.2.1 创建项目3.2.2 页面设计3.23 画蛇 一、使用知识 Jframe GUI 双向链表 线程 二、使用工具 IntelliJ IDEA jdk 1.8 三、开发过程 3.1素材准备 首先在开发之前应该准备一些素材,已备用,我主要找了一个图片以及一段优雅的音乐。 3.2

swyee的博客 4万+

java实现贪吃蛇游戏(附完整源码)

java实现贪吃蛇游戏(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 958

java双人贪吃蛇小游戏源码及设计思路

贪吃蛇是java学习的常用案例。本项目分享java双人贪吃蛇小游戏源码及设计思路,游戏实现java图形化界面控制,增加游戏趣味性。通过代码学习,掌握java图形界面AWT和Swing等相关知识。

haryjiang42的博客 1121

lammps建模(电解液)opls-aa力场的基本流程

lammps建模(电解液)opls-aa力场的基本流程

syj0922的博客 2133

告别简陋行情!在Ubuntu24.04系统用Wine9.0跑同花顺远航版的全流程记录

本文详细记录了在Ubuntu 24.04系统上,通过Wine 9.0兼容层成功安装并流畅运行同花顺远航版的全过程。文章对比了该方案与官方简陋Linux原生版本的功能差异,重点解决了高分辨率屏幕下的字体与界面显示问题,并提供了关键配置调优与长期维护建议,为Linux用户提供了功能完备的专业金融行情解决方案。

weixin_29207533的博客 1072

RocketMQ 为什么要自己做一个 NameServer ?RocketMQ 5.x 版本中的 proxy、controller 和 container 分别有什么用 ?

1.独立运行的分散结构 2.简化实现,容忍部分数据不一致 Proxy:多语言支持、简化开发 Controller: 提高 Broker 的性能 Container:提高资源利用率,平衡负载

xaiobit_hl的博客 1488

ROS2+PYTHON VENV虚拟环境配置方法

ROS2+PYTHON VENV配置方法本篇针对的是python。

下雨夏云的博客 555

linux内核学习(八)---摄像头框架移植(上)

本章来开始进行摄像头的移植,同时回顾一下V4L2的整个框架

文艺小少年的博客 113

RAG系统中Reranker模型选型实战

本文详细介绍了RAG系统中Reranker模型选型实战,希望能对学习RAG的同学们有所帮助。 文章目录 1. 前言 2. 思路解析 3. 测评数据集构建 3.1 步骤一 3.2 步骤二 3.3 数据示例 3.4 总结 4. 实战代码 4.1 本地模型 4.2 使用第三方的Reranker模型API

herosunly的博客 17万+

ABAP CDS Time Functions 全面解析:用 TIMS_IS_VALID 护航时刻字段的正确性

摘要:本文深入解析ABAP CDS时间函数TIMS_IS_VALID的应用,重点介绍其在企业系统时间字段校验中的关键作用。文章指出无效时间数据会导致业务流程混乱,而CDS层校验能有效减少重复逻辑。详细说明TIMS类型格式要求、空值处理规则,并提供两种工程实现方案:在CDS视图中直接派生校验列,或通过ABAP SQL在内存表中批量验证。最后给出可直接运行的代码示例,包括一个ABAP报表演示内存表验证,以及一个CDS View Entity实现系统时间自动映射与校验,帮助开发者在业务场景中快速落地时间校验功能。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 193

ARM Linux工控板+C# .NET Core:倍福ADS协议轻量化工业控制(附跨平台部署代码)

某自动化设备厂的倍福PLC控制系统曾依赖传统x86工控机:单台设备需配备1台Intel i5工控机(成本约8000元),功耗30W+,且Windows系统稳定性受工业环境干扰(如电磁辐射导致蓝屏)。更棘手的是,设备需部署在产线边缘(空间狭小),x86工控机的体积(4U机架)和散热需求(风扇噪音)难以适配;而多设备部署时,高硬件成本和高功耗导致年运维成本超20万元。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 954

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

上一篇: java实现简单的学生信息管理系统
下一篇: 从 Netflix 到 Spring Cloud差距有多少?
人工智能码农
博客等级 码龄5年 611粉丝 37原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值