Java贪吃蛇游戏源代码
- 格式:doc
- 大小:45.00 KB
- 文档页数:8
游戏贪吃蛇的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);});}}。
贪吃蛇源代码将Location、LocationRO、SnakeFrame、SnakeModel、SnakePanel放到命名为snake的文件夹里,主函数MainApp放到外面运行主函数即可实现。
主函数package snake;import javax.swing.*;import snake.*;public class MainApp {public static void main(String[] args) {JFrame.setDefaultLookAndFeelDecorated(true);SnakeFrame frame=new SnakeFrame();frame.setSize(350,350);frame.setResizable(false);frame.setLocation(330,220);frame.setTitle("贪吃蛇");frame.setV isible(true);}}package snake;public class Location {private int x;private int y;Location(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}void setX(int x){this.x=x;}void setY(int y){this.y=y;}public boolean equalOrRev(Location e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(Location e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(Location e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;public class LocationRO{private int x;private int y;LocationRO(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}public boolean equalOrRev(LocationRO e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(LocationRO e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(LocationRO e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;import java.awt.*;import java.awt.event.*;import javax.swing.*;class SnakeFrame extends JFrame implements ActionListener{final SnakePanel p=new SnakePanel(this);JMenuBar menubar=new JMenuBar();JMenu fileMenu=new JMenu("文件");JMenuItem newgameitem=new JMenuItem("开始");JMenuItem stopitem=new JMenuItem("暂停");JMenuItem runitem=new JMenuItem("继续");JMenuItem exititem=new JMenuItem("退出");//"设置"菜单JMenu optionMenu=new JMenu("设置");//等级选项ButtonGroup groupDegree = new ButtonGroup();JRadioButtonMenuItem oneItem= new JRadioButtonMenuItem("初级");JRadioButtonMenuItem twoItem= new JRadioButtonMenuItem("中级");JRadioButtonMenuItem threeItem= new JRadioButtonMenuItem("高级");JMenu degreeMenu=new JMenu("等级");JMenu helpMenu=new JMenu("帮助");JMenuItem helpitem=new JMenuItem("操作指南");final JCheckBoxMenuItem showGridItem = new JCheckBoxMenuItem("显示网格");JLabel scorelabel;public JTextField scoreField;private long speedtime=200;private String helpstr = "游戏说明:\n1 :方向键控制蛇移动的方向."+"\n2 :单击菜单'文件->开始'开始游戏."+"\n3 :单击菜单'文件->暂停'或者单击键盘空格键暂停游戏."+"\n4 :单击菜单'文件->继续'继续游戏."+"\n5 :单击菜单'设置->等级'可以设置难度等级."+"\n6 :单击菜单'设置->显示网格'可以设置是否显示网格."+ "\n7 :红色为食物,吃一个得10分同时蛇身加长."+"\n8 :蛇不可以出界或自身相交,否则结束游戏.";SnakeFrame(){setJMenuBar(menubar);fileMenu.add(newgameitem);fileMenu.add(stopitem);fileMenu.add(runitem);fileMenu.add(exititem);menubar.add(fileMenu);oneItem.setSelected(true);groupDegree.add(oneItem);groupDegree.add(twoItem);groupDegree.add(threeItem);degreeMenu.add(oneItem);degreeMenu.add(twoItem);degreeMenu.add(threeItem);optionMenu.add(degreeMenu);// 风格选项showGridItem.setSelected(true);optionMenu.add(showGridItem);menubar.add(optionMenu);helpMenu.add(helpitem);menubar.add(helpMenu);Container contentpane=getContentPane();contentpane.setLayout(new FlowLayout());contentpane.add(p);scorelabel=new JLabel("得分: ");scoreField=new JTextField("0",15);scoreField.setEnabled(false);scoreField.setHorizontalAlignment(0);JPanel toolPanel=new JPanel();toolPanel.add(scorelabel);toolPanel.add(scoreField);contentpane.add(toolPanel);oneItem.addActionListener(this);twoItem.addActionListener(this);threeItem.addActionListener(this);newgameitem.addActionListener(this);stopitem.addActionListener(this);runitem.addActionListener(this);exititem.addActionListener(this);helpitem.addActionListener(this);showGridItem.addActionListener(this);}public void actionPerformed(ActionEvent e){try{if(e.getSource()==helpitem){JOptionPane.showConfirmDialog(p,helpstr,"操纵说明",JOptionPane.PLAIN_MESSAGE);}else if(e.getSource()==exititem)System.exit(0);else if(e.getSource()==newgameitem)p.newGame(speedtime);else if(e.getSource()==stopitem)p.stopGame();else if(e.getSource()==runitem)p.returnGame();else if(e.getSource()==showGridItem){if(!showGridItem.isSelected()){p.setBackground(Color.lightGray);}else{p.setBackground(Color.darkGray);}}else if(e.getSource()==oneItem) speedtime=200;else if(e.getSource()==twoItem) speedtime=100;else if(e.getSource()==threeItem) speedtime=50;}catch(Exception ee){ee.printStackTrace();}}}package snake;import java.util.*;import javax.swing.JOptionPane;public class SnakeModel {private int rows,cols;//行列数private Location snakeHead,runingDiriction;//运行方向private LocationRO[][] locRO;//LocationRO类数组private LinkedList snake,playBlocks;//蛇及其它区域块private LocationRO snakeFood;//目标食物private int gameScore=0; //分数private boolean AddScore=false;//加分// 获得蛇头public LocationRO getSnakeHead(){return (LocationRO)(snake.getLast());}//蛇尾public LocationRO getSnakeTail(){return (LocationRO)(snake.getFirst());}//运行路线public Location getRuningDiriction(){return runingDiriction;}//获得蛇实体区域public LinkedList getSnake(){return snake;}//其他区域public LinkedList getOthers(){return playBlocks;}//获得总分public int getScore(){return gameScore;}//获得增加分数public boolean getAddScore(){return AddScore;}//设置蛇头方向private void setSnakeHead(Location snakeHead){ this.snakeHead=snakeHead;}//获得目标食物public LocationRO getSnakeFood(){return snakeFood;}//随机设置目标食物private void setSnakeFood(){snakeFood=(LocationRO)(playBlocks.get((int)(Math.random()*playBlocks.size()))); }//移动private void moveTo(Object a,LinkedList fromlist,LinkedList tolist){fromlist.remove(a);tolist.add(a);}//初始设置public void init(){playBlocks.clear();snake.clear();gameScore=0;for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){playBlocks.add(locRO[i][j]);}}//初始化蛇的形状for(int i=4;i<7;i++){moveTo(locRO[4][i],playBlocks,snake);}//蛇头位置snakeHead=new Location(4,6);//设置随机块snakeFood=new LocationRO(0,0);setSnakeFood();//初始化运动方向runingDiriction=new Location(0,1);}//Snake构造器public SnakeModel(int rows1,int cols1){rows=rows1;cols=cols1;locRO=new LocationRO[rows][cols];snake=new LinkedList();playBlocks=new LinkedList();for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){locRO[i][j]=new LocationRO(i,j);}}init();}/**定义布尔型move方法,如果运行成功则返回true,否则返回false*参数direction是Location类型,*direction 的值:(-1,0)表示向上;(1,0)表示向下;*(0,-1)表示向左;(0,1)表示向右;**/public boolean move(Location direction){//判断设定的方向跟运行方向是不是相反if (direction.reverse(runingDiriction)){snakeHead.setX(snakeHead.getX()+runingDiriction.getX());snakeHead.setY(snakeHead.getY()+runingDiriction.getY());}else{snakeHead.setX(snakeHead.getX()+direction.getX());snakeHead.setY(snakeHead.getY()+direction.getY());}//如果蛇吃到了目标食物try{if ((snakeHead.getX()==snakeFood.getX())&&(snakeHead.getY()==snakeFood.getY())){moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);setSnakeFood();gameScore+=10;AddScore=true;}else{AddScore=false;//是否出界if((snakeHead.getX()<rows)&&(snakeHead.getY()<cols)&&(snakeHead.getX()>=0&&(snak eHead.getY()>=0))){//如果不出界,判断是否与自身相交if(snake.contains(locRO[snakeHead.getX()][snakeHead.getY()])){//如果相交,结束游戏JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束",RMA TION_MESSAGE);return false;}else{//如果不相交,就把snakeHead加到snake里面,并且把尾巴移出moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);moveTo(snake.getFirst(),snake,playBlocks);}}else{//出界,游戏结束JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", RMA TION_MESSAGE);return false;}}}catch(ArrayIndexOutOfBoundsException e){return false;}//设置运行方向if (!(direction.reverse(runingDiriction)||direction.equals(runingDiriction))){runingDiriction.setX(direction.getX());runingDiriction.setY(direction.getY());}return true;}}package snake;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;public class SnakePanel extends JPanel implements Runnable,KeyListener{JFrame parent=new JFrame();private int row=20; //网格行数private int col=30; //列数private JPanel[][] gridsPanel; //面板网格private Location direction;//方向定位private SnakeModel snake; //贪吃蛇private LinkedList snakeBody; //蛇的身体private LinkedList otherBlocks; //其他区域private LocationRO snakeHead; //蛇的头部private LocationRO snakeFood; //目标食物private Color bodyColor=Color.orange;//蛇的身体颜色private Color headColor=Color.black; //蛇的头部颜色private Color foodColor=Color.red; //目标食物颜色private Color othersColor=Color.lightGray;//其他区域颜色private int gameScore=0; //总分private long speed; //速度(难度设置)private boolean AddScore; //加分private Thread t; //线程private boolean isEnd; //暂停private static boolean notExit;// 构造器,初始化操作public SnakePanel(SnakeFrame parent){this.parent=parent;gridsPanel=new JPanel[row][col];otherBlocks=new LinkedList();snakeBody=new LinkedList();snakeHead=new LocationRO(0,0);snakeFood=new LocationRO(0,0);direction=new Location(0,1);// 布局setLayout(new GridLayout(row,col,1,1));for(int i=0;i<row;i++){for(int j=0;j<col;j++){gridsPanel[i][j]=new JPanel();gridsPanel[i][j].setBackground(othersColor);add(gridsPanel[i][j]);}}addKeyListener(this);}// 开始游戏public void newGame(long speed){this.speed=speed;if (notExit) {snake.init();}else{snake=new SnakeModel(row,col);notExit=true;t=new Thread(this);t.start();}requestFocus();direction.setX(0);direction.setY(1);gameScore=0;updateTextFiled(""+gameScore);isEnd=false;}// 暂停游戏public void stopGame(){requestFocus();isEnd=true;}// 继续public void returnGame(){requestFocus();isEnd=false;}// 获得总分public int getGameScore(){return gameScore;}//更新总分private void updateTextFiled(String str){((SnakeFrame)parent).scoreField.setText(str); }//更新各相关单元颜色private void updateColors(){// 设定蛇身颜色snakeBody=snake.getSnake();Iterator i =snakeBody.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(bodyColor);}//设定蛇头颜色snakeHead=snake.getSnakeHead();gridsPanel[snakeHead.getX()][snakeHead.getY()].setBackground(headColor);//设定背景颜色otherBlocks=snake.getOthers();i =otherBlocks.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(othersColor);}//设定临时块的颜色snakeFood=snake.getSnakeFood();gridsPanel[snakeFood.getX()][snakeFood.getY()].setBackground(foodColor); }public boolean isFocusTraversable(){return true;}//实现Runnable接口public void run(){while(true){try{Thread.sleep(speed);}catch (InterruptedException e){}if(!isEnd){isEnd=!snake.move(direction);updateColors();if(snake.getAddScore()){gameScore+=10;updateTextFiled(""+gameScore);}}}}//实现KeyListener接口public void keyPressed(KeyEvent event){int keyCode = event.getKeyCode();if(notExit){if (keyCode == KeyEvent.VK_LEFT) { //向左direction.setX(0);direction.setY(-1);}else if (keyCode == KeyEvent.VK_RIGHT) { //向右direction.setX(0);direction.setY(1);}else if (keyCode == KeyEvent.VK_UP) { //向上direction.setX(-1);direction.setY(0);}else if (keyCode == KeyEvent.VK_DOWN) { //向下direction.setX(1);direction.setY(0);}else if (keyCode == KeyEvent.VK_SPACE){ //空格键isEnd=!isEnd;}}}public void keyReleased(KeyEvent event){}public void keyTyped(KeyEvent event){}}。
附录1.SnakeView类package com.example.android_snake.view;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import com.example.android_snake.R;import com.example.android_snake.food.Food;import com.example.android_snake.snake.Body;import com.example.android_snake.snake.Head;import com.example.android_snake.snake.Snake;import com.example.android_snake.snake.SnakeDirection; import com.example.android_snake.stone.Stone;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.os.Handler;import android.util.DisplayMetrics;import android.view.Display;import android.view.MotionEvent;import android.view.View;import android.view.ViewManager;import android.view.WindowManager;import android.widget.Toast;public class SnakeView extends View {private Context context;private Bitmap headBitmap;private Bitmap bodyBitmap;private Bitmap foodBitmap;private Bitmap stoneBitmap;// 屏幕的高度和宽度private int screenHeight;private int screenWidth;// 每个小格子的高度和宽度private int eachHeight;private int eachWidth;private Snake snake;private Food food;private Stone stone;private int [] listx;private int [] listy;private Timer timer = new Timer();Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {moveSnake();invalidate();}};public SnakeView(Context context) {super(context);this.context = context;listx =new int[100];listy =new int[100];// 获得屏幕的高和宽DisplayMetrics metrics = new DisplayMetrics();WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);windowManager.getDefaultDisplay().getMetrics(metrics);screenHeight = metrics.heightPixels;screenWidth = metrics.widthPixels;eachHeight = screenHeight / 32;eachWidth = screenWidth / 20;// 初始化图片headBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.head);bodyBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.body);foodBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.food);stoneBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.stone);this.initSnake();this.initFood();this.initstone();gameRun();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);Paint paint = new Paint();// 定义画笔paint.setColor(Color.GRAY);// 设置画笔颜色paint.setAntiAlias(true);// 去除锯齿paint.setStyle(Style.STROKE);// 设置空心实心paint.setTextSize(40);drawLines(canvas, paint);drawStone(canvas, paint);if(isCollide()){canvas.drawText("Game Over!", screenWidth/4, screenHeight/3, paint);canvas.drawText("得分", screenWidth/4, screenHeight/2, paint);timer.cancel();}else{this.drawSnake(canvas, paint);}boolean flag = IsRectCollision(snake.getHead().getPointX(), snake.getHead().getPointY(), eachWidth, eachHeight,food.getPointX(), food.getPointY(), eachWidth, eachHeight);if (flag) {food = null;snake.getBodyList().add(new Body());this.initFood();this.initstone();} else {this.drawFood(canvas, paint);this.drawStone(canvas, paint);}}//方向控制@Overridepublic boolean onTouchEvent(MotionEvent event) {int x = (int) event.getX();int y = (int) event.getY();SnakeDirection nowDir = snake.getSnakeDirection();int m = -screenHeight * x + screenHeight * screenWidth - screenWidth * y;int n = screenHeight * x - screenWidth * y;if ((m > 0 && n > 0) && (nowDir != SnakeDirection.DOWN)) {snake.setSnakeDirection(SnakeDirection.UP);} else if ((m > 0 && n < 0) && (nowDir != SnakeDirection.RIGHT)) { snake.setSnakeDirection(SnakeDirection.LEFT);} else if ((m < 0 && n > 0) && (nowDir != SnakeDirection.LEFT)) { snake.setSnakeDirection(SnakeDirection.RIGHT);} else if ((m < 0 && n < 0) && (nowDir != SnakeDirection.UP)) { snake.setSnakeDirection(SnakeDirection.DOWN);}return super.onTouchEvent(event);}public void gameRun() {timer.scheduleAtFixedRate(new TimerTask() {public void run() {handler.obtainMessage().sendToTarget();}}, 100, 400);}/** 画网格线*/public void drawLines(Canvas canvas, Paint paint) {int startX = 0, startY = 0;for (int i = 0; i < 100; i++) {canvas.drawLine(0, startY, screenWidth, startY, paint);startY = startY + eachHeight;}for (int i = 0; i < 100; i++) {canvas.drawLine(startX, 0, startX, screenHeight, paint);startX = startX + eachWidth;}canvas.drawLine(0, 0, screenWidth, screenHeight, paint);canvas.drawLine(0, screenHeight, screenWidth, 0, paint);}// 初始化蛇public void initSnake() {List<Body> bodies = new ArrayList<Body>();Head head = new Head(eachWidth * 4, eachHeight * 2, headBitmap);Body body1 = new Body(eachWidth * 3, eachHeight * 2, bodyBitmap);Body body2 = new Body(eachWidth * 2, eachHeight * 2, bodyBitmap);Body body3 = new Body(eachWidth * 1, eachHeight * 2, bodyBitmap);Body body4 = new Body(eachWidth * 0, eachHeight * 2, bodyBitmap);bodies.add(body1);bodies.add(body2);bodies.add(body3);bodies.add(body4);snake = new Snake(head, bodies, SnakeDirection.RIGHT);}// 画蛇public void drawSnake(Canvas canvas, Paint paint) {canvas.drawBitmap(headBitmap, snake.getHead().getPointX(), snake .getHead().getPointY(), paint);for (int i = 0; i < snake.getBodyList().size(); i++) {canvas.drawBitmap(bodyBitmap, snake.getBodyList().get(i).getPointX(), snake.getBodyList().get(i).getPointY(), paint);}}// 改变蛇身的位置public void changSnakePosition(int pointX, int pointY) {for (int i = snake.getBodyList().size() - 1; i > 0; i--) {snake.getBodyList().get(i).setPointX(snake.getBodyList().get(i - 1).getPointX());snake.getBodyList().get(i).setPointY(snake.getBodyList().get(i - 1).getPointY());}snake.getBodyList().get(0).setPointX(snake.getHead().getPointX());snake.getBodyList().get(0).setPointY(snake.getHead().getPointY());}// 移动蛇public void moveSnake() {int nowPointX = snake.getHead().getPointX();int nowPointY = snake.getHead().getPointY();if (snake.getSnakeDirection() == SnakeDirection.RIGHT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX >= screenWidth - eachWidth) {snake.getHead().setPointX(0);} else {snake.getHead().setPointX(nowPointX + eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.DOWN) { changSnakePosition(nowPointX, nowPointY);if (nowPointY >= screenHeight - eachHeight) {snake.getHead().setPointY(0);} else {snake.getHead().setPointY(nowPointY + eachHeight);}} else if (snake.getSnakeDirection() == SnakeDirection.LEFT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX <= 0) {snake.getHead().setPointX(screenWidth - eachWidth);} else {snake.getHead().setPointX(nowPointX - eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.UP) {changSnakePosition(nowPointX, nowPointY);if (nowPointY <= 0) {snake.getHead().setPointY(screenHeight - eachHeight);} else {snake.getHead().setPointY(nowPointY - eachHeight);}}}// 初始化foodpublic void initFood() {int x = new Random().nextInt(19);int y = new Random().nextInt(29);food = new Food(eachWidth * x, eachHeight * y, foodBitmap);}// 在界面上画出Foodpublic void drawFood(Canvas canvas, Paint paint) {if (food != null) {canvas.drawBitmap(foodBitmap, food.getPointX(), food.getPointY(),paint);}}// 初始化stonepublic void initstone() {int x = new Random().nextInt(17);int y = new Random().nextInt(23);stone = new Stone(eachWidth * x, eachHeight * y, stoneBitmap);int i=0,j=0;listx[i++]=x;listy[j++]=y;}// 在界面上画出Stonepublic void drawStone(Canvas canvas, Paint paint) {if (true) {canvas.drawBitmap(stoneBitmap, stone.getPointX(), stone.getPointY(),paint);for(int k=0;k<100;k++){//food = new Food(eachWidth * listx[k], eachHeight * listy[k], foodBitmap);//canvas.drawBitmap(stoneBitmap,listx[k], listy[k],paint);}}}/*** 矩形碰撞检测参数为x,y,width,height** @param x1* 第一个矩形的x* @param y1* 第一个矩形的y* @param w1* 第一个矩形的w* @param h1* 第一个矩形的h* @param x2* 第二个矩形的x* @param y2* 第二个矩形的y* @param w2* 第二个矩形的w* @param h2* 第二个矩形的h* @return是否碰撞*/public boolean IsRectCollision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {if (x2 > x1 && x2 >= x1 + w1) {return false;} else if (x2 < x1 && x2 <= x1 - w2) {return false;} else if (y2 > y1 && y2 >= y1 + h1) {return false;} else if (y2 < y1 && y2 <= y1 - h2) {return false;} else {return true;}}//检测蛇头是否与蛇身碰撞//检测蛇头与墙的碰撞//public boolean isCollide() {boolean flag = false;for (int i = 0; i < snake.getBodyList().size(); i++) {flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,snake.getBodyList().get(i).getPointX(),snake.getBodyList().get(i).getPointY(),eachWidth,eachHeight);for(int j=0;j<100;j++){flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,listx[j],listy[j], eachWidth,eachHeight);if(flag){break;}}if ((snake.getHead().getPointX() < 1) ||(snake.getHead().getPointY() < 1) ||(snake.getHead().getPointX() > screenWidth - 1)||(snake.getHead().getPointY() > screenHeight - 1)){flag = true;}if(flag){break;}}return flag;}}2.MainActivity类package com.example.android_snake;import com.example.android_snake.R;import com.example.android_snake.view.SnakeView;//Downloads By import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.MenuItem;import android.view.Window;import android.view.WindowManager;public class MainActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);//设置全屏getWindow().setFlags(youtParams.FLAG_FULLSCREEN, youtParams.FLAG_FULLSCREEN);SnakeView view = new SnakeView(this);setContentView(view);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu);return true;}}3.Food类package com.example.android_snake.food;import android.graphics.Bitmap;public class Food {private int pointX;private int pointY;private Bitmap foodBitmap;public Food() {super();}public Food(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.foodBitmap = foodBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getFoodBitmap() {return foodBitmap;}public void setFoodBitmap(Bitmap foodBitmap) {this.foodBitmap = foodBitmap;}}4.Body类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Body {private int pointX;private int pointY;private Bitmap bodyBitMap;public Body() {super();}public Body(int pointX, int pointY, Bitmap bodyBitMap) { super();this.pointX = pointX;this.pointY = pointY;this.bodyBitMap = bodyBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getBodyBitMap() {return bodyBitMap;}public void setBodyBitMap(Bitmap bodyBitMap) {this.bodyBitMap = bodyBitMap;}}5.Head类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Head {private int pointX;private int pointY;private Bitmap headBitMap;public Head() {super();}public Head(int pointX, int pointY, Bitmap headBitMap) {super();this.pointX = pointX;this.pointY = pointY;this.headBitMap = headBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getHeadBitMap() {return headBitMap;}public void setHeadBitMap(Bitmap headBitMap) {this.headBitMap = headBitMap;}}6.Snake类package com.example.android_snake.snake;import java.util.ArrayList;import java.util.List;import android.graphics.Bitmap;public class Snake {private Head head;private Body body;private List<Body> bodyList;private SnakeDirection snakeDirection;public Snake(){}public Snake(Head head,List<Body> bodyList,SnakeDirection snakeDirection){ super();this.head = head;this.bodyList = bodyList;this.snakeDirection = snakeDirection;}public Head getHead() {return head;}public void setHead(Head head) {this.head = head;}public Body getBody() {return body;}public void setBody(Body body) {this.body = body;}public List<Body> getBodyList() {return bodyList;}public void setBodyList(List<Body> bodyList) {this.bodyList = bodyList;}public SnakeDirection getSnakeDirection() {return snakeDirection;}public void setSnakeDirection(SnakeDirection snakeDirection) { this.snakeDirection = snakeDirection;}}7.SnakeDirection类package com.example.android_snake.snake;public enum SnakeDirection {UP,DOWN,LEFT,RIGHT;}8.Stone类package com.example.android_snake.stone;import android.graphics.Bitmap;public class Stone {private int pointX;private int pointY;private Bitmap stoneBitmap;public Stone() {super();}public Stone(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.stoneBitmap = stoneBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getStoneBitmap() {return stoneBitmap;}public void setFoodBitmap(Bitmap foodBitmap) { this.stoneBitmap = stoneBitmap;}}。
import java.awt.*;import java.awt.event.*;public class GreedSnake //主类{public static void main(String[] args) {// TODO Auto-generated method stubnew MyWindow();}}class MyPanel extends Panel implements KeyListener,Runnable//自定义面板类,继承了键盘和线程接口{Button snake[]; //定义蛇按钮int shu=0; //蛇的节数int food[]; //食物数组boolean result=true; //判定结果是输还是赢Thread thread; //定义线程static int weix,weiy; //食物位置boolean t=true; //判定游戏是否结束int fangxiang=0; //蛇移动方向int x=0,y=0; //蛇头位置MyPanel(){setLayout(null);snake=new Button[20];food=new int [20];thread=new Thread(this);for(int j=0;j<20;j++){food[j]=(int)(Math.random()*99);//定义20个随机食物}weix=(int)(food[0]*0.1)*60; //十位*60为横坐标weiy=(int)(food[0]%10)*40; //个位*40为纵坐标for(int i=0;i<20;i++){snake[i]=new Button();}add(snake[0]);snake[0].setBackground(Color.black);snake[0].addKeyListener(this); //为蛇头添加键盘监视器snake[0].setBounds(0,0,10,10);setBackground(Color.cyan);}public void run() //接收线程{while(t){if(fangxiang==0)//向右{try{x+=10;snake[0].setLocation(x, y);//设置蛇头位置if(x==weix&&y==weiy) //吃到食物{shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint(); //重绘下一个食物add(snake[shu]); //增加蛇节数和位置snake[shu].setBounds(snake[shu-1].getBounds()); }thread.sleep(100); //睡眠100ms}catch(Exception e){}}else if(fangxiang==1)//向左{try{x-=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds()); }thread.sleep(100);}catch(Exception e){}}else if(fangxiang==2)//向上{try{y-=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds());}thread.sleep(100);}catch(Exception e){}}else if(fangxiang==3)//向下{try{y+=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds());}thread.sleep(100);}catch(Exception e){}}int num1=shu;while(num1>1)//判断是否咬自己的尾巴{if(snake[num1].getBounds().x==snake[0].getBounds().x&&snake[num1].getBounds().y==snake[0]. getBounds().y){t=false;result=false;repaint();}num1--;}/*if(x<0||x>=this.getWidth()||y<0||y>=this.getHeight())//判断是否撞墙{t=false;result=false;repaint();}*/int num=shu;while(num>0) //设置蛇节位置{snake[num].setBounds(snake[num-1].getBounds());num--;}if(shu==5) //如果蛇节数等于15则胜利{t=false;result=true;repaint();}}}public void keyPressed(KeyEvent e) //按下键盘方向键{if(e.getKeyCode()==KeyEvent.VK_RIGHT)//右键{if(fangxiang!=1)//如果先前方向不为左fangxiang=0;}else if(e.getKeyCode()==KeyEvent.VK_LEFT){ if(fangxiang!=0)fangxiang=1;}else if(e.getKeyCode()==KeyEvent.VK_UP){ if(fangxiang!=3)fangxiang=2;}else if(e.getKeyCode()==KeyEvent.VK_DOWN){ if(fangxiang!=2)fangxiang=3;}}public void keyTyped(KeyEvent e){}public void keyReleased(KeyEvent e){}public void paint(Graphics g) //在面板上绘图{int x1=this.getWidth()-1;int y1=this.getHeight()-1;g.setColor(Color.red);g.fillOval(weix, weiy, 10, 10);//食物g.drawRect(0, 0, x1, y1); //墙if(t==false&&result==false)g.drawString("游戏结束", 250, 200);//输出游戏失败else if(t==false&&result==true)g.drawString("你赢了", 250, 200);//输出游戏成功}}class MyWindow extends Frame implements ActionListener//自定义窗口类{MyPanel my;Button btn;Panel panel;MyWindow(){super("GreedSnake");my=new MyPanel();btn=new Button("begin");panel=new Panel();btn.addActionListener(this);panel.add(new Label("begin后请按Tab键选定蛇"));panel.add(btn);panel.add(new Label("按上下左右键控制蛇行动"));add(panel,BorderLayout.NORTH);add(my,BorderLayout.CENTER);setBounds(100,100,610,500);setVisible(true);validate();addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public void actionPerformed(ActionEvent e)//按下begin按钮{if(e.getSource()==btn){try{my.thread.start(); //开始线程my.validate();}catch(Exception ee){}}}}。
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();}}}}。
import java.awt.Color;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.InputEvent;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JCheckBoxMenuItem;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.KeyStroke;public class 贪吃蛇extends JFrame implements ActionListener, KeyListener,Runnable {private static final long serialV ersionUID = 1L;private JMenuBar menuBar;private JMenu youXiMenu,nanDuMenu,fenShuMenu,guanY uMenu;private JMenuItem kaiShiY ouXi,exitItem,zuoZheItem,fenShuItem;private JCheckBoxMenuItem cJianDan,cPuTong,cKunNan;private int length = 6;private Toolkit toolkit;private int i,x,y,z,objectX,objectY,object=0,growth=0,time;//bojectX,Yprivate int m[]=new int[50];private int n[]=new int[50];private Thread she = null;private int life=0;private int foods = 0;private int fenshu=0;public void run(){time=500;for(i=0;i<=length-1;i++){m[i]=90-i*10;n[i]=60;}x=m[0];y=n[0];z=4;while(she!=null){check();try{Thread.sleep(time);}catch(Exception ee){System.out.println(z+"");}}}public 贪吃蛇() {setVisible(true);menuBar = new JMenuBar();toolkit=getToolkit();youXiMenu = new JMenu("游戏");kaiShiY ouXi = new JMenuItem("开始游戏"); exitItem = new JMenuItem("退出游戏");nanDuMenu = new JMenu("困难程度"); cJianDan = new JCheckBoxMenuItem("简单"); cPuTong = new JCheckBoxMenuItem("普通"); cKunNan = new JCheckBoxMenuItem("困难");fenShuMenu = new JMenu("积分排行"); fenShuItem = new JMenuItem("最高记录");guanY uMenu = new JMenu("关于");zuoZheItem = new JMenuItem("关于作者");guanY uMenu.add(zuoZheItem);nanDuMenu.add(cJianDan);nanDuMenu.add(cPuTong);nanDuMenu.add(cKunNan);fenShuMenu.add(fenShuItem);youXiMenu.add(kaiShiY ouXi);youXiMenu.add(exitItem);menuBar.add(youXiMenu);menuBar.add(nanDuMenu);menuBar.add(fenShuMenu);menuBar.add(guanY uMenu);zuoZheItem.addActionListener(this);kaiShiY ouXi.addActionListener(this);exitItem.addActionListener(this);addKeyListener(this);fenShuItem.addActionListener(this);KeyStroke keyOpen = KeyStroke.getKeyStroke('O',InputEvent.CTRL_DOWN_MASK); kaiShiY ouXi.setAccelerator(keyOpen);KeyStroke keyExit = KeyStroke.getKeyStroke('X',InputEvent.CTRL_DOWN_MASK); exitItem.setAccelerator(keyExit);setJMenuBar(menuBar);setTitle("贪吃蛇");setResizable(false);setBounds(300,200,400,400);validate();setDefaultCloseOperation(EXIT_ON_CLOSE);}public static void main(String args[]) {new 贪吃蛇();}public void actionPerformed(ActionEvent e){if(e.getSource()==kaiShiY ouXi){length = 6;life = 0;foods = 0;if(she==null){she=new Thread(this);she.start();}else if(she!=null){she=null;she= new Thread(this);she.start();}}if(e.getSource()==exitItem){System.exit(0);}if(e.getSource()==zuoZheItem){JOptionPane.showMessageDialog(this, "孤独的野狼制作"+"\n\n"+" "+"QQ号:2442701497"+"\n");}if(e.getSource()==fenShuItem){JOptionPane.showMessageDialog(this,"最高记录为"+fenshu+"");}}public void check(){isDead();if(she!=null){if(growth==0){reform(); //得到食物}else{upgrowth(); //生成食物}if(x==objectX&&y==objectY){object=0;growth=1;toolkit.beep();}if(object==0){object=1;objectX=(int)Math.floor(Math.random()*39)*10;objectY=(int)Math.floor(Math.random()*29)*10+50;}this.repaint(); //重绘}}void isDead(){//判断游戏是否结束的方法if(z==4){x=x+10;}else if(z==3){x=x-10;}else if(z==2){y=y+10;}else if(z==1){y=y-10;}if(x<0||x>390||y<50||y>390){she=null;}for(i=1;i<length;i++){if(m[i]==x&&n[i]==y){she=null;}}}public void upgrowth(){//当蛇吃到东西时的方法if(length<50){length++;}growth--;time=time-10;reform();life+=100;if(fenshu<life){fenshu = life;}foods++;}public void reform(){for(i=length-1;i>0;i--){m[i]=m[i-1];n[i]=n[i-1];}if(z==4){m[0]=m[0]+10;}if(z==3){m[0]=m[0]-10;}if(z==2){n[0]=n[0]+10;}if(z==1){n[0]=n[0]-10;}}public void keyPressed(KeyEvent e) {if(she!=null){if(e.getKeyCode()==KeyEvent.VK_UP){if(z!=2){z=1;check();}}else if(e.getKeyCode()==KeyEvent.VK_DOWN) {if(z!=1){z=2;check();}}else if(e.getKeyCode()==KeyEvent.VK_LEFT){if(z!=4){z=3;check();}}else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {if(z!=3){z=4;check();}}}}public void keyReleased(KeyEvent e){}public void keyTyped(KeyEvent e){}public void paint(Graphics g) {g.setColor(Color.DARK_GRAY); //设置背景g.fillRect(0,50,400,400);g.setColor(Color.pink);for(i=0;i<=length-1;i++){g.fillRect(m[i],n[i],10,10);}g.setColor(Color.green); //蛇的食物g.fillRect(objectX,objectY,10,10);g.setColor(Color.white);g.drawString("当前分数"+this.life,6,60);g.drawString("当前已吃食物数"+this.foods,6,72); }}。
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);}}。
import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.util.*;public class SnakeGame extends JFrame implements KeyListener{private int stat=1,direction=0,bodylen=6,headx=7,heady=8,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() {//构造函数super("贪吃蛇");setSize(510,510);setVisible(true);//设定窗口属性addKeyListener(this);//添加监听setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);for(int i=1;i<=7;i++) fillblock[i][8]=EAST;//初始化蛇身属性direction=EAST;//方向初始化的设置FoodLocate(); //定位食物while (stat==1){fillblock[headx][heady]=direction;switch(direction){case 1:headx++;break;case 2:headx--;break;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){stat=0;break;} //判断游戏是否结束try{Thread.sleep(150); }catch(InterruptedException e){}//延迟fillblock[headx][heady]=direction;if(headx==foodx&&heady==foody){//吃到食物FoodLocate();food=2;try{Thread.sleep(100); }catch(InterruptedException e){}//延迟}if(food!=0)food--;else{tail=fillblock[tailx][taily];fillblock[tailx][taily]=0;//蛇尾的消除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);}public void keyPressed(KeyEvent e) {//按键响应int keyCode=e.getKeyCode();if(stat==1) switch(keyCode){case KeyEvent.VK_UP:if(direction!=SOUTH) direction=NORTH;break;caseKeyEvent.VK_DOWN:if(direction!=NORTH)direction=SOUTH;break;caseKeyEvent.VK_LEFT:if(direction!=EAST)direction=WEST;break;case KeyEvent.VK_RIGHT:if(direction!=WEST)direction=EAST;break;}}public void keyReleased(KeyEvent e){}//空函数public void keyTyped(KeyEvent e){} //空函数public void FoodLocate(){//定位食物坐标do{Random r=new Random();foodx=r.nextInt(20);foody=r.nextInt(20);}while (fillblock[foodx][foody]!=0);}public void paint(Graphics g){//画图super.paint(g);g.setColor(Color.BLUE);for(int i=0;i<20;i++)for(int j=0;j<20;j++)if (fillblock[i][j]!=0)g.fillRect(25*i+5,25*j+5,24,24);g.setColor(Color.RED);g.fillRect(foodx*25+5,foody*25+5,24,24);}public static void main(String[] args) {//主程序SnakeGame application=new SnakeGame();}}。
贪吃蛇源代码将Location、LocationRO、SnakeFrame、SnakeModel、SnakePanel放到命名为snake的文件夹里,主函数MainApp放到外面运行主函数即可实现。
主函数package snake;import javax.swing.*;import snake.*;public class MainApp {public static void main(String[] args) {JFrame.setDefaultLookAndFeelDecorated(true);SnakeFrame frame=new SnakeFrame();frame.setSize(350,350);frame.setResizable(false);frame.setLocation(330,220);frame.setTitle("贪吃蛇");frame.setVisible(true);}}package snake;public class Location {private int x;private int y;Location(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}void setX(int x){this.x=x;}void setY(int y){this.y=y;}public boolean equalOrRev(Location e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(Location e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(Location e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;public class LocationRO{private int x;private int y;LocationRO(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}public boolean equalOrRev(LocationRO e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(LocationRO e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(LocationRO e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;import java.awt.*;import java.awt.event.*;import javax.swing.*;class SnakeFrame extends JFrame implements ActionListener{final SnakePanel p=new SnakePanel(this);JMenuBar menubar=new JMenuBar();JMenu fileMenu=new JMenu("文件");JMenuItem newgameitem=new JMenuItem("开始");JMenuItem stopitem=new JMenuItem("暂停");JMenuItem runitem=new JMenuItem("继续");JMenuItem exititem=new JMenuItem("退出");//"设置"菜单JMenu optionMenu=new JMenu("设置");//等级选项ButtonGroup groupDegree = new ButtonGroup();JRadioButtonMenuItem oneItem= new JRadioButtonMenuItem("初级");JRadioButtonMenuItem twoItem= new JRadioButtonMenuItem("中级");JRadioButtonMenuItem threeItem= new JRadioButtonMenuItem("高级");JMenu degreeMenu=new JMenu("等级");JMenu helpMenu=new JMenu("帮助");JMenuItem helpitem=new JMenuItem("操作指南");final JCheckBoxMenuItem showGridItem = new JCheckBoxMenuItem("显示网格");JLabel scorelabel;public JTextField scoreField;private long speedtime=200;private String helpstr = "游戏说明:\n1 :方向键控制蛇移动的方向."+"\n2 :单击菜单'文件->开始'开始游戏."+"\n3 :单击菜单'文件->暂停'或者单击键盘空格键暂停游戏."+"\n4 :单击菜单'文件->继续'继续游戏."+"\n5 :单击菜单'设置->等级'可以设置难度等级."+"\n6 :单击菜单'设置->显示网格'可以设置是否显示网格."+ "\n7 :红色为食物,吃一个得10分同时蛇身加长."+"\n8 :蛇不可以出界或自身相交,否则结束游戏.";SnakeFrame(){setJMenuBar(menubar);fileMenu.add(newgameitem);fileMenu.add(stopitem);fileMenu.add(runitem);fileMenu.add(exititem);menubar.add(fileMenu);oneItem.setSelected(true);groupDegree.add(oneItem);groupDegree.add(twoItem);groupDegree.add(threeItem);degreeMenu.add(oneItem);degreeMenu.add(twoItem);degreeMenu.add(threeItem);optionMenu.add(degreeMenu);// 风格选项showGridItem.setSelected(true);optionMenu.add(showGridItem);menubar.add(optionMenu);helpMenu.add(helpitem);menubar.add(helpMenu);Container contentpane=getContentPane();contentpane.setLayout(new FlowLayout());contentpane.add(p);scorelabel=new JLabel("得分: ");scoreField=new JTextField("0",15);scoreField.setEnabled(false);scoreField.setHorizontalAlignment(0);JPanel toolPanel=new JPanel();toolPanel.add(scorelabel);toolPanel.add(scoreField);contentpane.add(toolPanel);oneItem.addActionListener(this);twoItem.addActionListener(this);threeItem.addActionListener(this);newgameitem.addActionListener(this);stopitem.addActionListener(this);runitem.addActionListener(this);exititem.addActionListener(this);helpitem.addActionListener(this);showGridItem.addActionListener(this);}public void actionPerformed(ActionEvent e){try{if(e.getSource()==helpitem){JOptionPane.showConfirmDialog(p,helpstr,"操纵说明",JOptionPane.PLAIN_MESSAGE);}else if(e.getSource()==exititem)System.exit(0);else if(e.getSource()==newgameitem)p.newGame(speedtime);else if(e.getSource()==stopitem)p.stopGame();else if(e.getSource()==runitem)p.returnGame();else if(e.getSource()==showGridItem){if(!showGridItem.isSelected()){p.setBackground(Color.lightGray);}else{p.setBackground(Color.darkGray);}}else if(e.getSource()==oneItem) speedtime=200;else if(e.getSource()==twoItem) speedtime=100;else if(e.getSource()==threeItem) speedtime=50;}catch(Exception ee){ee.printStackTrace();}}}package snake;import java.util.*;import javax.swing.JOptionPane;public class SnakeModel {private int rows,cols;//行列数private Location snakeHead,runingDiriction;//运行方向private LocationRO[][] locRO;//LocationRO类数组private LinkedList snake,playBlocks;//蛇及其它区域块private LocationRO snakeFood;//目标食物private int gameScore=0; //分数private boolean AddScore=false;//加分// 获得蛇头public LocationRO getSnakeHead(){return (LocationRO)(snake.getLast());}//蛇尾public LocationRO getSnakeTail(){return (LocationRO)(snake.getFirst());}//运行路线public Location getRuningDiriction(){return runingDiriction;}//获得蛇实体区域public LinkedList getSnake(){return snake;}//其他区域public LinkedList getOthers(){return playBlocks;}//获得总分public int getScore(){return gameScore;}//获得增加分数public boolean getAddScore(){return AddScore;}//设置蛇头方向private void setSnakeHead(Location snakeHead){ this.snakeHead=snakeHead;}//获得目标食物public LocationRO getSnakeFood(){return snakeFood;}//随机设置目标食物private void setSnakeFood(){snakeFood=(LocationRO)(playBlocks.get((int)(Math.random()*playBlocks.size()))); }//移动private void moveTo(Object a,LinkedList fromlist,LinkedList tolist){fromlist.remove(a);tolist.add(a);}//初始设置public void init(){playBlocks.clear();snake.clear();gameScore=0;for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){playBlocks.add(locRO[i][j]);}}//初始化蛇的形状for(int i=4;i<7;i++){moveTo(locRO[4][i],playBlocks,snake);}//蛇头位置snakeHead=new Location(4,6);//设置随机块snakeFood=new LocationRO(0,0);setSnakeFood();//初始化运动方向runingDiriction=new Location(0,1);}//Snake构造器public SnakeModel(int rows1,int cols1){rows=rows1;cols=cols1;locRO=new LocationRO[rows][cols];snake=new LinkedList();playBlocks=new LinkedList();for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){locRO[i][j]=new LocationRO(i,j);}}init();}/**定义布尔型move方法,如果运行成功则返回true,否则返回false*参数direction是Location类型,*direction 的值:(-1,0)表示向上;(1,0)表示向下;*(0,-1)表示向左;(0,1)表示向右;**/public boolean move(Location direction){//判断设定的方向跟运行方向是不是相反if (direction.reverse(runingDiriction)){snakeHead.setX(snakeHead.getX()+runingDiriction.getX());snakeHead.setY(snakeHead.getY()+runingDiriction.getY());}else{snakeHead.setX(snakeHead.getX()+direction.getX());snakeHead.setY(snakeHead.getY()+direction.getY());}//如果蛇吃到了目标食物try{if ((snakeHead.getX()==snakeFood.getX())&&(snakeHead.getY()==snakeFood.getY())){moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);setSnakeFood();gameScore+=10;AddScore=true;}else{AddScore=false;//是否出界if((snakeHead.getX()<rows)&&(snakeHead.getY()<cols)&&(snakeHead.getX()>=0&&(snak eHead.getY()>=0))){//如果不出界,判断是否与自身相交if(snake.contains(locRO[snakeHead.getX()][snakeHead.getY()])){//如果相交,结束游戏JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束",RMA TION_MESSAGE);return false;}else{//如果不相交,就把snakeHead加到snake里面,并且把尾巴移出moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);moveTo(snake.getFirst(),snake,playBlocks);}}else{//出界,游戏结束JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", RMA TION_MESSAGE);return false;}}}catch(ArrayIndexOutOfBoundsException e){return false;}//设置运行方向if (!(direction.reverse(runingDiriction)||direction.equals(runingDiriction))){runingDiriction.setX(direction.getX());runingDiriction.setY(direction.getY());}return true;}}package snake;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;public class SnakePanel extends JPanel implements Runnable,KeyListener{JFrame parent=new JFrame();private int row=20; //网格行数private int col=30; //列数private JPanel[][] gridsPanel; //面板网格private Location direction;//方向定位private SnakeModel snake; //贪吃蛇private LinkedList snakeBody; //蛇的身体private LinkedList otherBlocks; //其他区域private LocationRO snakeHead; //蛇的头部private LocationRO snakeFood; //目标食物private Color bodyColor=Color.orange;//蛇的身体颜色private Color headColor=Color.black; //蛇的头部颜色private Color foodColor=Color.red; //目标食物颜色private Color othersColor=Color.lightGray;//其他区域颜色private int gameScore=0; //总分private long speed; //速度(难度设置)private boolean AddScore; //加分private Thread t; //线程private boolean isEnd; //暂停private static boolean notExit;// 构造器,初始化操作public SnakePanel(SnakeFrame parent){this.parent=parent;gridsPanel=new JPanel[row][col];otherBlocks=new LinkedList();snakeBody=new LinkedList();snakeHead=new LocationRO(0,0);snakeFood=new LocationRO(0,0);direction=new Location(0,1);// 布局setLayout(new GridLayout(row,col,1,1));for(int i=0;i<row;i++){for(int j=0;j<col;j++){gridsPanel[i][j]=new JPanel();gridsPanel[i][j].setBackground(othersColor);add(gridsPanel[i][j]);}}addKeyListener(this);}// 开始游戏public void newGame(long speed){this.speed=speed;if (notExit) {snake.init();}else{snake=new SnakeModel(row,col);notExit=true;t=new Thread(this);t.start();}requestFocus();direction.setX(0);direction.setY(1);gameScore=0;updateTextFiled(""+gameScore);isEnd=false;}// 暂停游戏public void stopGame(){requestFocus();isEnd=true;}// 继续public void returnGame(){requestFocus();isEnd=false;}// 获得总分public int getGameScore(){return gameScore;}//更新总分private void updateTextFiled(String str){((SnakeFrame)parent).scoreField.setText(str); }//更新各相关单元颜色private void updateColors(){// 设定蛇身颜色snakeBody=snake.getSnake();Iterator i =snakeBody.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(bodyColor);}//设定蛇头颜色snakeHead=snake.getSnakeHead();gridsPanel[snakeHead.getX()][snakeHead.getY()].setBackground(headColor);//设定背景颜色otherBlocks=snake.getOthers();i =otherBlocks.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(othersColor);}//设定临时块的颜色snakeFood=snake.getSnakeFood();gridsPanel[snakeFood.getX()][snakeFood.getY()].setBackground(foodColor); }public boolean isFocusTraversable(){return true;}//实现Runnable接口public void run(){while(true){try{Thread.sleep(speed);}catch (InterruptedException e){}if(!isEnd){isEnd=!snake.move(direction);updateColors();if(snake.getAddScore()){gameScore+=10;updateTextFiled(""+gameScore);}}}}//实现KeyListener接口public void keyPressed(KeyEvent event){int keyCode = event.getKeyCode();if(notExit){if (keyCode == KeyEvent.VK_LEFT) { //向左direction.setX(0);direction.setY(-1);}else if (keyCode == KeyEvent.VK_RIGHT) { //向右direction.setX(0);direction.setY(1);}else if (keyCode == KeyEvent.VK_UP) { //向上direction.setX(-1);direction.setY(0);}else if (keyCode == KeyEvent.VK_DOWN) { //向下direction.setX(1);direction.setY(0);}else if (keyCode == KeyEvent.VK_SPACE){ //空格键isEnd=!isEnd;}}}public void keyReleased(KeyEvent event){}public void keyTyped(KeyEvent event){}。
package com.huai;import Java.awt.Color;import java.awt.Graphics;import java.awt.Point;import java.util.HashSet;import java.util.LinkedList;import java.util.Set;import com.huai.listener.SnakeListener;import com.huai.util.Constant;public class Snake { //和蛇的监听器有关Set snakeListener=new HashSet(); //用链表保存蛇的身体节点 LinkedListbody=new LinkedList(); private boolean life=true; //默认速度为400ms private int speed=400; private Point lastTail=null; private boolean pause=false; //定义各个方向 public static final int UP=1; public static final int DOWN=-1; public static final int LEFT=2; public static final int RIGHT=-2; int newDirection=RIGHT; int oldDirection=newDirection; public Snake(){ initial(); } public void initial(){ //先清空所有的节点 body.removeAll(body); int x=Constant.WIDTH/2; int y=Constant.HEIGHT/2; //蛇的默认长度为7 for(int i=0; i < 7; i++){ body.add(new Point(x--, y)); } } public void setSpeed(int speed){ this.speed=speed; } public void setLife(boolean life){ this.life=life; } public boolean getLife(){ return this.life; } public boolean getPause(){ return this.pause; } public void setPause(boolean pause){ this.pause=pause; } public void move(){ //蛇移动的实现所采用的数据结构为蛇尾删除一个节点,蛇头增加一个节点。
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.snakeReDirection = 4;this.add( new Point( temp.x + 1, temp.y ) );break;case 3://downthis.snakeReDirection = 1;this.add( new Point( temp.x, temp.y + 1 ) );break;case 4://leftthis.snakeReDirection = 2;this.add( new Point( temp.x - 1, temp.y ) );break;}}public boolean checkBeanIn( Point bean ){Point temp = (Point) this.getLast();if( temp.equals( bean ) ){return true;}return false;}public void removeTail(){this.remove( 0 );}public void drawSnake( Graphics g, int singleWidthX, int singleHeightY, int cooPos ) {g.setColor( ColorGroup.COLOR_SNAKE );Iterator snakeSq = this.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawSnakePiece( g, tempPoint.x, tempPoint.y,singleWidthX, singleHeightY, cooPos );}}public void drawSnakePiece( Graphics g, int temp1, int temp2,int singleWidthX, int singleHeightY, int cooPos ){g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}public void clearEndSnakePiece( Graphics g, int temp1, int temp2, int singleWidthX, int singleHeightY, int cooPos ){g.setColor( ColorGroup.COLOR_BACK );g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}}GameFrame.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.awt.geom.*;class GameFrame extends JFrame{private Toolkit tempKit;private int horizontalGrid, verticalGrid;private int singleWidthX, singleHeightY;private int cooPos;private Snake mainSnake;private LinkedList eatedBean;{eatedBean = new LinkedList();}private Iterator snakeSq;public javax.swing.Timer snakeTimer;private int direction = 2;private int score;private String info;private Point bean, eatBean;{bean = new Point();}private boolean flag;private JMenuBar infoMenu;private JMenu[] tempMenu;private JMenuItem[] tempMenuItem;private JRadioButtonMenuItem[] levelMenuItem, versionMenuItem;private JLabel scoreLabel;{scoreLabel = new JLabel();}private Graphics2D g;private ImageIcon snakeHead;{snakeHead = new ImageIcon( "LOGO.gif" );}private ConfigMenu configMenu;private boolean hasStoped = true;public GameFrame(){this.tempKit = this.getToolkit();this.setSize( tempKit.getScreenSize() );this.setGrid( 60, 40, 5 );this.getContentPane().setBackground( ColorGroup.COLOR_BACK );this.setUndecorated( true );this.setResizable( false );this.addKeyListener( new KeyHandler() );GameFrame.this.snakeTimer = new javax.swing.Timer( 80, new TimerHandler() ); this.getContentPane().add( scoreLabel, BorderLayout.SOUTH );this.scoreLabel.setFont( new Font( "Fixedsys", Font.BOLD, 15 ) );this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );this.configMenu = new ConfigMenu( this );this.setVisible( true );}public void setGrid( int temp1, int temp2, int temp3 ){this.horizontalGrid = temp1;this.verticalGrid = temp2;this.singleWidthX = this.getWidth() / temp1;this.singleHeightY = this.getHeight() / temp2;this.cooPos = temp3;}private class KeyHandler extends KeyAdapter{public void keyPressed( KeyEvent e ){if( e.getKeyCode() == 27 ){snakeTimer.stop();if( JOptionPane.showConfirmDialog( null, "Are you sure to exit?" ) == 0 ) {System.exit( 0 );}snakeTimer.start();}else if( e.getKeyCode() == 37 && mainSnake.snakeDirection != 2 )//left {direction = 4;}else if( e.getKeyCode() == 39 && mainSnake.snakeDirection != 4 )//right {direction = 2;}else if( e.getKeyCode() == 38 && mainSnake.snakeDirection != 3 )//up {direction = 1;}else if( e.getKeyCode() == 40 && mainSnake.snakeDirection != 1 )//down {direction = 3;}else if( e.getKeyCode() == 32 ){if( !hasStoped ){if( !flag ){snakeTimer.stop();configMenu.setVisible( true );configMenu.setMenuEnable( false );flag = true;}else{snakeTimer.start();configMenu.setVisible( false );configMenu.setMenuEnable( true );flag = false;}}}}}private class TimerHandler implements ActionListener{public synchronized void actionPerformed( ActionEvent e ){Point temp = (Point) mainSnake.getLast();snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();if( temp.equals( tempPoint ) && snakeSq.hasNext() != false ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "\n\nYou Loss!" );}}System.out.println( temp.x + " " + temp.y );if( (temp.x == 0 && direction == 4) ||(temp.x == horizontalGrid-1 && direction == 2) ||(temp.y == 0 && direction == 1) ||(temp.y == verticalGrid-1 && direction == 3) ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "\n\nYou Loss!" );}if( direction != mainSnake.snakeReDirection ){moveSnake( direction );}mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); drawBeanAndEBean( getGraphics() );}}public void stopGame(){this.hasStoped = true;this.snakeTimer.stop();Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );configMenu.setVisible( true );}public void resetGame(){System.gc();this.hasStoped = false;Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );this.mainSnake = new Snake();this.createBean( bean );this.eatedBean.clear();mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); this.snakeTimer.start();this.direction = 2;this.score = 0;this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );}private void moveSnake( int direction ){if( mainSnake.checkBeanIn( this.bean ) ){this.score += 100;this.scoreLabel.setText( + " Current Score:" + this.score );this.eatedBean.add( new Point(this.bean) );this.createBean( this.bean );}mainSnake.changeDirection( (Point) mainSnake.getLast(), direction );Point temp = (Point) mainSnake.getFirst();if( eatedBean.size() != 0 ){if( eatedBean.getFirst().equals( temp ) ){eatedBean.remove( 0 );}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}private void drawBeanAndEBean( Graphics g ){g.setColor( ColorGroup.COLOR_BEAN );this.drawPiece( g, this.bean.x, this.bean.y );g.setColor( ColorGroup.COLOR_EATEDBEAN );snakeSq = eatedBean.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawPiece( g, tempPoint.x, tempPoint.y );}}private void drawPiece( Graphics g, int x, int y ){g.fillRoundRect( this.singleWidthX * x + 1,this.singleHeightY * y + 1,this.singleWidthX - 2,this.singleHeightY - 2,this.cooPos,this.cooPos );}private void createBean( Point temp ){LP:while( true ){temp.x = (int) (Math.random() * this.horizontalGrid);temp.y = (int) (Math.random() * this.verticalGrid);snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){if( snakeSq.next().equals( new Point( temp.x, temp.y ) ) ){continue LP;}}break;}}}ConfigMenu.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ConfigMenu extends JMenuBar{GameFrame owner;JMenu[] menu;JMenuItem[] menuItem;JRadioButtonMenuItem[] speedItem, modelItem, standardItem; private UIManager.LookAndFeelInfo looks[];public ConfigMenu( GameFrame owner ){this.owner = owner;owner.setJMenuBar( this );String[] menu_name = {"Snake Game", "Game Configure", "Game Help"}; menu = new JMenu[menu_name.length];for( int i = 0; i < menu_name.length; i++ ){menu[i] = new JMenu( menu_name[i] );menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );this.add( menu[i] );}String[] menuItem_name = {"Start Game", "Stop Game", "Exit Game", "Game Color","About..."};menuItem = new JMenuItem[menuItem_name.length];for( int i = 0; i < menuItem_name.length; i++ ){menuItem[i] = new JMenuItem( menuItem_name[i] );menuItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) ); menuItem[i].addActionListener( new ActionHandler() );}menu[0].add( menuItem[0] );menu[0].add( menuItem[1] );menu[0].addSeparator();menu[0].add( menuItem[2] );menu[1].add( menuItem[3] );menu[2].add( menuItem[4] );String[] inner_menu_name = {"Game Speed", "Window Model", "Game Standard "}; JMenu[] inner_menu = new JMenu[inner_menu_name.length];for( int i = 0; i < inner_menu_name.length; i++ ){inner_menu[i] = new JMenu( inner_menu_name[i] );inner_menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );menu[1].add( inner_menu[i] );}ButtonGroup temp1 = new ButtonGroup();String[] speedItem_name = {"Speed-1", "Speed-2", "Speed-3", "Speed-4", "Speed-5"}; speedItem = new JRadioButtonMenuItem[speedItem_name.length];for( int i = 0; i < speedItem_name.length; i++ ){speedItem[i] = new JRadioButtonMenuItem( speedItem_name[i] );inner_menu[0].add( speedItem[i] );speedItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );speedItem[i].addItemListener( new ItemHandler() );temp1.add( speedItem[i] );}ButtonGroup temp2 = new ButtonGroup();String[] modelItem_name = { "Linux", "Mac", "Windows" };modelItem = new JRadioButtonMenuItem[modelItem_name.length];for( int i = 0; i < modelItem_name.length; i++ ){modelItem[i] = new JRadioButtonMenuItem( modelItem_name[i] );inner_menu[1].add( modelItem[i] );modelItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );modelItem[i].addItemListener( new ItemHandler() );temp2.add( modelItem[i] );}ButtonGroup temp3 = new ButtonGroup();String[] standardItem_name = { "60 * 40", "45 * 30", "30 * 20" };standardItem = new JRadioButtonMenuItem[standardItem_name.length];for( int i = 0; i < standardItem_name.length; i++ ){standardItem[i] = new JRadioButtonMenuItem( standardItem_name[i] );inner_menu[2].add( standardItem[i] );standardItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );standardItem[i].addItemListener( new ItemHandler() );temp3.add( standardItem[i] );}looks = UIManager.getInstalledLookAndFeels();}private class ActionHandler implements ActionListener{public void actionPerformed( ActionEvent e ){if( e.getSource() == menuItem[0] ){owner.resetGame();ConfigMenu.this.setVisible( false );}else if( e.getSource() == menuItem[1] ){owner.stopGame();ConfigMenu.this.setVisible( true );ConfigMenu.this.setMenuEnable( true );}else if( e.getSource() == menuItem[2] ){System.exit( 0 );}else if( e.getSource() == menuItem[3] ){ConfigDialog temp = new ConfigDialog( owner );temp.setVisible( true );}else if( e.getSource() == menuItem[4] ){JOptionPane.showMessageDialog( null, "Sanke Game 2.0 Version!\n\n" + "Author: FinalCore\n\n" );}}}private class ItemHandler implements ItemListener{public void itemStateChanged( ItemEvent e ){for( int i = 0; i < speedItem.length; i++ ){if( e.getSource() == speedItem[i] ){owner.snakeTimer.setDelay( 150 - 30 * i );}}if( e.getSource() == standardItem[0] ){owner.setGrid( 60, 40, 5 );}else if( e.getSource() == standardItem[1] ){owner.setGrid( 45, 30, 10 );}else if( e.getSource() == standardItem[2] ){owner.setGrid( 30, 20, 15 );}for( int i = 0; i < modelItem.length; i++ ){if( e.getSource() == modelItem[i] ){try{UIManager.setLookAndFeel( looks[i].getClassName() ); }catch(Exception ex){}}}}}public void setMenuEnable( boolean temp ){menu[1].setEnabled( temp );}}。
java实现贪吃蛇游戏代码(附完整源码)先给⼤家分享源码,喜欢的朋友。
游戏界⾯GUI界⾯java实现贪吃蛇游戏需要创建⼀个桌⾯窗⼝出来,此时就需要使⽤java中的swing控件创建⼀个新窗⼝JFrame frame = new JFrame("贪吃蛇游戏");//设置⼤⼩frame.setBounds(10, 10, 900, 720);向窗⼝中添加控件可以直接⽤add⽅法往窗⼝中添加控件这⾥我创建GamePanel类继承⾃Panel,最后使⽤add⽅法添加GamePanel加载图⽚图⽚加载之后可以添加到窗⼝上public static URL bodyUrl = GetImage.class.getResource("/picture/body.png");public static ImageIcon body = new ImageIcon(bodyUrl);逻辑实现//每次刷新页⾯需要进⾏的操作@Overridepublic void actionPerformed(ActionEvent e) {//当游戏处于开始状态且游戏没有失败时if(gameStart && !isFail) {//蛇头所在的位置就是下⼀次蛇⾝体的位置bodyX[++bodyIndexRight] = headX;bodyY[bodyIndexRight] = headY;//bodyIndexLeft++;//长度到达数组的尾部if(bodyIndexRight==480) {for(int i=bodyIndexLeft, j=0; i<=bodyIndexRight; i++,j++) {bodyX[j]=bodyX[i];bodyY[j]=bodyY[i];}bodyIndexLeft=0;bodyIndexRight=length-1;}//更新头部位置if(fdirection==1) {//头部⽅向为上,将蛇头向上移动⼀个单位headY-=25;}else if(fdirection==2) {//头部⽅向为下,将蛇头向下移动⼀个单位headY+=25;}else if(fdirection==3) {//头部⽅向为左,将蛇头向左移动⼀个单位headX-=25;}else if(fdirection==4) {//头部⽅向为右,将蛇头向右移动⼀个单位headX+=25;}//当X坐标与Y坐标到达极限的时候,从另⼀端出来if(headX<25)headX = 850;if(headX>850)headX = 25;if(headY<75)headY = 650;if(headY>650)headY = 75;//当头部坐标和⾷物坐标重合时if(headX==foodX && headY==foodY){length++;score+=10;//重新⽣成⾷物,判断⾷物坐标和蛇⾝坐标是否重合,效率较慢while(true) {foodX = 25 + 25* random.nextInt(34);foodY = 75 + 25* random.nextInt(24);//判断⾷物是否和头部⾝体重合boolean isRepeat = false;//和头部重合if(foodX == headX && foodY == headY)isRepeat = true;//和⾝体重合for(int i=bodyIndexLeft; i<=bodyIndexRight; i++) {if(foodX == bodyX[i] && foodY == bodyY[i]){isRepeat = true;}}//当不重复的时候,⾷物⽣成成功,跳出循环if(isRepeat==false)break;}}else bodyIndexLeft++;//判断头部是否和⾝体重合for(int i=bodyIndexLeft; i<=bodyIndexRight;i++) {if(headX==bodyX[i] && headY==bodyY[i]){//游戏失败isFail = true;break;}}repaint();}timer.start();}键盘监听实现KeyListener接⼝,重写KeyPressed⽅法,在其中写当键盘按下时所对应的操作。
package Game;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.*;public class she extends JFrame{MyPaint mp=null;public static void main(String[] args) {she she=new she();}public she(){mp=new MyPaint();Thread t1=new Thread(mp);//启动mp线程t1.start();this.add(mp);//加载面板this.addKeyListener(mp);//加载按键监听this.setSize(300,320);//窗口大小this.setLocationRelativeTo(null); //居中this.setTitle("贪吃蛇V1.0");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//点击关闭时,关闭程序this.setVisible(true);//可见}}class MyPaint extends JPanel implements KeyListener,Runnable{ yidong yd=new yidong();public void paint (Graphics g){super.paint(g);g.setColor(Color.ORANGE);g.fillRect(0, 0, 300, 260);g.setColor(Color.black);g.fillOval(yd.swx, yd.swy, 20, 20);g.setColor(Color.red);g.fillOval(yd.x[0], yd.y[0], 20, 20);//蛇头显示g.setColor(Color.blue);for(int i=1;i<yd.sum-1;i++){//蛇身体显示g.fillOval(yd.x[i], yd.y[i], 20, 20);}g.drawString("当前分数: "+yd.fenshu, 190, 275);g.drawString("速度等级: "+yd.lv, 10, 275);g.setColor(Color.white);if(yd.kaishi==0){ //当游戏结束时显示g.setFont(new Font("黑体",1,20));g.drawString("Game over", 90, 100);g.setFont(new Font("幼体",1,15));g.drawString("按Z键继续游戏!", 80, 120);}}public void keyPressed(KeyEvent e) {if(yd.kaishi==1){//当游戏进行时可控制if(e.getKeyCode()==KeyEvent.VK_UP){if(yd.fx!=2){yd.fx=8;}}else if(e.getKeyCode()==KeyEvent.VK_DOWN){if(yd.fx!=8){yd.fx=2;}}else if(e.getKeyCode()==KeyEvent.VK_LEFT){if(yd.fx!=6){yd.fx=4;}}else if(e.getKeyCode()==KeyEvent.VK_RIGHT){if(yd.fx!=4){yd.fx=6;}}}else{//当游戏结束时按Z 恢复游戏if(e.getKeyCode()==KeyEvent.VK_Z){yd.sum=4;yd.x[0]=100;yd.y[0]=100;yd.x[1]=80;yd.y[1]=100;yd.x[2]=60;yd.y[2] =100;yd.yanchi=200;yd.kaishi=1;yd.fx=6;yd.nfx=6;yd.sp=20;}}}public void keyReleased(KeyEvent arg0) {}public void keyTyped(KeyEvent arg0) {}public void run() { //刷新面板线程Thread t2=new Thread(yd);t2.start();while(true){try {Thread.sleep(10);}catch (InterruptedException e) {e.printStackTrace();}this.repaint();}}}class yidong implements Runnable{ //蛇移动线程int maxsum=128,sum=4,x[]=new int[maxsum],y[]=new int[maxsum],kaishi=1; //sum:代表蛇的总共长度是sum-1int fx=1,nfx,sp=20,i=0,yanchi=200,fenshu;//方向fx :4=←6=→8=↑ 2=↓其余:无移动int swx=0,swy=0,shiwu=0;String lv="1";Random sj=new Random();@Overridepublic void run() {x[0]=100;y[0]=100;//初始化蛇坐标while(true){try {Thread.sleep(yanchi);}catch (InterruptedException e) {e.printStackTrace();}if(shiwu==0){//随机产生食物swx=(sj.nextInt(10)+1)*20;swy=(sj.nextInt(10)+1)*20;shiwu=1; }if(kaishi==1){fenshu=sum*100-400;}//分数计算for(int i=sum-1;i>0;i--){//身体坐标刷新x[i]=x[i-1];y[i]=y[i-1];}if(fx==6&&nfx!=4){//方向判断x[0]+=sp;//移动nfx=6;}else if(fx==4&&nfx!=6){x[0]-=sp;nfx=4;}else if(fx==2&&nfx!=8){y[0]+=sp;nfx=2;}else if(fx==8&&nfx!=2){y[0]-=sp;nfx=8;}else{if(nfx==6){x[0]+=sp;}if(nfx==4){x[0]-=sp;}if(nfx==2){y[0]+=sp;}if(nfx==8){y[0]-=sp;}}if(x[0]>270){x[0]-=sp;}if(x[0]<0){x[0]+=sp;}if(y[0]>255){y[0]-=sp;}if(y[0]<0){y[0]+=sp;}if(x[0]>swx-5&&x[0]<swx+5&&y[0]>swy-5&&y[0]<swy+5){sum++;//增加长度shiwu=0;if(sum==10){yanchi=180;lv="2";}//加速if(sum==20){yanchi=160;lv="3";}if(sum==30){yanchi=150;lv="4";}if(sum==40){yanchi=140;lv="5";}if(sum==50){yanchi=130;lv="max";}}for(int i=sum-1;i>0;i--){//判断蛇是否吃到自己if(x[0]>x[i]-5&&x[0]<x[i]+5&&y[0]>y[i]-5&&y[0]<y[i]+5){sp=0;yanchi=500;kaishi=0;}}}}}。
2013-2014学年第二学期《面向对象程序设计》课程设计报告题目:贪吃蛇游戏与程序设计专业:网络工程班级:12级一班**:***指导教师:***成绩:计算机与信息工程系2014年 6月 10日目录1. 设计内容及要求 (2)1.1设计内容 (2)1.2设计任务及具体要求 (2)2. 概要设计 (3)3. 设计过程 (3)3.1开发环境和软件 (3)3.2总体程序流程图 (3)3.2.1主类贪吃蛇 (4)3.2.2类SnakeFrame (5)3.2.3类贪吃蛇 (5)3.2.4类Paint (6)4.运行结果如所示 (6)游戏结束 (7)5.参考文献 (8)源程序 (8)1.设计内容及要求1.1设计内容本软件是针对贪吃蛇小游戏的JAVA程序,利用方向键来改变蛇的运行方向,空格键暂停或继续游戏,并在随机的地方产生食物,吃到食物就变成新的蛇体,碰到壁或自身则游戏结束,否则正常运行。
1.2设计任务及具体要求本游戏用户可以自己练习和娱乐。
本游戏需要满足以下几点要求:(1)利用方向键来改变蛇的运行方向。
(2)空格键暂停游戏,并在随机的地方产生食物。
(3)吃到食物就变成新的蛇体,碰到壁或自身则游戏结束,否则正常运行。
(4)用户可以根据需要暂停,以及根据水平选择不同的游戏难度。
要求:明确课程设计的目的,能根据课程设计的要求,查阅相关文献,为完成设计准备必要的知识;提高学生用java语言进行程序设计的能力,初步了解软件开发的一般方法和步骤;提高撰写技术文档的能力。
2. 概要设计游戏大体框架如图3. 设计过程3.1开发环境和软件(1)操作系统:Windows 7(2)Java开发工具:Eclipse3.2总体程序流程图新建游戏的启动窗口public class SnakeGame {public static void main(String[] args) {SnakeFrame frame = new SnakeFrame(); frame.setTitle("贪吃蛇");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);}}3.2.1主类贪吃蛇(1)主类为此程序的入口,定义了贪吃蛇的对象Frame,开始运行程序(2)源程序见详细代码成员变量描述变量类型名称是否运动Boolean isrun蛇体ArrayList<NODE> body食物Node food方向int drection分数int score速度int Speed状态Int StatusRunning运动中Public static finalintLeft左Public static finalint右Public static finalRightint上Public static finalUPint(1)成员变量见表2(2)方法见表3(1)成员变量见表4int速度Public static finalint SLOW,MID,FAST(2)方法见表五表格 4 主要方法方法名功能Iseating() 吃食物Isbang() 是否碰撞到墙壁,或自己Changedirecte() 判断是否吃到食物,判断是否改变方向Makefood() 在随机的地方产生食物Move() 蛇如何移动3.2.4类Paint此类为画蛇的面板类,是粉色蛇身算法的类。
import java.awt.Color;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.InputEvent;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JCheckBoxMenuItem;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.KeyStroke;public class 贪吃蛇extends JFrame implements ActionListener, KeyListener,Runnable { /****/private static final long serialVersionUID = 1L;private JMenuBar menuBar;private JMenu youXiMenu,nanDuMenu,fenShuMenu,guanYuMenu;private JMenuItem kaiShiYouXi,exitItem,zuoZheItem,fenShuItem;private JCheckBoxMenuItem cJianDan,cPuTong,cKunNan;private int length = 6;private Toolkit toolkit;private int i,x,y,z,objectX,objectY,object=0,growth=0,time;//bojectX,Yprivate int m[]=new int[50];private int n[]=new int[50];private Thread she = null;private int life=0;private int foods = 0;private int fenshu=0;public void run(){time=500;for(i=0;i<=length-1;i++){m[i]=90-i*10;n[i]=60;}x=m[0];y=n[0];z=4;while(she!=null){check();try{Thread.sleep(time);}catch(Exception ee){System.out.println(z+"");}}}public 贪吃蛇() {setVisible(true);menuBar = new JMenuBar();toolkit=getToolkit();youXiMenu = new JMenu("游戏"); kaiShiYouXi = new JMenuItem("开始游戏"); exitItem = new JMenuItem("退出游戏");nanDuMenu = new JMenu("困难程度"); cJianDan = new JCheckBoxMenuItem("简单"); cPuTong = new JCheckBoxMenuItem("普通"); cKunNan = new JCheckBoxMenuItem("困难");fenShuMenu = new JMenu("积分排行"); fenShuItem = new JMenuItem("最高记录");guanYuMenu = new JMenu("关于");zuoZheItem = new JMenuItem("关于作者");guanYuMenu.add(zuoZheItem);nanDuMenu.add(cJianDan);nanDuMenu.add(cPuTong);nanDuMenu.add(cKunNan);fenShuMenu.add(fenShuItem);youXiMenu.add(kaiShiYouXi);youXiMenu.add(exitItem);menuBar.add(youXiMenu);menuBar.add(nanDuMenu);menuBar.add(fenShuMenu);menuBar.add(guanYuMenu);zuoZheItem.addActionListener(this);kaiShiYouXi.addActionListener(this);exitItem.addActionListener(this);addKeyListener(this);fenShuItem.addActionListener(this);KeyStroke keyOpen = KeyStroke.getKeyStroke('O',InputEvent.CTRL_DOWN_MASK); kaiShiYouXi.setAccelerator(keyOpen);KeyStroke keyExit = KeyStroke.getKeyStroke('X',InputEvent.CTRL_DOWN_MASK); exitItem.setAccelerator(keyExit);setJMenuBar(menuBar);setTitle("贪吃蛇");setResizable(false);setBounds(300,200,400,400);validate();setDefaultCloseOperation(EXIT_ON_CLOSE);}public static void main(String args[]) {new 贪吃蛇();}public void actionPerformed(ActionEvent e){if(e.getSource()==kaiShiYouXi){length = 6;foods = 0;if(she==null){she=new Thread(this);she.start();}else if(she!=null){she=null;she= new Thread(this);she.start();}}if(e.getSource()==exitItem){System.exit(0);}if(e.getSource()==zuoZheItem){JOptionPane.showMessageDialog(this, "孤独的野狼制作"+"\n\n"+" "+"QQ号:2442701497"+"\n");}if(e.getSource()==fenShuItem){JOptionPane.showMessageDialog(this,"最高记录为"+fenshu+"");}}public void check(){isDead();if(she!=null){if(growth==0){reform(); //得到食物}else{upgrowth(); //生成食物}if(x==objectX&&y==objectY){growth=1;toolkit.beep();}if(object==0){object=1;objectX=(int)Math.floor(Math.random()*39)*10;objectY=(int)Math.floor(Math.random()*29)*10+50;}this.repaint(); //重绘}}void isDead(){//判断游戏是否结束的方法if(z==4){x=x+10;}else if(z==3){x=x-10;}else if(z==2){y=y+10;}else if(z==1){y=y-10;}if(x<0||x>390||y<50||y>390){she=null;}for(i=1;i<length;i++){if(m[i]==x&&n[i]==y){she=null;}}}public void upgrowth() {//当蛇吃到东西时的方法if(length<50){length++;}growth--;time=time-10;reform();life+=100;if(fenshu<life){fenshu = life;}foods++;}public void reform(){for(i=length-1;i>0;i--) {m[i]=m[i-1];n[i]=n[i-1];}if(z==4){m[0]=m[0]+10;}if(z==3){m[0]=m[0]-10;}if(z==2){n[0]=n[0]+10;}if(z==1){n[0]=n[0]-10;}}{if(she!=null){if(e.getKeyCode()==KeyEvent.VK_UP){if(z!=2){z=1;check();}}else if(e.getKeyCode()==KeyEvent.VK_DOWN) {if(z!=1){z=2;check();}}else if(e.getKeyCode()==KeyEvent.VK_LEFT){if(z!=4){z=3;check();}}else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {if(z!=3){z=4;check();}}}}public void keyReleased(KeyEvent e){}{}public void paint(Graphics g) {g.setColor(Color.DARK_GRAY); //设置背景g.fillRect(0,50,400,400);g.setColor(Color.pink);for(i=0;i<=length-1;i++){g.fillRect(m[i],n[i],10,10);}g.setColor(Color.green); //蛇的食物g.fillRect(objectX,objectY,10,10);g.setColor(Color.white);g.drawString("当前分数"+this.life,6,60);g.drawString("当前已吃食物数"+this.foods,6,72); }}。