java课程设计贪吃蛇小程序 附代码(2)
用Java做的贪吃蛇,简单版......

⽤Java做的贪吃蛇,简单版......效果图⽚::话不多说,上代码:⼀共三个类:①public class Body {int x;int y;public Body(int x, int y) {this.x = x;this.y = y;}}②import java.awt.Color;import java.awt.Graphics;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.Random;import javax.swing.JFrame;public class BallThread extends JFrame {/****/private static final long serialVersionUID = 1L;private static int RedX = 120; // ⼩球初始位置private static int RedY = 120;private Color color = Color.RED; // ⼩球初始颜⾊private Thread run;private String direction;private Body[] body = new Body[100];int body_length = 1;int randomx = 40, randomy = 40;private boolean pause = false;// 有参构造⽅法public BallThread() {// 实例化数组for (int i = 0; i < 100; i++) {body[i] = new Body(0, 0);}body[0].x = RedX;body[0].y = RedY;setSize(400, 400); // 设置⼤⼩setLocationRelativeTo(null);setTitle("贪吃球");setResizable(false);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent e) {System.out.println("到这来.........");super.keyPressed(e);// System.out.println(e.getKeyCode());if (e.getKeyCode() == KeyEvent.VK_LEFT) { direction = "L";}if (e.getKeyCode() == KeyEvent.VK_RIGHT) { direction = "R";}if (e.getKeyCode() == KeyEvent.VK_UP) {direction = "U";}if (e.getKeyCode() == KeyEvent.VK_DOWN) { direction = "D";}if (e.getKeyCode() == KeyEvent.VK_SPACE) {if (pause == false) {pause = true;} else {pause = false;}}}});}public void paint(Graphics g) {// 必须传递给⽗类super.paint(g);// System.out.println("运⾏到这来");// 画⽹格// g.drawLine(500, 500, 600, 400);g.clipRect(1, 1, 400, 400);// 1.画⽅格// 竖线for (int i = 1; i < 500; i = i + 20) {g.setColor(Color.BLACK);g.drawLine(i, 1, i, i + 400);// 填充g.setColor(Color.GREEN);// 画横墙g.fill3DRect(i + 1, 20 + 1, 20, 20, true);g.fill3DRect(i + 1, 380 + 1, 20, 20, true);}// 横线for (int i = 1; i < 500; i = i + 20) {g.setColor(Color.BLACK);g.drawLine(1, i, i + 400, i);// 填充g.setColor(Color.green);g.fill3DRect(1, i + 1, 20, 20, true);g.fill3DRect(382, i + 1, 20, 20, true);}// 画颜⾊圈g.setColor(Color.blue);g.drawRoundRect(20, 40, 20, 20, 20, 20);g.setColor(Color.RED);g.drawRoundRect(80, 120, 20, 20, 20, 20);g.setColor(Color.PINK);g.drawRoundRect(220, 220, 20, 20, 20, 20);if (isEated()) {produceFood();g.setColor(Color.yellow);g.fillRect(randomx, randomy, 20, 20);} else {g.setColor(Color.yellow);g.fillRect(randomx, randomy, 20, 20);}// ⼩球g.setColor(color); // 颜⾊g.drawRoundRect(RedX, RedY, 20, 20, 20, 20);g.fillRoundRect(RedX, RedY, 20, 20, 20, 20);body[0].x = RedX;body[0].y = RedY;for (int i = 1; i < body_length; i++) {System.out.println("⾝体显⽰了");System.out.println("X==" + body[i].x + " Y======" + body[i].y);g.setColor(Color.BLACK);g.drawRect(body[i].x, body[i].y, 20, 20);g.fillRect(body[i].x, body[i].y, 20, 20);}g.setColor(color); // 颜⾊g.drawRoundRect(RedX, RedY, 20, 20, 20, 20);g.fillRoundRect(RedX, RedY, 20, 20, 20, 20);}// 消除闪烁(下⾯这两⾏代码可写可不写,因为还没实现解决闪烁这个问题,有兴趣的可以⾃⼰解决闪烁问题)public void update(Graphics g) {paint(g);}private boolean isEated() {// TODO Auto-generated method stubif (RedX == randomx && RedY == randomy) {return true;} else {return false;}}// ⼩球移动public void move() {System.out.println(body.length);long millis = 600; // 每隔300毫秒刷新⼀次run = new Thread() {public void run() {while (true) {try {System.out.println("public void Thread:" + Thread.currentThread().getName());Thread.sleep(millis);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (!pause) {// 移动if (direction == "L") {if (RedX >= 40)RedX -= 20;}if (direction == "R") {if (RedX <= 340)RedX += 20;}if (direction == "U") {if (RedY >= 60)RedY -= 20;}if (direction == "D") {if (RedY <= 340)RedY += 20;}System.out.println("body_length====" + body_length);if (RedX == randomx && RedY == randomy) {body_length++;body[body_length - 1].x = randomx;body[body_length - 1].y = randomy;System.out.println("body[body_length-1].x" + body[body_length - 1].x); System.out.println(body[body_length - 1].y);}// ⾝体刷新for (int i = body_length - 1; i > 0; i--) {body[i].x = body[i - 1].x;body[i].y = body[i - 1].y;}// 给球头换颜⾊if (RedY == 40 && RedX == 20) {color = Color.blue;}if (RedX == 80 && RedY == 120) {color = Color.RED;}if (RedY == 220 && RedX == 220) {color = Color.PINK;}repaint();}}}};run.start();}// ⽣产⾷物public void produceFood() {boolean flag = true;Random r = new Random();randomx = (r.nextInt(18) + 1) * 20;randomy = (r.nextInt(17) + 2) * 20;while (flag) {for (int i = 0; i < body_length; i++) {if (body[i].x == randomx && body[i].y == randomy) {// 如果⽣产的⾷物在球⾝上,那么就重新⽣产randomx = (r.nextInt(18) + 1) * 20;randomy = (r.nextInt(17) + 2) * 20;flag = true;break;} else {if (i == body_length - 1) {flag = false;}}}}}}③public class BallMove {public static void main(String[] args) {BallThread Ball = new BallThread();Ball.move();}}如果你有其他想法或建议,写下来:我们⼀块讨论啊。
贪吃蛇JAVA源代码完整版

游戏贪吃蛇的JAVA源代码一.文档说明a)本代码主要功能为实现贪吃蛇游戏,GUI界面做到尽量简洁和原游戏相仿。
目前版本包含计分,统计最高分,长度自动缩短计时功能。
b)本代码受计算机系大神指点,经许可后发布如下,向Java_online网致敬c)运行时请把.java文件放入default package 即可运行。
二.运行截图a)文件位置b)进入游戏c)游戏进行中三.JAVA代码import java.awt.*;import java.awt.event.*;import static ng.String.format;import java.util.*;import java.util.List;import javax.swing.*;public class Snake extends JPanel implements Runnable { enum Dir {up(0, -1), right(1, 0), down(0, 1), left(-1, 0);Dir(int x, int y) {this.x = x; this.y = y;}final int x, y;}static final Random rand = new Random();static final int WALL = -1;static final int MAX_ENERGY = 1500;volatile boolean gameOver = true;Thread gameThread;int score, hiScore;int nRows = 44;int nCols = 64;Dir dir;int energy;int[][] grid;List<Point> snake, treats;Font smallFont;public Snake() {setPreferredSize(new Dimension(640, 440));setBackground(Color.white);setFont(new Font("SansSerif", Font.BOLD, 48));setFocusable(true);smallFont = getFont().deriveFont(Font.BOLD, 18);initGrid();addMouseListener(new MouseAdapter() {@Overridepublic void mousePressed(MouseEvent e) {if (gameOver) {startNewGame();repaint();}}});addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:if (dir != Dir.down)dir = Dir.up;break;case KeyEvent.VK_LEFT:if (dir != Dir.right)dir = Dir.left;break;case KeyEvent.VK_RIGHT:if (dir != Dir.left)dir = Dir.right;break;case KeyEvent.VK_DOWN:if (dir != Dir.up)dir = Dir.down;break;}repaint();}});}void startNewGame() {gameOver = false;stop();initGrid();treats = new LinkedList<>();dir = Dir.left;energy = MAX_ENERGY;if (score > hiScore)hiScore = score;score = 0;snake = new ArrayList<>();for (int x = 0; x < 7; x++)snake.add(new Point(nCols / 2 + x, nRows / 2));doaddTreat();while(treats.isEmpty());(gameThread = new Thread(this)).start();}void stop() {if (gameThread != null) {Thread tmp = gameThread;gameThread = null;tmp.interrupt();}}void initGrid() {grid = new int[nRows][nCols];for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)grid[r][c] = WALL;}}}@Overridepublic void run() {while (Thread.currentThread() == gameThread) {try {Thread.sleep(Math.max(75 - score, 25));} catch (InterruptedException e) {return;}if (energyUsed() || hitsWall() || hitsSnake()) {gameOver();} else {if (eatsTreat()) {score++;energy = MAX_ENERGY;growSnake();}moveSnake();addTreat();}repaint();}}boolean energyUsed() {energy -= 10;return energy <= 0;}boolean hitsWall() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;return grid[nextRow][nextCol] == WALL;}boolean hitsSnake() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : snake)if (p.x == nextCol && p.y == nextRow)return true;return false;}boolean eatsTreat() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : treats)if (p.x == nextCol && p.y == nextRow) {return treats.remove(p);}return false;}void gameOver() {gameOver = true;stop();}void moveSnake() {for (int i = snake.size() - 1; i > 0; i--) {Point p1 = snake.get(i - 1);Point p2 = snake.get(i);p2.x = p1.x;p2.y = p1.y;}Point head = snake.get(0);head.x += dir.x;head.y += dir.y;}void growSnake() {Point tail = snake.get(snake.size() - 1);int x = tail.x + dir.x;int y = tail.y + dir.y;snake.add(new Point(x, y));}void addTreat() {if (treats.size() < 3) {if (rand.nextInt(10) == 0) { // 1 in 10if (rand.nextInt(4) != 0) { // 3 in 4int x, y;while (true) {x = rand.nextInt(nCols);y = rand.nextInt(nRows);if (grid[y][x] != 0)continue;Point p = new Point(x, y);if (snake.contains(p) || treats.contains(p))continue;treats.add(p);break;}} else if (treats.size() > 1)treats.remove(0);}}}void drawGrid(Graphics2D g) {g.setColor(Color.lightGray);for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (grid[r][c] == WALL)g.fillRect(c * 10, r * 10, 10, 10);}}}void drawSnake(Graphics2D g) {g.setColor(Color.blue);for (Point p : snake)g.fillRect(p.x * 10, p.y * 10, 10, 10);g.setColor(energy < 500 ? Color.red : Color.orange);Point head = snake.get(0);g.fillRect(head.x * 10, head.y * 10, 10, 10);}void drawTreats(Graphics2D g) {g.setColor(Color.green);for (Point p : treats)g.fillRect(p.x * 10, p.y * 10, 10, 10);}void drawStartScreen(Graphics2D g) {g.setColor(Color.blue);g.setFont(getFont());g.drawString("Snake", 240, 190);g.setColor(Color.orange);g.setFont(smallFont);g.drawString("(click to start)", 250, 240);}void drawScore(Graphics2D g) {int h = getHeight();g.setFont(smallFont);g.setColor(getForeground());String s = format("hiscore %d score %d", hiScore, score);g.drawString(s, 30, h - 30);g.drawString(format("energy %d", energy), getWidth() - 150, h - 30); }@Overridepublic void paintComponent(Graphics gg) {super.paintComponent(gg);Graphics2D g = (Graphics2D) gg;g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);drawGrid(g);if (gameOver) {drawStartScreen(g);} else {drawSnake(g);drawTreats(g);drawScore(g);}}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {JFrame f = new JFrame();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setTitle("Snake");f.setResizable(false);f.add(new Snake(), BorderLayout.CENTER);f.pack();f.setLocationRelativeTo(null);f.setVisible(true);});}}。
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 语言设计贪吃蛇游戏源代码提供者:轻听世音一.(程序入口)snakeMainpackage game;import java.awt.Color;import java.awt.Image;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;public class snakeMain extends JFrame{//无参构造函数(构造一个初始时不可见的新窗体)public snakeMain(){ //在构造函数里面设置窗体的属性snakeWin win = new snakeWin();//Jpanel的子类add(win);//将其添加到窗口setTitle("贪吃蛇游戏");//设置窗口标题// setBackground(Color.orange);setSize(435,390);//设置窗口大小setLocation(200,200);//位置setVisible(true); //可见}public static void main(String[] args){new snakeMain();}}二.snakeAct类package game;public class snakeAct{private int x;private int y;//封装public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}}三,snakeWinpackage game;import java.awt.Color;import java.awt.FlowLayout;import java.awt.Graphics;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.IOException;import java.nio.CharBuffer;import java.util.ArrayList;import java.util.List;import java.util.Random;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;public class snakeWin extends JPanel implements ActionListener,KeyListener,Runnable{JButton newGame,stopGame; //定义两个按钮类型变量int fenShu,speed; //记录游戏的分数和速度boolean start = false; //定义一个开关,用来判断游戏的状态Random r = new Random(); //使用Random 类产生随机数int rx = 0,ry = 0; //定义两个变量记录产生的随机数的坐标List<snakeAct> list = new ArrayList<snakeAct>(); //利用列表来储存蛇块int temp = 0; //定义一个方向变量Thread nThread; //定义一个线程变量int tempeat1= 0,tempeat2 = 0; //定义两个变量,分别用来记录蛇块的量,用它们的插值来记录速度的变化JDialog dialog = new JDialog(); //游戏失败时的对话框JLabel label = new JLabel(); //可以在dialog添加label,用来显示一些信息JButton ok = new JButton("确定"); //在dialog上添加按钮//构造函数(创建具有双缓冲和流布局的新JPanel)public snakeWin(){// setBackground(Color.pink);//newGame = new JButton("开始"); //创建开始按钮newGame = new JButton("开始",new ImageIcon("src/boy.png"));stopGame = new JButton("结束",new ImageIcon("src/boy.png")); //创建结束按钮setLayout(new FlowLayout(FlowLayout.LEFT));// setLayout(new FlowLayout(FlowLayout.LEFT)); //将按钮设置为居左(按钮位置默认为居中)newGame.addActionListener(this); //设置按钮监听stopGame.addActionListener(this); //设置按钮监听ok.addActionListener(this); //设置按钮监听(结束游戏是的按钮)// newGame.addKeyListener(this);this.addKeyListener(this); //添加键盘监听add(newGame); //添加按钮add(stopGame); //添加按钮dialog.setLayout(new GridLayout(2,1));dialog.add(label); //添加labeldialog.add(ok); //添加OK 按钮dialog.setSize(300, 200); //设置dialog 大小dialog.setLocation(300, 300);//出现位置// dialog.setVisible(true); //可见}//画图public void paintComponent(Graphics g){super.paintComponent(g); //重画g.drawRect(10, 40, 400, 300); //游戏的区域在坐标为(10,40)的地方创建一个长400,高300像素的区域g.drawString("分数: "+fenShu, 200, 20); //在(150,20)的地方添加分数g.drawString("速度: "+speed, 200, 35); //在(150,35)的地方添加速度g.setColor(Color.blue); //设置蛇块的颜色if(start){g.fillRect(10+rx*10, 40+ry*10, 10, 10);//画出蛇块; 分别为蛇块的x,y坐标,和蛇块的长度高度for(int i = 0; i < list.size(); i ++){g.setColor(Color.red);g.fillRect(10+list.get(i).getX()*10,40 +list.get(i).getY()*10 , 10,10);//画出蛇体}}}//监听器public void actionPerformed(ActionEvent e){if(e.getSource() == newGame) //监听到得对象是开始按钮{newGame.setEnabled(false); //开始按钮不能再点start = true; //设定游戏开始rx = r.nextInt(40);ry = r.nextInt(30); //随机产生的食物坐标snakeAct tempAct = new snakeAct(); //(snakeAct中保存了蛇块的坐标)tempAct.setX(20); //初始蛇块位置为中总共有40个tempAct.setY(15); //初始蛇块位置为中总共有30个list.add(tempAct); //将蛇块添加到list 列表中requestFocus(true);nThread = new Thread(this);nThread.start(); //执行线程repaint();}if(e.getSource() == stopGame) //如果监听到得对象时结束游戏时{System.exit(0); //关闭窗口}if(e.getSource() == ok) //如果监听到得按钮重新开始{list.clear(); //清空列表fenShu = 0; //分数清零speed = 0; //速度清零start = false; //游戏状态为falsenewGame.setEnabled(true); //开始按钮释放,又可以点击dialog.setVisible(false);repaint();}}public void eat(){if(rx == list.get(0).getX()&&ry == list.get(0).getY()) //如果蛇头的坐标与随机产生的蛇块的坐标相对应,表示吃到食物{rx = r.nextInt(40);ry = r.nextInt(30); //吃到食物之后要产生另外一个随机食物snakeAct tempAct = new snakeAct(); //snakeAct 类中保存着蛇块的坐标属性tempAct.setX(list.get(list.size()-1).getX());tempAct.setY(list.get(list.size()-1).getY()); //直接将吃到的蛇块放到列表的末尾list.add(tempAct); //添加蛇块fenShu += 100+10*speed; //分数为吃一个食物加(100+speed*10)分tempeat1 +=1; //记录吃到的食物if(tempeat1 - tempeat2 >=10) //如果吃到的蛇块第一次相差为十时{//每吃到十个,速度加一tempeat2 = tempeat1; //速度提升的条件speed++;}repaint();}}//移动方法public void move(int x,int y){if(maxYes(x,y)){ //预判,如果minYes(x,y)返回true时,表示可以移动otherMove(); //蛇头之后的蛇块跟着蛇头动list.get(0).setX(list.get(0).getX()+x);list.get(0).setY(list.get(0).getY()+y); //蛇头的移动eat(); //吃蛇块repaint();}else{//死亡方法nThread = null;label.setText("游戏结束,你获得的分数是:"+fenShu);dialog.setVisible(true);}}public void otherMove(){/*让其他的蛇块都跟着蛇头的移动而移动,很简单,就是* 首先将第二个蛇块获得第一个蛇块的坐标,相当于* 第二个蛇块前进到原来第一个蛇块的位置,而后面* 的蛇块只需要彼此交换位置就好了,总的下来蛇块就前进了一个单位的位置,* 总之要保护蛇头,如果蛇头参与相互的交换,则控制蛇头的移动将失效*/snakeAct tempAct = new snakeAct();for(int i = 0;i < list.size();i ++){if(i == 1){list.get(i).setX(list.get(0).getX());list.get(i).setY(list.get(0).getY());}else if(i > 1){tempAct = list.get(i-1);list.set(i-1, list.get(i));list.set(i,tempAct); //交换}}}//方块移动边界的判定// public boolean minYes(int x,int y)// {// if(!maxYes(list.get(0).getX()+x , list.get(0).getY()+y))// {// return false;// }// return true;// }public boolean maxYes(int x,int y){if(list.get(0).getX()+x<0||list.get(0).getX()+x>=40||list.get(0).getY()+y<0||list.get( 0).getY()+y>=30) //如果坐标范围不在游戏设定的区域里面,简而言之就是撞墙了{return false;}for(int i = 0;i < list.size();i ++) //蛇头的坐标和自己身体的坐标相等的时候说明蛇头于身体相撞{if(i>1&&list.get(0).getX()==list.get(i).getX()&&list.get(0).getY()==list.get(i).get Y()){return false;}}return true;}// 键盘监听器public void keyPressed(KeyEvent e){if(start){switch(e.getKeyCode()) //监听到得对象{case KeyEvent.VK_UP: //UPmove(0,-1); //x不变,y减1temp = 1; //标记upbreak;case KeyEvent.VK_DOWN: //downmove(0,1); //x不变,y +1temp = 2; //标记downbreak;case KeyEvent.VK_LEFT: //leftmove(-1,0); //x-1,y不变temp = 3; //标记leftbreak;case KeyEvent.VK_RIGHT: //rightmove(1,0); //x+1,y不变temp = 4; //标记方向rightbreak;}}}public void keyReleased(KeyEvent e) {} //空函数public void keyTyped(KeyEvent e) {} //空方法public void run() //重写的run方法{while(start) //条件是游戏开始{switch(temp){case 1:move(0,-1);break;case 2:move(0,1);break;case 3:move(-1,0);break;case 4:move(1,0);break;default: //设置默认向右移动move(1,0);break;}// fenShu +=10*speed; //速度越快加的分数越高repaint();try{Thread.sleep(500-(50*speed)); //吃的蛇块越多,速度越快}catch (InterruptedException e){e.printStackTrace();}}}}。
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);}}。
java 贪吃蛇 代码

this.setSize(20, 20);
}
}
//
package cs;
import java.awt.Graphics;
import javax.swing.JLabel;
public class ground extends JLabel{
KeyAdapter ka=new KeyAdapter() {
public void keyPressed(KeyEvent e) {
char ch=e.getKeyChar();
if(ch=='w'&&(ba==true||bd==true)){
bw=true;
//
package cs;
import java.awt.Color;
import javax.swing.JLabel;
public class she extends JLabel {
// 构造函数1 蛇
public she() {
this.setOpaque(true);
while (true){
rb=b.getBounds();
rsh=this.sh[0].getBounds();
// 上
if(bw){
if(rsh.intersects(rb)){
System.out.println(++cnt);
void slp(int x){
try {
th.sleep(x);
} catch (Exception e) {
}
}
基于Java的游戏设计——贪吃蛇

毕业设计论文基于Java的游戏设计——贪吃蛇毕业设计(论文)中文摘要毕业设计(论文)外文摘要目录1 绪论 (1)1.1J AVA语言的特点 (1)1.2开发工具E CLIPSE介绍 (2)1.3开发工具JDK介绍 (3)1.4应用环境 (3)2 系统需求分析 (3)2.1需求分析 (4)2.2可行性分析 (4)3 系统概要设计 (5)3.1游戏流程图 (5)3.2设计目标 (6)3.3系统功能模块 (6)3.4系统数据结构设计 (8)4 系统详细设计 (12)4.1程序设计 (12)4.2贪吃蛇游戏各功能界面截图 (16)5 系统测试 (19)5.1测试的意义 (19)5.2测试过程 (19)5.3测试结果 (20)结论 (21)致谢 (22)参考文献 (23)1 绪论贪吃蛇是世界知名的益智类小游戏,选择这个题目一方面是为了将我们自己的所学知识加以运用;另一方面,我希望通过自己的所学知识把它剖析开来,通过自己的动手实践,真正的了解它的本质和精髓。
希望通过这次实践,能从中提高自己的编程能力。
并从中学会从零开始分析设计程序,达到学以致用,活学活用的目的。
另外,通过本游戏的开发,达到学习Java技术和熟悉软件开发流程的目的。
本游戏的开发语言为Java,开发工具选用Eclipse。
Java是一种简单的,面向对象的,分布式的,解释型的,健壮安全的,结构中立的,可移植的,性能优异、多线程的动态语言。
这里采用Java作为开发语言主要是基于Java的面向对象和可移植性。
Eclipse 是一个开放源代码的、基于Java 的可扩展开发平台。
就其本身而言,它只是一个框架和一组服务,用于通过插件组件构建开发环境。
1.1 Java语言的特点1.1.1 简单性Java与C++语言非常相近,但Java比C++简单,它抛弃了C++中的一些不是绝对必要的功能,如头文件、预处理文件、指针、结构、运算符重载、多重继承以及自动强迫同型。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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)界面美观大方,操作简单便捷,按键布局美观。
(2)实现贪吃蛇游戏的左右拐弯,增长等基本游戏功能。
(3)程序能正确运行,操作无错误。
(4)要求所撰写的课程设计任务书的内容和格式符合要求。
指导教师签字:日期:
指导教师评语
成绩:指导教师签字:日期:
课程设计所需软件、硬件等
硬件CPU:Intel T2080D-0 内存:2G 硬盘空间:320G
枣 庄 学 院
信息科学与工程学院
课程设计任务书
题目:贪吃蛇小程序的设计与开发
学号:
姓பைடு நூலகம்:
专业:计算机科学与技术
课程:java程序设计
指导教师:刘职称:讲师
完成时间:2012年5月----2012年6月
枣庄学院信息科学与工程学院制
课程设计任务书及成绩评定
课程设计的任务和具体要求
1、课程设计的任务:利用所学知识开发一个java贪吃蛇小游戏;
本程序的另一个功能是在程序运行窗口的左上角显示,用户在游戏过程中所得的分数,不过缺点是无法保存分数。
2.3.3总设计模块的划分
根据游戏需求中游戏所要实现的功能,整个游戏分为二个模块进行具体的设计,如图2-2所示。
游戏控制模块的主要框架如图2-3所示。
游戏移动速度功能控制:点击“PageUp, PageDown”按钮,蛇的移动速度就会改变,每点击一次,速度的改变频率为0.75。
游戏暂停控制:点击“Space或P暂停游戏”按钮,游戏暂停;再单击,游戏继续。
游戏重新开始控制:点击“Enter、S或R”键后,系统图重新载入,即游戏重新开始。
2.3.4类、方法、属性说明
1.成员变量
表1 主要成员变量(属性)
成员变量描述
变量类型
名称
文件菜单中子菜单“新建”
JMenuItem
mFile_New
异常的处理如下:
try{
Thread.sleep(timeInterval); }
catch(Exception e)
{
break;
}
通过这次课程设计,我对这学期所学的JAVA语言程序设计有一个更深刻的了解,将所学的知识应用于实践,由于所学知识有限,为了使游戏能够实现自己预先的构想,我通过上网和去图书馆找程序,比较好的流程图及功能模块,不断阅读修改代码使程序达到预期所要实现的目标,完成课程设计后,可以感觉到自己对Java程序的又有了新的认识。
软件 操作系统:Windows XP 开发软件:jdk eclips
课程设计进度计划
起至日期
工作内容
备注
2012.5.1—5.15
2012.6.1—6.10
2012.6.11—6.15
2012.6.16—6.20
确定课题并收集资料
整体规划并进行初步定位
编写程序代码并进行试验
撰写课程设计任务书
参考文献、资料索引
类名:Exception
作用:用来处理当蛇撞到墙或自己的身体时程序的运行
继承的父类:GreedSnake类
实现的接口:没有
2.3.1程序流程图
本次游戏设计的处理流程如图2-1所示。
2.3.2程序概述
本程序是一个利用Java应用软件制作的贪食蛇小游戏。
在游戏过程中,用户通过点击小键盘区的方向键来控制蛇的运行方向;通过Pageup和pagedown键来控制蛇的移动速度,每单击一次,蛇的移动速度改变一次,改变频率为0.75。游戏运行过程中,如果想暂停,只需要按Space或P键即可。重新开始游戏的按键为Enter、S或R。当蛇没有吃到食物且碰到墙壁或自己的身体时游戏结束。
case 3:heady++;break;
case 4:heady--;break;}//蛇头的前进
if(heady>19||headx>19||tailx>19||taily>19||heady<0||headx<0||tailx<0||taily<0||fillblock[headx][heady]!=0){
tailx=1,taily=8,tail,foodx,foody,food;//初始化定义变量
public final int EAST=1,WEST=2,SOUTH=3,NORTH=4;//方向常量
int [][] fillblock=new int [20][20];//定义蛇身所占位置
public SnakeGame() {//构造函数
FoodLocate();
food=2;
try{
Thread.sleep(100); }
catch(InterruptedException e){}//延迟
}
if(food!=0)food--;
else{tail=fillblock[tailx][taily];
fillblock[tailx][taily]=0;//蛇尾的消除
stat=0;
break;
} //判断游戏是否结束
try{
Thread.sleep(150); }
catch(InterruptedException e){}//延迟
fillblock[headx][heady]=direction;
if(headx==foodx&&heady==foody){//吃到食物
switch(tail){
case 1:tailx++;break;
case 2:tailx--;break;
case 3:taily++;break;
case 4:taily--;break;
}//蛇尾的前进
}
repaint();
}
if(stat==0)
JOptionPane.showMessageDialog(null,"GAME OVER","Game Over",RMATION_MESSAGE);
direction=EAST;//方向初始化的设置
FoodLocate(); //定位食物
while (stat==1){
fillblock[headx][heady]=direction;
switch(direction){case 1:headx++;break;
case 2:headx--;break;
设置编辑区默认背景色
无
Text.setForeground(Color.black)
设置编辑区默认前景色
无
本程序在运行后,能够正常的相应按键事件。由于程序的主要部分已经集成为一个对象SnakeModel,所以利用键盘就可以实现操作。蛇前行的过程中,可以任意向其左或右方向改变方向,但按其前进方向和前进的反方向都没有反应。点击PageUp, PageDown键后,蛇的移动速度会根据点击的次数而改变。每点击一次,速度的改变频率为0.75。点击Space或P键后游戏就暂停了。点击Enter或R或S键后系统则重新载入,即游戏重新开始。运行结果如图3-1所示:
case KeyEvent.VK_DOWN:if(direction!=NORTH)direction=SOUTH;break;
case KeyEvent.VK_LEFT:if(direction!=EAST)direction=WEST;break;
序号
文献、资料名称
编著者
出版单位
[1] 《Java语言程序设计》(第二版) 李尊朝,苏军 中国铁道出版社
[2] 《java大学基础教程》(第六版) 刘晓莉电子工业出版社
[3] 《Java编程思想》(第四版)埃史尔(美),译者:陈昊鹏 机械工业出
版社
《JAVA程序设计》是计算机相关专业的必修专业基础课程,其实践性、应用性很强。实践教学环节是必不可少的一个重要环节。本课程的程序设计专题实际是计算机相关专业学生学习完《JAVA程序设计》课程后,进行的一次全面的综合训练,JAVA程序设计的设计目的是加深对理论教学内容的理解和掌握,使学生较系统地掌握程序设计及其在网络开发中的广泛应用,基本方法及技巧,为学生综合运用所学知识,利用软件工程为基础进行软件开发、并在实践应用方面打下一定基础。