Java实现贪吃蛇

项目效果图:源代码:import java.awt.Color;import java.awt.Container;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Point;import ponentAdapter; import ponentEvent; import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent;import java.awt.event.MouseMotionAdapter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent;import java.awt.geom.Rectangle2D;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import java.util.*;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;/* author: 蒋冰*/public class KeyBoard extends JFrame{private int direction = 0;private int judge = 0;private Panel panel = new Panel();private RectLabel label[] = new RectLabel[1200];private HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();private ArrayList<RectLabel> list = new ArrayList<RectLabel>();private Point[] point = new Point[1200];private int targetX = 0;private int targetY = 0;private static int goal = 3;private int speed;private RectLabel targetLabel = new RectLabel();private static KeyBoard frame = new KeyBoard();public static void main(String[] args){frame.setVisible(true);}public KeyBoard(){super();addWindowListener(new WindowAdapter() {@Overridepublic void windowActivated(WindowEvent arg0) {map.put(KeyEvent.VK_RIGHT, KeyEvent.VK_LEFT);map.put(KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT);map.put(KeyEvent.VK_UP, KeyEvent.VK_DOWN);map.put(KeyEvent.VK_DOWN, KeyEvent.VK_UP);map.put(0, 0);map.put(KeyEvent.VK_G, 0);Random ra = new Random();targetX = ra.nextInt(30)*10 + 50;targetY = ra.nextInt(20)*10 + 50;targetLabel.setLocation(targetX, targetY);}});setBackground(Color.gray);setLayout(null);setBounds(400,200,400,300);addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e){if(e.getKeyCode() == map.get(direction)){return;}elsedirection = e.getKeyCode();}});for(int i=1; i<goal; i++){label[i] = new RectLabel();label[i].setBounds(-10,-10, 10, 10);list.add(label[i]);}panel.setBounds(-10, -10, 10, 10);panel.addComponentListener(new ComponentAdapter() {@Overridepublic void componentMoved(ComponentEvent arg0) {point[0] = panel.getLocation();if(Math.abs(point[0].x-targetX)<5&&Math.abs(point[0].y-targetY)<5){ Random ra = new Random();targetX = ra.nextInt(30)*10 + 50;targetY = ra.nextInt(20)*10 + 50;while(true){for(int i=1; i<goal-1; i++){Point p = label[i].getLocation();if((p.x==targetX)&&(p.y==targetY)){break;}else{judge ++;}}if(judge==goal-2){break;}else{judge=0;targetX = ra.nextInt(30)*10 + 50;targetY = ra.nextInt(20)*10 + 50;}}targetLabel.setLocation(targetX, targetY);label[goal] = new RectLabel();label[goal].setBounds(-10, -10, 10, 10);point[goal-1] = new Point();list.add(label[goal]);goal++;}for(int i=1; i<list.size(); i++){point[i] = label[i].getLocation();label[i].setLocation(point[i-1]);frame.add(label[i]);}label[list.size()].setLocation(point[list.size()-1]);frame.add(label[list.size()]);for(int i=3; i<list.size(); i++){if(Math.abs(label[1].getLocation().x-label[i].getLocation().x)<=1&&Math.abs(label[1].getLocation().y-label[i].getLocation().y)<=1){direction = KeyEvent.VK_G;}}}});targetLabel.setBounds(200, 100,10,10);add(targetLabel);add(panel);}class Panel extends JPanel implements Runnable{private int flag = 0;private int x = 0;private int y = 0;public Panel(){setPreferredSize(new Dimension(10, 10));new Thread(this).start();}@Overridepublic void run() {while(true){if(direction == KeyEvent.VK_RIGHT){if(x<=this.getParent().getWidth()-10){x+=10;setLocation(x,y);}else{direction = KeyEvent.VK_G;}}if(direction == KeyEvent.VK_G){JOptionPane.showMessageDialog(null, "您得了"+(goal-3)+"分,"+"欢迎再次光临!");System.exit(0);setLocation(-10,-10);}if(direction == KeyEvent.VK_LEFT){if(x>=0){x-=10;setLocation(x,y);}else{direction = KeyEvent.VK_G;}}if(direction == KeyEvent.VK_DOWN){if(y<=this.getParent().getHeight()-10){y+=10;setLocation(x,y);}else{direction = KeyEvent.VK_G;}}if(direction == KeyEvent.VK_UP){if(y>=0){y-=10;setLocation(x,y);}else{direction = KeyEvent.VK_G;}}try{if(goal<30){speed = goal;}else{speed = 30;}Thread.sleep(400 - speed*10);}catch(InterruptedException e){e.printStackTrace();}repaint();}}}class RectLabel extends JLabel{private int r = 5;// 小球半径private int width = r * 2;// 球宽度private int height = r * 2;// 球高度private Color ballColor = Color.BLUE;// 默认颜色public RectLabel() {setPreferredSize(new Dimension(width, height));// 初始化大小 }@Overrideprotected void paintComponent(Graphics g) {super.paintComponent(g);g.setColor(ballColor);// 设置默认颜色g.fillRect(0, 0, width, height);// 在标签上绘制球体}}}。

合集下载

java版的贪吃蛇毕业论文

java版的贪吃蛇毕业论文

j a v a版的贪吃蛇毕业论文Document serial number【UU89WT-UU98YT-UU8CB-UUUT-UUT108】贪吃蛇姓名:摘要:本文用J2SE实现大家耳熟能详的一个贪吃蛇游戏来综合运用所学知识,本游戏运用软件工程思想(螺旋模型),打好游戏主体框架,JAVA的面向对象思想,封装类,接口等概念,来完成本游戏,打到综合运用知识的目的。

⑴.本游戏开发平台:WINXP;⑵.JAVA开发环境: +Eclipse;⑶.开发语言:J2SE关键词:中央控制器;游戏面板;食物;蛇;石头The Greed SnakeAbstract: In this paper, J2SE implementation of a Snake game familiar to the integrated use of what they have learned, this game is the use of software engineering thinking (spiral model), the main framework of the fight game, JAVA object-oriented thinking, wrapper classes, interface concepts to complete this game, hitting the integrated use of knowledge and purpose.⑴. The game development platform: WINXP;⑵. JAVA Development Environment: + Eclipse;⑶. Development Languages: J2SEKeywords:Controller;GamePanel;Food;Snake;Ground前言贪吃蛇游戏背景:蛇引诱夏娃吃了苹果之后,就被贬为毒虫,阴险的象征。

java 贪吃蛇

java  贪吃蛇

◆GameFrame类:import java.awt.*;import java.awt.event.*;public class GameFrame {public GameFrame() {Frame app = new Frame("GameFrame");app.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});app.setLocation(100, 100);GamePanel drawB = new GamePanel();app.add(drawB, BorderLayout.CENTER);app.pack();app.setResizable(false);app.setVisible(true);drawB.gameStart();}public static void main(String[] args) {new GameFrame();}}◆GamePanel类:import java.awt.*;import java.awt.event.*;public class GamePanel extends Panel implements Runnable, KeyListener{public int width;public int heigth;private Image im;private Graphics dbg;private Thread gamethread;private static final int FPS =30;private boolean running = false;private boolean isPaused = false;private int direction;public static final int SOUTH = 0;public static final int NORTH = 1;public static final int EAST = 2;public static final int WEST = 3;private Snake sk; //建立贪吃蛇对象private Food bk; //建立食物对象public GamePanel() {width = 300;heigth = 300;setPreferredSize(new Dimension(width, heigth));sk = new Snake(this);bk = new Food(this, sk);setFocusable(true);requestFocus();addKeyListener(this);}public int getDirection() {return direction;}public void gameStart() {if (!running) {gamethread = new Thread(this);gamethread.start();}}public void gameStop() {running = false;}public void gamePaint() {Graphics g = this.getGraphics();g.drawImage(im, 0, 0, null);g.dispose();}public void gameRender() {}dbg.setColor(Color.white);dbg.fillRect(0, 0, width, heigth);sk.draw(dbg);//在后备缓冲区绘制贪吃蛇的图形bk.draw(dbg);//在后备缓冲区绘制食物的图形}public void gameUpdate() {sk.update();bk.update();}public void keyTyped(KeyEvent e) {}public void keyPressed(KeyEvent e) {int Keycode= e.getKeyCode();switch(Keycode){case KeyEvent.VK_DOWN:direction=SOUTH;break;case KeyEvent.VK_UP:direction=NORTH;break;case KeyEvent.VK_RIGHT:direction=EAST;break;case KeyEvent.VK_LEFT:direction=WEST;break;}public void keyReleased(KeyEvent e) {}public void run() {// TODO Auto-generated method stub// 请在此处将代码补充完整while(true){ public void run() {long t1,t2,dt,sleepTime;long period=1000/FPS; //计算每一次游戏循环需要的执行时间,单位毫秒t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒while(true){if(isPaused==false){gameUpdate();}//更新小球坐标gameRender(); //离屏绘制gamePaint(); //前屏显示t2= System.nanoTime() ;//游戏循环执行后的系统时间,单位纳秒dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒if(sleepTime<=0) //防止sleepTime值为负数sleepTime=2;try {Thread.sleep(sleepTime);//让线程休眠,由sleepTime值决定} catch(InterruptedException ex) { }t1 = System.nanoTime();//重新获取当前系统时间}}}Snake类:import java.awt.*;public class Snake {GamePanel gameP;private Point[] body;public static final int MAXLENTH = 20;private int head;private int tail;public int length;private int speed;public int x;public int y;public int diameter;public Snake(GamePanel gp) {gameP = gp;//通过构造方法的参数来获取GamePanel对象的引用body = new Point[MAXLENTH];head = -1;tail = -1;length = 1;speed = 10;x = 50;y = 50;diameter = 10;}//更新贪吃蛇坐标public void update() {int direction=gameP.getDirection();switch(direction){case GamePanel.SOUTH:y +=speed;break;case GamePanel.NORTH:y-=speed;break;case GamePanel.EAST:x+=speed;break;case GamePanel.WEST:x-=speed;}head = (head+1) % body.length;tail = (head + body.length - length + 1)%body.length;body[head] = new Point(x,y);}//绘制贪吃蛇图形public void draw(Graphics g) {g.setColor(Color.blue);if(length>1){int i=tail;while(i!=head){g.fillOval(body[i].x, body[i].y, diameter, diameter);i= (i+1)%body.length;}}g.setColor(Color.red);g.fillOval(body[head].x, body[head].y, diameter, diameter);}}Food类:import java.awt.*;public class Food {public Point location;public Point size;private GamePanel gameP;private Snake snk;private Random rand;public Food(GamePanel gp, Snake sk) {gameP = gp;//通过构造方法的参数来获取GamePanel对象的引用snk = sk;//通过构造方法的参数来获取Snake对象的引用rand = new Random();//位置随机出现location = newPoint(Math.abs(rand.nextInt()%gameP.width),Math.abs(rand.nextInt()%ga meP.heigth));size = new Point(sk.diameter, sk.diameter);}public void update() {//碰撞检测,判断贪吃蛇是否吃到食物if((snk.x-location.x)*(snk.x-location.x)+(snk.y-location.y)*(snk.y-location.y)<snk.diameter*snk.diameter){location = newPoint(Math.abs(rand.nextInt()%gameP.width),Math.abs(rand.nextInt()%ga meP.heigth));if (snk.length<Snake.MAXLENGTH){snk.length++;}}}//绘制食物图形public void draw(Graphics g) {g.setColor(Color.black);g.fillRect(location.x,location.y,size.x,size.y);}}。

java课程设计贪吃蛇小程序 附代码(2)

java课程设计贪吃蛇小程序 附代码(2)
}
public void keyPressed(KeyEvent e) {//按键响应
int keyCode=e.getKeyCode();
if(stat==1) switch(keyCode){
case KeyEvent.VK_UP:if(direction!=SOUTH) direction=NORTH;break;
游戏主界面模块:
游戏的主界面是进入游戏后,能够给玩家第一感官的部分,主要包括游戏图形区域界面、游戏的速度选择更新界面、新生方块的预览、游戏速度控制按钮、暂停游戏按钮、重新开始游戏按钮以及游戏排行榜按钮。从很大程度上决定了玩家对游戏的兴趣问题,因此,游戏的主界面应该力求美观,爽心悦目。
游戏控制模块:
这个模块是游戏的中心环节,主要完成控制游戏的速度、暂停、重新开始等功能。为了能够给玩家一个很好的游戏环境,这部分应该做到易懂、易操作。
本设计所开发的是基于Java的一个贪吃蛇游戏软件,主要实现游戏的速度控制、游戏的暂停、游戏的退出等功能,分为: 游戏主界面模块、游戏控制模块以二个模块。
性能:
本软件在设计方面本着方便、实用及娱乐性高的宗旨,在对界面进行设计的过程中,始终坚持清晰明了,在性能方面能够实现效率高,不易出错等优点。
自定义类说明
图3-1程序运行图
当蛇没有吃到食物且碰到边界或碰撞到自己的身体时,游戏结束,此时得分为0。如果想重新开始即按ENTER或S键,运行结果如图3-2所示:
图3-2程序结束图
程序异常处理
在蛇的运行线程过程中,当蛇撞到墙或自己的身体时,将抛出一个Exception类的异常对象,然后使用try-catch去捕捉这个异常,
2、课程设计的具体要求:
(1)界面美观大方,操作简单便捷,按键布局美观。

使用Java制作贪吃蛇游戏

使用Java制作贪吃蛇游戏
熟 悉 软 件 开 发 流程 的 目的 。
【 关键词】 J a v a ; E c l i p s e ; “ 贪吃 蛇” 游戏
近年来 . J a v a 作为一种新的编程语言 。 以其 简单性 、 可移植性 和平 i f ( g a me O v e r ) { 台无 关性等优点 . 得到 了广泛 地应用 . 特别是 J a v a与万维 网的完美结 la f g = f a l s e ; 合. 使其成 为网络 编程 和嵌入式编程领域 的首选编程语言 。 E c l i p s e 是 】 个 开放源代 码的 、 基于 J a y a 的可扩展开发平 台 . 同时它也是是著名 的跨平 台的 自由集 成开发环境 . 它 以其友 好的开发界 面、 强大 的组 件 支持等优点 . 得到广大程序员 的接受 和认可 。 J 贪吃蛇是 人们手 机中是一个很 常见 的一个 经典小游戏 . 人们对 它 } 并不陌生 . 在 紧张的现实生活 中给人们带来 了不少的乐趣 . 编写这个 通过在循环体 中设置每休眠 2 0 0毫秒则重画一次 界面 . 使 得界面 不断更新 . 当蛇移动时产生一个动画 的效果 。 贪吃蛇小游戏能让人 们在业余 时间里适 当的放松 . 保持好 的心态 。 在这个程序 中我采用 了 J a v a中 的图形 用户界面技术 .同时 引入 3 ) 绘 制 游 戏 界 面 了线 程来 编写。本次设计主要是对我之前所学 J a v a 知识 的一个巩 固 , p u b l i c v o i d p a i n t ( G r a p h i c s { 不仅 提高了我综合运 用以前 所学知识 的能力 . 同时也锻炼 了我 的实际 C o l o r c = g . g e t C o l o r 0 ; 动手 能力 整个游戏代码 简单易懂 . 用户在娱 乐的同时也可 以简单 的 g . s e t C o l o r ( C o l o r . c y a n ) ; 看一 下代码 . 有助 于初涉 J a v a者语 言水平 的提高。 g . i f l l R e c t ( O , 0 , RO WS B L OC K _ S I Z E, C O L S B L O C K _ S I Z E ) ; 贪吃蛇 的核心算法是如何实现移动和吃掉食 物 . 在当前运动方 向 g . s e t C o l o r ( C o l o r . b l a c k ) ; 上头指针所指的位置之前 添加一个节 点 , 然后删 除尾节 点 , 最后把链 f o r ( i n t i = l ; i < R O WS ; i + + ) { 表中的所有 节点依次 画出来 . 这样就可 以达 到移动的效果 。对是否吃 g . d r a w L i n e ( 0 , B L O C K _ S I Z E i , R O WS B L O C K _ S I Z E , OCK S 到食 物, 需要对 蛇和食物进行 碰撞检 测 . 检测 未碰撞 在一起则 只需要 BL I Z E* i ) ; 执行移 动操作 . 碰撞在一起时表示吃到食物 。 则 只需把食 物人队即可 , ) 即在 蛇的节 点链 表上再添加 一个节 点 , 从而达到身体增长 的效果 。 f o r ( i n t i = 1 ; i < C O L S ; i + + ) { 本次设计 的重 点之处在于 编程思想 的形 成 . 设计 图像 界面 . 产生 g . d r a w L i n e( i B L O C K _ S I Z E , 0 , B L O C K _ S I Z E i , C OL S 随机食 物及其 位置 。 难点在于程序编写中 , 整个程序框架的架构。 这就 BL OCK S I Z E ) ; 要求 我们不仅要对这个游戏 的玩 法特别 熟悉 . 而且还要熟 练掌握 J a v a } , , 每次重 画时 . 判 断蛇是否 吃到蛋 语言 。 实现贪 吃蛇的四个类模块 , 分别为游戏界 面 、 蛇、 食物和方 向。其 s . e a t ( e ) ; , 份 别 把 蛇 和 食 物 画 出来 具体设计 如下 :

JAVA贪吃蛇游戏设计文档

JAVA贪吃蛇游戏设计文档

《JA V A贪吃蛇游戏设计》目录《JA V A贪吃蛇游戏设计》 (1)目录 (1)摘要 (2)一.系统开发环境 (2)1.1 开发工具 (2)1.2 应用环境 (3)二.java介绍 (3)2.1java语言的特点 (3)2.2JA V A的主要特性 (4)2.3选题的意义 (5)2.4研究现状 (5)2.5研究目的 (6)三.系统需求分析 (6)3.1 需求分析 (6)3.2 可行性分析 (6)四.设计方案论证 (7)4.1设计思路 (7)4.2设计方法 (7)五.系统概要设计 (11)5.1 设计目标 (11)5.2 系统功能模块 (11)六.系统详细设计 (12)6.1 程序设计 (12)6.2 各功能界面截图 (15)七.系统测试 (20)7.1 测试的意义 (20)7.2 测试过程 (21)7.3 测试结果 (21)7.4设计体会 (21)7.5设计总结 (21)八.参考文献 (22)九.附录 (22)摘要近年来,Java作为一种新的编程语言,以其简单性、可移植性和平台无关性等优点,得到了广泛地应用,特别是Java与万维网的完美结合,使其成为网络编程和嵌入式编程领域的首选编程语言。

JBuilder是Borland公司用于快速开发Java应用的一款优秀的集成开发环境,它以其友好的开发界面、强大的组件支持等优点,得到广大程序员的接受和认可。

“贪吃蛇”游戏是一个经典的游戏,它因操作简单、娱乐性强而广受欢迎。

本文基于Java技术和JBuilder开发环境,开发了一个操作简单、界面美观、功能较齐全的“贪吃蛇”游戏。

整个游戏程序分为二个功能模块,六个类模块,实现了游戏的开始、暂停、结束。

通过本游戏的开发,达到学习Java技术和熟悉软件开发流程的目的。

本文在介绍Java相关技术和国内外发展现状的基础上,对“贪吃蛇”游戏的整个生命周期的各个开发阶段进行了详细地介绍。

首先,分析了开发本游戏软件的可行性,重点分析本设计所采用的技术的可行性。

java贪吃蛇毕业论文

java贪吃蛇毕业论文

java贪吃蛇毕业论文本文将介绍贪吃蛇游戏的设计与实现,该游戏的主要功能包括游戏开始、游戏暂停、游戏结束、得分统计等。

基于Java 语言,采用面向对象的程序设计方法,构建了具有良好交互性的贪吃蛇游戏系统。

一、引言贪吃蛇是一个经典的小游戏,它在全世界范围内都受到玩家们的喜欢。

贪吃蛇这个小游戏有着简单的规则和良好的互动性,因此成为了许多程序员学习编程的入门教材。

本文旨在通过对贪吃蛇游戏的设计和实现,加深对Java编程语言的理解,提升面向对象程序设计的能力。

本文将介绍贪吃蛇游戏的整体框架设计、游戏流程设计、源代码分析等内容,希望对同学们学习Java编程有所帮助。

二、贪吃蛇游戏的设计与实现2.1整体框架设计首先,我们来看一下贪吃蛇游戏的整体框架设计。

贪吃蛇游戏的界面分为左右两部分,左边显示游戏画面,右边显示得分情况。

游戏开始后,蛇会出现在游戏画面的中央位置,游戏画面上还会随机出现食物。

如果蛇吃到了食物,那么得分就会增加,同时蛇也会变长。

如果蛇撞到了游戏画面的边界或者自己的身体,则游戏失败,游戏画面会出现“Game over”的提示。

贪吃蛇游戏的设计可以分为两个模块:游戏画面显示模块和游戏逻辑实现模块。

其中,游戏画面显示模块是用来将游戏运行时的状态显示在界面上,游戏逻辑实现模块则是通过对用户的操作产生游戏效果。

2.2游戏流程设计当用户点击游戏开始按钮后,游戏画面会显示出蛇的头部,然后蛇会按照一定的规则向前移动。

此时,用户可以通过按键控制蛇的移动方向,蛇吃到食物时,得分会增加,同时蛇的长度增加。

如果蛇撞到了游戏画面的边界或自己的身体,则游戏失败,游戏画面会出现“Game over”的提示。

如果用户点击游戏暂停按钮,则游戏就会暂停,并且再次点击按钮游戏就会恢复进行。

2.3源代码分析以下是源代码的分析,采用了面向对象的编程方式,将游戏画面、蛇、食物等各个元素都抽象成了对象。

下面我们就来看一下其中的一部分代码。

(1)GamePanel.java```javapublic class GamePanel extends JPanel {private Snake snake;//蛇private Food food;//食物private int score;//分数private int speed;//移动速度private Timer timer;//计时器public GamePanel() {snake = new Snake();food = new Food();score = 0;speed = 200;timer = new Timer(speed, new ActionListener() { @Overridepublic void actionPerformed(ActionEvent e) { snake.move();//蛇移动check();//检查游戏是否结束或吃到食物repaint();//重新绘制}});timer.start();//开始计时器}public void paint(Graphics g) {super.paint(g);snake.draw(g);//绘制蛇food.draw(g);//绘制食物g.drawString(\。

JAVA小程序—贪吃蛇源代码

JAVA贪吃蛇源代码SnakeGame。

javapackage SnakeGame;import javax.swing。

*;public class SnakeGame{public static void main( String[]args ){JDialog。

setDefaultLookAndFeelDecorated( true ); GameFrame temp = new GameFrame();}}Snake.javapackage SnakeGame;import java。

awt.*;import java。

util。

*;class Snake extends LinkedList{public int snakeDirection = 2;public int snakeReDirection = 4;public Snake(){this。

add( new Point( 3, 3 ));this。

add(new Point(4, 3 ));this.add( new Point(5,3 ) );this。

add( new Point(6,3 ) );this。

add(new Point(7,3 ));this。

add( new Point( 8,3 ) );this。

add( new Point( 9, 3 ));this。

add( new Point( 10,3 ));}public void changeDirection( Point temp, int direction ) {this。

snakeDirection = direction;switch(direction ){case 1://upthis.snakeReDirection = 3;this。

add( new Point(temp.x,temp.y - 1 ));break;case 2://rightthis。

使用Java制作贪吃蛇游戏

近年来,Java作为一种新的编程语言,以其简单性、可移植性和平台无关性等优点,得到了广泛地应用,特别是Java与万维网的完美结合,使其成为网络编程和嵌入式编程领域的首选编程语言。

Eclipse是一个开放源代码的、基于Java的可扩展开发平台,同时它也是是著名的跨平台的自由集成开发环境,它以其友好的开发界面、强大的组件支持等优点,得到广大程序员的接受和认可。

贪吃蛇是人们手机中是一个很常见的一个经典小游戏,人们对它并不陌生,在紧张的现实生活中给人们带来了不少的乐趣,编写这个贪吃蛇小游戏能让人们在业余时间里适当的放松,保持好的心态。

在这个程序中我采用了Java中的图形用户界面技术,同时引入了线程来编写。

本次设计主要是对我之前所学Java知识的一个巩固,不仅提高了我综合运用以前所学知识的能力,同时也锻炼了我的实际动手能力。

整个游戏代码简单易懂,用户在娱乐的同时也可以简单的看一下代码,有助于初涉Java者语言水平的提高。

贪吃蛇的核心算法是如何实现移动和吃掉食物,在当前运动方向上头指针所指的位置之前添加一个节点,然后删除尾节点,最后把链表中的所有节点依次画出来,这样就可以达到移动的效果。

对是否吃到食物,需要对蛇和食物进行碰撞检测,检测未碰撞在一起则只需要执行移动操作,碰撞在一起时表示吃到食物,则只需把食物入队即可,即在蛇的节点链表上再添加一个节点,从而达到身体增长的效果。

本次设计的重点之处在于编程思想的形成,设计图像界面,产生随机食物及其位置。

难点在于程序编写中,整个程序框架的架构。

这就要求我们不仅要对这个游戏的玩法特别熟悉,而且还要熟练掌握Java 语言。

实现贪吃蛇的四个类模块,分别为游戏界面、蛇、食物和方向。

其具体设计如下:1产生游戏界面Yard.java包括界面的位置、大小的设定,绘制游戏界面,启动键盘监听器。

1)在launch()中添加代码:this.setBounds(200,200,COLS*BLOCK_SIZE,ROWS*BLOCK _SIZE);设定界面的位置、大小。

java贪吃蛇 代码

代码:一:::::::public class Cell {// 格子:食物或者蛇的节点private int x;private int y;private Color color;// 颜色public Cell() {}public Cell(int x, int y) {this.x = x;this.y = y;}public Cell(int x, int y, Color color) { this.color = color;this.x = x;this.y = y;}public Color getColor() {return color;}public int getX() {return x;}public int getY() {return y;}public String toString() {return"[" + x + "]" + "[" + y + "]";}}二::::::::::public class Worm {private int currentDirection;// 蛇包含的格子private Cell[] cells;private Color color;public static final int UP = 1;public static final int DOWN = -1;public static final int RIGHT = 2;public static final int LEFT = -2;// 创建对象创建默认的蛇:(0,0)(1,0)(2,0)······(11,0)public Worm() {// 构造器初始化对象color = Color.pink;// 蛇的颜色cells = new Cell[12];// 创建数组对象for (int x = 0, y = 0, i = 0; x < 12; x++) { // for(int y=0;;){}cells[i++] = new Cell(x, y, color);// 添加数组元素}currentDirection = DOWN;}public boolean contains(int x, int y) {// 数组迭代for (int i = 0; i < cells.length; i++) {Cell cell = cells[i];if (cell.getX() == x && cell.getY() == y) {return true;}}return false;}public String toString() {return Arrays.toString(cells);}public void creep() {for (int i = this.cells.length - 1; i >= 1; i--) {cells[i] = cells[i - 1];}cells[0] = createHead(currentDirection);}// 按照默认方法爬一步private Cell createHead(int direction) {// 根据方向,和当前(this)的头结点,创建新的头结点int x = cells[0].getX();int y = cells[0].getY();switch (direction) {case DOWN:y++;break;case UP:y--;break;case RIGHT:x++;break;case LEFT:x--;break;}return new Cell(x, y);}/*** food 食物**/public boolean creep(Cell food) {Cell head = createHead(currentDirection);boolean eat = head.getX() == food.getX() && head.getY() == food.getY();if (eat) {Cell[] ary = Arrays.copyOf(cells, cells.length + 1);cells = ary;// 丢弃原数组}for (int i = cells.length - 1; i >= 1; i--) { cells[i] = cells[i - 1];}cells[0] = head;return eat;}// 吃到东西就变长一格public boolean creep(int direction, Cell food) {if (currentDirection + direction == 0) {return false;}this.currentDirection = direction;Cell head = createHead(currentDirection);boolean eat = head.getX() == food.getX() && head.getY() == food.getY();if (eat) {Cell[] ary = Arrays.copyOf(cells, cells.length + 1);cells = ary;// 丢弃原数组}for (int i = cells.length - 1; i >= 1; i--) { cells[i] = cells[i - 1];}cells[0] = head;return eat;}// 检测在新的运动方向上是否能够碰到边界和自己(this 蛇)public boolean hit(int direction) {// 生成下个新头节点位置// 如果新头节点出界返回true,表示碰撞边界// ···············if (currentDirection + direction == 0) {return false;}Cell head = createHead(direction);if(head.getX() < 0 || head.getX() >= WormStage.COLS || head.getY() < 0|| head.getY() >= WormStage.ROWS) {return true;}for (int i = 0; i < cells.length - 1; i++) { if (cells[i].getX() == head.getX()&& cells[i].getY() == head.getY()) {return true;}}return false;}public boolean hit() {return hit(currentDirection);}// 为蛇添加会制方法// 利用来自舞台面板的画笔绘制蛇public void paint(Graphics g) {g.setColor(this.color);for (int i = 0; i < cells.length; i++) {Cell cell = cells[i];g.fill3DRect(cell.getX() * WormStage.CELL_SIZE, cell.getY()* WormStage.CELL_SIZE, WormStage.CELL_SIZE,WormStage.CELL_SIZE, true);}}}三:::::::::public class WormStage extends JPanel {/** 舞台的列数 */public static final int COLS = 35;/** 舞台的行数 */public static final int ROWS = 35;/** 舞台格子的大小 */public static final int CELL_SIZE = 10;private Worm worm;private Cell food;public WormStage() {worm = new Worm();food = createFood();}/*** 随机生成食物,要避开蛇的身体 1 生成随机数 x, y 2 检查蛇是否包含(x,y)* 3 如果包含(x,y) 返回 1 4 创建食物节点* */private Cell createFood() {Random random = new Random();int x, y;do {x = random.nextInt(COLS);// COLS列数y = random.nextInt(ROWS);// WOWS行数} while (worm.contains(x, y));return new Cell(x, y, Color.green);// 食物颜色/** 初始化的舞台单元测试 */public static void test() {WormStage stage = new WormStage();System.out.println(stage.worm);System.out.println(stage.food);}/*** 重写JPanel绘制方法paint:绘制,绘画,涂抹Graphics 绘图,* 理解为:绑定到当前面板的画笔*/public void paint(Graphics g) {// 添加自定义绘制!// 绘制背景g.setColor(Color.darkGray);// 背景色g.fillRect(0, 0, getWidth(), getHeight());g.setColor(Color.cyan);// 边框上的颜色// draw 绘制 Rect矩形g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);// 绘制食物g.setColor(food.getColor());// fill 填充 3D 3维 Rect矩形突起的立体按钮形状g.fill3DRect(food.getX() * CELL_SIZE, food.getY() * CELL_SIZE,CELL_SIZE, CELL_SIZE, true);// 绘制蛇worm.paint(g);// 让蛇自己去利用画笔绘制private Timer timer;/*** 启动定时器驱动蛇的运行 1 检查碰撞是否将要发生* 2 如果发生碰撞:创建新的蛇和食物,重写开始* 3 如果没有碰撞就爬行,并检查是否能够吃到食物* 4如果吃到食物:重新创建新的食物* 5 启动重新绘制界面功能 repaint() 更新界面显示效果! repaint()* 方法会尽快调用paint(g) 更新界面!*/private void go() {if (timer == null)timer = new Timer();timer.schedule(new TimerTask() {public void run() {if (worm.hit()) {// 如果蛇碰到边界或自己worm = new Worm();// 创建新的蛇food = createFood();// 创建新食物} else {// 如果没有碰到自己boolean eat = worm.creep(food);// 蛇向前(当前方向)爬行,返回结果表示是否吃到食物if(eat) {// 如果吃到食物,就生成新食物food = createFood();}}repaint();}}, 0, 1000 / 5);this.requestFocus();this.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {int key = e.getKeyCode();switch (key) {case KeyEvent.VK_UP:creepForFood(Worm.UP);break;case KeyEvent.VK_DOWN:creepForFood(Worm.DOWN);break;case KeyEvent.VK_LEFT:creepForFood(Worm.LEFT);break;case KeyEvent.VK_RIGHT:creepForFood(Worm.RIGHT);break;}}});}private void creepForFood(int direction) { if (worm.hit(direction)) {worm = new Worm();food = createFood();} else {boolean eat = worm.creep(direction, food);if (eat) {food = createFood();}}}/** 软件启动的入口方法 */public static void main(String[] args) {// 启动软件....JFrame frame = new JFrame("贪吃蛇");// 一个画框对象frame.setSize(450, 480);// size 大小,setSize 设置大小// frame.setLocation(100,50);//Locationq位置frame.setLocationRelativeTo(null);// 居中// 设置默认的关闭操作为在关闭时候离开软件frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);// Visible可见的设置可见性frame.setLayout(null);// 关闭默认布局管理,避免面板充满窗口WormStage stage = new WormStage();// System.out.println("CELL_SIZE * COLS:"+CELL_SIZE * COLS);stage.setSize(CELL_SIZE* COLS, CELL_SIZE* ROWS);stage.setLocation(40, 50);stage.setBorder(new LineBorder(Color.BLACK));frame.add(stage);// 在窗口添加舞台stage.go();// 启动定时器驱动蛇自动运行}}。

java课程设计-贪吃蛇代码

java课程设计-贪吃蛇代码importjava.awt.Color;importponent;importjava.awt.Graphic;importjava.awt.event.ActionEvent; importjava.awt.event.ActionLitener; importjava.awt.event.KeyEvent;importjava.awt.event.KeyLitener; importjava.util.ArrayLit;importjava某.wing.BorderFactory;importjava某.wing.JFrame;importjava某.wing.JLabel;importjava某.wing.JMenu;importjava某.wing.JMenuBar;importjava某.wing.JMenuItem;importjava某.wing.JPanel; publicclaSnakeGame{publictaticvoidmain(String[]arg){ SnakeFrameframe=newSnakeFrame();frame.etTitle("贪吃蛇");frame.etDefaultCloeOperation(JFrame.E某IT_ON_CLOSE);frame.etViible(true);}}//----------记录状态的线程claStatuRunnableimplementRunnable{publicStatuRunnable(Snakenake,JLabeltatuLabel,JLabelcoreLabe l){thi.tatuLabel=tatuLabel;thi.coreLabel=coreLabel;thi.nake=nake;}publicvoidrun(){Stringta="";Stringpe="";while(true){witch(nake.tatu){caeSnake.RUNNING:ta="Running";break;caeSnake.PAUSED:ta="Paued";break;caeSnake.GAMEOVER:ta="GameOver";break;}tatuLabel.etTe某t(ta); coreLabel.etTe某t(""+nake.core); try{Thread.leep(100);}catch(E某ceptione){}}}privateJLabelcoreLabel; privateJLabeltatuLabel; privateSnakenake;}//----------蛇运动以及记录分数的线程claSnakeRunnableimplementRunnable{ thi.nake=nake;}publicvoidrun(){while(true){try{nake.move();Thread.leep(nake.peed);}catch(E某ceptione){}}}privateSnakenake;}claSnake{booleaniRun;//---------是否运动中ArrayLit<Node>body;//-----蛇体Nodefood;//--------食物intderection;//--------方向intcore;inttatu;intpeed; publictaticfinalintSLOW=500; publictaticfinalintMID=300; publictaticfinalintFAST=100; publictaticfinalintRUNNING=1; publictaticfinalintPAUSED=2; publictaticfinalintGAMEOVER=3; publictaticfinalintLEFT=1; publictaticfinalintUP=2; publictaticfinalintRIGHT=3; publictaticfinalintDOWN=4; publicSnake(){peed=Snake.SLOW;core=0;iRun=fale;tatu=Snake.PAUSED;derection=Snake.RIGHT;body=newArrayLit<Nod e>();body.add(newNode(60,20));body.add(newNode(40,20));body.add(newNode(20,20));makeFood();}//------------判断食物是否被蛇吃掉//-------如果食物在蛇运行方向的正前方,并且与蛇头接触,则被吃掉privatebooleaniEaten(){Nodehead=body.get(0);if(derection==Snake.RIGHT&&(head.某+Node.W)==food.某&&head.y==food.y)returntrue;if(derection==Snake.LEFT&&(head.某-Node.W)==food.某&&head.y==food.y)returntrue;if(derection==Snake.UP&&head.某==food.某&&(head.y-Node.H)==food.y)returntrue;if(derection==Snake.DOWN&&head.某==food.某&&(head.y+Node.H)==food.y)returntrue;elereturnfale;}//----------是否碰撞privatebooleaniCollion(){Nodenode=body.get(0);//------------碰壁if(derection==Snake.RIGHT&&node.某==280) returntrue;if(derection==Snake.UP&&node.y==0) returntrue;if(derection==Snake.LEFT&&node.某==0) returntrue;if(derection==Snake.DOWN&&node.y==380) returntrue;//--------------蛇头碰到蛇身Nodetemp=null;inti=0;for(i=3;i<body.ize();i++){temp=body.get(i);if(temp.某==node.某&&temp.y==node.y) break;}if(i<body.ize())returntrue;elereturnfale;}//-------在随机的地方产生食物publicvoidmakeFood(){Nodenode=newNode(0,0); booleaniInBody=true;int某=0,y=0;int某=0,Y=0;inti=0;while(iInBody){某=(int)(Math.random()某15);y=(int)(Math.random()某20);某=某某Node.W;Y=y某Node.H;for(i=0;i<body.ize();i++){if(某==body.get(i).某&&Y==body.get(i).y)break; }if(i<body.ize())iInBody=true;eleiInBody=fale;}food=newNode(某,Y);}//---------改变运行方向publicvoidchangeDerection(intnewDer){if(derection%2!=newDer%2)//-------如果与原来方向相同或相反,则无法改变derection=newDer;}publicvoidmove(){if(iEaten()){//-----如果食物被吃掉body.add(0,food);//--------把食物当成蛇头成为新的蛇体core+=10;makeFood();//--------产生食物}eleif(iCollion())//---------如果碰壁或自身{iRun=fale;tatu=Snake.GAMEOVER;//-----结束}eleif(iRun){//----正常运行(不吃食物,不碰壁,不碰自身)Nodenode=body.get(0);int某=node.某;intY=node.y;//------------蛇头按运行方向前进一个单位witch(derection){cae1:某-=Node.W;break;cae2:Y-=Node.H;break;cae3:某+=Node.W;break;cae4:Y+=Node.H;break;}body.add(0,newNode(某,Y));//---------------去掉蛇尾body.remove(body.ize()-1);}}}//---------组成蛇身的单位,食物claNode{publictaticfinalintW=20;publictaticfinalintH=20;int某;inty;publicNode(int某,inty){thi.某=某;thi.y=y;}}//------画板claSnakePanele某tendJPanel{Snakenake;publicSnakePanel(Snakenake){thi.nake=nake;}Nodenode=null;for(inti=0;i<nake.body.ize();i++){//---黄绿间隔画蛇身if(i%2==0)g.etColor(Color.green);eleg.etColor(Color.yellow);node=nake.body.get(i);g.fillRect(node.某,node.y,node.H,某某某某某某某某某某某某某某某某某某某试用某某某某某某某某某某某某某某某某某某某某某}node=nake.food;node.W);//g.etColor(Color.blue);g.fillRect(node.某,node.y,node.H,node.W);}}claSnakeFramee某tendJFrame{privateJLabeltatuLabel;privateJLabelpeedLabel;privateJLabelcoreLabel;privateJPanelnakePanel;privateSnakenake;privateJMenuBarbar;JMenugameMenu;JMenuhelpMenu;JMenupeedMenu;JMenuItemnewItem;JMenuItempaueItem; JMenuItembeginItem; JMenuItemhelpItem; JMenuItemaboutItem;JMenuItemlowItem;JMenuItemmidItem;JMenuItemfatItem;publicSnakeFrame(){init();ActionLitenerl=newActionLitener(){ publicvoidactionPerformed(ActionEvente){ if(e.getSource()==paueItem)nake.iRun=fale;if(e.getSource()==beginItem)nake.iRun=true;if(e.getSource()==newItem){newGame();}//------------菜单控制运行速度if(e.getSource()==lowItem){ nake.peed=Snake.SLOW; peedLabel.etTe某t("Slow");}if(e.getSource()==midItem){ nake.peed=Snake.MID; peedLabel.etTe某t("Mid");}if(e.getSource()==fatItem){ nake.peed=Snake.FAST; peedLabel.etTe某t("Fat");}}};paueItem.addActionLitener(l); beginItem.addActionLitener(l);newItem.addActionLitener(l); aboutItem.addActionLitener(l);lowItem.addActionLitener(l);midItem.addActionLitener(l);fatItem.addActionLitener(l); addKeyLitener(newKeyLitener(){ publicvoidkeyPreed(KeyEvente){witch(e.getKeyCode()){//------------方向键改变蛇运行方向caeKeyEvent.VK_DOWN://nake.changeDerection(Snake.DOWN);break; caeKeyEvent.VK_UP://nake.changeDerection(Snake.UP);break; caeKeyEvent.VK_LEFT://nake.changeDerection(Snake.LEFT);break; caeKeyEvent.VK_RIGHT://nake.changeDerection(Snake.RIGHT);break; //空格键,游戏暂停或继续caeKeyEvent.VK_SPACE://if(nake.iRun==true){nake.iRun=fale;nake.tatu=Snake.PAUSED;break;}if(nake.iRun==fale){nake.iRun=true;nake.tatu=Snake.RUNNING;break; }}}publicvoidkeyReleaed(KeyEventk){ }publicvoidkeyTyped(KeyEventk){ }});}privatevoidinit(){peedLabel=newJLabel();nake=newSnake();etSize(380,460);etLayout(null);thi.etReizable(fale);bar=newJMenuBar();gameMenu=newJMenu("Game");newItem=newJMenuItem("NewGame");PaueItem=newJMenuItem("Paue");beginItem=newJMenuItem("Continue");gameMenu.add(paueItem);gameMenu.add(newItem);gameMenu.add(beginItem);helpMenu=newJMenu("Help");aboutItem= newJMenuItem("About");helpMenu.add(aboutItem);peedMenu=newJMenu("Speed");lowItem=newJMenuItem("Slow");fatItem=newJMenuItem("Fat");midItem=newJMenuItem("Middle");peedMenu.add(lowItem);peedMenu.add(midItem);peedMenu.add(fatItem);bar.add(gameMenu);bar.add(helpMenu);bar.add(peedMenu);etJMenuBar(bar);tatuLabel=newJLabel();coreLabel=newJLabel();nakePanel=newJPanel();nakePanel.etBound(0,0,300,400);nakePanel.etBorder(BorderFactory.createLineBorder(Color.dark Gray));add(nakePanel);tatuLabel.etBound(300,25,60,20);add(tatuLabel);coreLabel.etBound(300,20,60,20);add(coreLabel);JLabeltemp=newJLabel("状态");temp.etBound(310,5,60,20);add(temp);temp=newJLabel("速度");temp.etBound(310,105,60,20);add(temp);temp=newJLabel("分数");temp.etBound(310,55,60,20);add(temp);temp.etBound(310,155,60,20);add(temp);temp=newJLabel("14滕月"); temp.etBound(310,175,60,20);add(temp);peedLabel.etBound(310,75,60,20); add(peedLabel);}privatevoidnewGame(){thi.remove(nakePanel);thi.remove(tatuLabel);thi.remove(coreLabel); peedLabel.etTe某t("Slow"); tatuLabel=newJLabel();coreLabel=newJLabel();nakePanel=newJPanel();nake=newSnake();nakePanel=newSnakePanel(nake);nakePanel.etBound(0,0,300,400);nakePanel.etBorder(BorderFactory.createLineBorder(Color.dark Gray));Runnabler1=newSnakeRunnable(nake,nakePanel);Runnabler2=newStatuRunnable(nake,tatuLabel,coreLabel);Thread t1=newThread(r1);Threadt2=newThread(r2);t1.tart();t2.tart();add(nakePanel);tatuLabel.etBound(310,25,60,20);add(tatuLabel);coreLabel.etBound(310,125,60,20);add(coreLabel);}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档