贪吃蛇java源代码

合集下载

用Java做的贪吃蛇,简单版......

用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源代码完整版

游戏贪吃蛇的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程序源代码(贪吃蛇)

JAVA程序源代码(贪吃蛇)

贪吃蛇源代码将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){}}。

贪吃蛇源代码

贪吃蛇源代码

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简单贪吃蛇代码

java简单贪吃蛇代码

/** 贪吃蛇*/import java.awt.*; //包含文件import javax.swing.*;import java.awt.event.*;public class GreedSnack extends JFrame{int i,j;WH_panel panel; //定义WH_panel的实例JMenuBar wh_bar; //定义菜单实例public GreedSnack() //构造函数{super("贪吃蛇--game--"); //框架名称Container c=getContentPane(); //获得框架容器setBounds(200, 200, 620, 465); //设置frame的大小c.setLayout(null); //设置框架布局wh_bar=new JMenuBar(); //定义菜单实例setJMenuBar(wh_bar); //设置菜单JMenu[]m={new JMenu("文件"),new JMenu("编辑")}; //主菜单JMenuItem[][]mi={ //下拉菜单项{new JMenuItem("开始"),new JMenuItem("退出")}, //设计菜单的内容{new JMenuItem("分数"),new JMenuItem("记录分")}};for(i=0;i<m.length;i++) //添加菜单{wh_bar.add(m[i]); //添加下拉菜单for(j=0;j<mi[i].length;j++) //小于菜单的长度{m[i].add(mi[i][j]); //添加} //for } //formi[0][0].addActionListener(new ActionListener() //设置菜单监听{public void actionPerformed(ActionEvent e) //{try{panel.thread.start(); //开始线程panel.right(); //直接执行right函数}catch(Exception ee){} //对线程进行捕获错误}});addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e) //键盘监听{if(e.getKeyCode()==KeyEvent.VK_LEFT) //监听左键panel.left(); //执行left函数if(e.getKeyCode()==KeyEvent.VK_RIGHT) //监听右键panel.right(); //执行right函数if(e.getKeyCode()==KeyEvent.VK_UP) //监听上键panel.up(); //执行up函数if(e.getKeyCode()==KeyEvent.VK_DOWN) //监听下键panel.down(); //执行down函数} //键盘事件public void keyTyped(KeyEvent e) {}public void keyReleased(KeyEvent e) {}});panel=new WH_panel();panel.setLayout(null); //panel布局c.add(panel); //添加panel}public static void main(String args[]) //主函数{GreedSnack app=new GreedSnack(); //设置frame的实例app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口app.setVisible(true); //设置成可见} //main}//greedsnackclass WH_panel extends JPanel implements Runnable //panel函数{Thread thread; //定义线程int x=0,y=0,wh_direct=0; //设置变量int food_x=60,food_y=80; //初始食物的位置int d_l,d_r,d_u,d_d; //定义行使方向int i,j,wh_stop;int food_date; //定义食物数int [][]wh_array=new int[30][20]; //定义数组public WH_panel() //构造函数{this.setBounds(0, 0,600,400); //设置panel的大小thread=new Thread(this); //创建线程threadfor(i=0;i<30;i++) //给数组付初值{for(j=0;j<20;j++) //列标小于20{wh_array[i][j]=0; //将数组赋为0 } //for } //for }//WH_panel()public void left() //left函数{if(d_r!=3) //假设现在向右行进{wh_direct=1; //wh_direct 为1d_l=1; //标记左不能运行d_r=3;d_u=0; //标记上可以运行d_d=0; //标记下可以运行}else //假设现在不是向右行进{d_l=0; //向左可以运行}}public void right() //右键函数{if(d_l!=1) //假设现在向左行进{wh_direct=2; //wh_direct为2d_l=1;d_r=3; //向右不可以运行d_u=0; //向上可以运行d_d=0; //向下可以运行}else //假设没有向左行进{d_r=0; //向右可以运行}}public void up() //向上键函数{if(d_d!=7) //假设现在向下行进{wh_direct=3; //wh_direct 为3d_u=5; //向上不可以运行d_d=7;d_l=0; //向左可以行进d_r=0; //向右可以运行}else //假设现在没有向下运行{d_u=0; //可以向上行进}}public void down() //向下键的函数{if(d_u!=5) //如果现在向上运行{wh_direct=4; //wh_direct为4d_u=5;d_d=7; //现在不可向下行进d_r=0; //现在可向右行进d_l=0; //现在向左行进}else //如果现在没有向上行进{d_d=0; //可以向下行进}}public void run() //线程函数{while(true) //while循环{if(wh_direct==1) //向左方{if(x>=20&&y>=0&&x<=580&&y<=380) //规定范围if(wh_array[x/20-1][y/20]!=0) //当下一个有蛇身{wh_stop=1; //wh_stop=1}x=x-20; //x坐标减小变化wh_run();}if(wh_direct==2) //向右方{if(x>=0&&y>=0&&x<=560&&y<=380) //规定范围if(wh_array[x/20+1][y/20]!=0) //当下一个有蛇身{wh_stop=1; //wh_stop=1}x=x+20; //x坐标增大变化wh_run();}if(wh_direct==3) //向上方{if(x>=0&&y>=20&&x<=580&&y<=380) //规定范围if(wh_array[x/20][y/20-1]!=0) //当下一个有蛇身{wh_stop=1; //wh_stop=1}y=y-20; //y坐标减小变化wh_run();}if(wh_direct==4) //向下方{if(x>=0&&y>=0&&x<=580&&y<=360) //规定范围if(wh_array[x/20][y/20+1]!=0) //当下一个有蛇身{wh_stop=1; //wh_stop=1 }y=y+20; //y坐标增大变化wh_run();}if(food_x==x&&food_y==y) //蛇头的坐标与食物相同{food_x=((int)(Math.random()*30))*20; //随机食物坐标Xfood_y=((int)(Math.random()*20))*20; //随机食物坐标Yrepaint(); //刷新绘图food_date=food_date+1; //食物数进行自加}if(x==600||y==400||x<0||y<0||wh_stop==1) //到达边界跳出循环{break;}}}public void wh_run() //蛇身行进函数{/** 此函数为贪吃蛇的重点函数,实现蛇身的各种变化,主要思路是:* 将面板分割成20X30的数组,并将其初始值赋为0,每次将蛇头* 值赋为1,然后对数组非0的数进行加1操作,若数组内的值大于* 蛇本身应有的长度,就将其值改为0,最后对数组不为0的进行绘* 图。

贪吃蛇游戏源代码

贪吃蛇游戏源代码
mainFrame.setVisible(true);
begin();
}
//----------------------------------------------------------------------
//keyPressed():按键检测
//----------------------------------------------------------------------
void begin()
{
if(snakeModel==null||!snakeModel.running)
{
snakeModel=new SnakeModel(this,canvasWidth/nodeWidth,
this.canvasHeight/nodeHeight);
(new Thread(snakeModel)).start();
//GreedSnake():初始化游戏界面
//----------------------------------------------------------------------
public GreedSnake()
{
//设置界面元素
mainFrame=new JFrame("GreedSnake");
*要点分析:
*1)数据结构:matrix[][]用来存储地图上面的信息,如果什么也没有设置为false,
* 如果有食物或蛇,设置为true;nodeArray,一个LinkedList,用来保存蛇的每
* 一节;food用来保存食物的位置;而Node类是保存每个位置的信息。

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 代码

贪吃蛇 Java 代码
}
}
// 打印食物到地图上
public void showFood(Graphics g) {
// tempImage = createImage(WIDTH, HEIGHT);
// Graphics g = tempImage.getGraphics();
// ground[food.x][food.y] = true;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.KeyAdapter;
}
break;
case (DOWN_DIRECTION):
if (head.y == HEIGHT - 1) {
snake.addFirst(new Point(head.x, 0));
} else {
snake.addFirst(new Point(head.x, head.y + 1));
switch (currentDirection) {
case (UP_DIRECTION):
if (head.y == 0) {
snake.addFirst(new Point(head.x, HEIGHT - 1));
} else {
snake.addFirst(new Point(head.x, head.y - 1));
// food = new Point(x, y);

Java贪吃蛇游戏源代码

Java贪吃蛇游戏源代码

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贪吃蛇 代码

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课程设计-贪吃蛇代码

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代码

贪吃蛇Java代码

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();}}。

java 贪吃蛇 代码

java 贪吃蛇 代码
this.setOpaque(true);
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小程序—贪吃蛇源代码

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 + "&#92;n&#92;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 + "&#92;n&#92;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!&#92;n&#92;n" + "Author: FinalCore&#92;n&#92;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实现贪吃蛇游戏代码(附完整源码)

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

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⽅法,在其中写当键盘按下时所对应的操作。

用java编写的贪吃蛇游戏代码[资料]

用java编写的贪吃蛇游戏代码[资料]

用java编写的贪吃蛇游戏代码[资料] 用Java编写的贪吃蛇代码下面是我用java编写的一个贪吃蛇游戏源代码.我个人是比较喜欢玩游戏的,所以学习编程二年多了,很想做个游戏程序,由于能力有限,一直没能做好,后来突然看同学在手机上玩“贪吃蛇”,故想做出来,其一是因为此游戏界面容易设计,算法也比较简单,今天我就把我程序的代码和算法介绍一下,顺便把程序界面皮肤设计说一下......程序中一个关于游戏信息的类如下,由于类的说明在程序中写的很清楚了,就不再多解释了:#include "time.h"//方向定义const CPoint UP(CPoint(0,-1));const CPoint DOWN(CPoint(0,1));const CPoint LEFT(CPoint(-1,0));const CPoint RIGHT(CPoint(1,0));//速度快慢定义const int HIGH = 75;const int NORMAL = 180;const int SLOW = 300;const int MAX = 80; //表示转向数const int LENGTH = 10;class GameMsg{public:GameMsg(void): m_icon(0){InitGame();}void InitGame(int up = VK_UP, int down = VK_DOWN, int left = VK_LEFT, int right = VK_RIGHT){srand((unsigned)time(NULL));m_gameSpeed = NORMAL;m_speedNum = 2;m_snakeNum = 4;for(int i=0; i<m_snakeNum; ++i)m_snakePoint[i] = CPoint(5+LENGTH*2*5+LENGTH,LENGTH*2*(i+5));m_run = true;m_direction = RIGHT;turnUP = up;turnDOWN = down;turnLEFT = left;turnRIGHT = right;}public:int m_gameSpeed;//游戏速度int m_speedNum;//游戏速度数CPoint m_foodPoint; //食物定义bool m_run;//游戏状态,运得态还是暂停(结束)态CPoint m_snakePoint[MAX]; //蛇身定义CPoint m_direction;//蛇运动方向int m_snakeNum; //蛇身结点数int m_icon;//用来设定食物是那种图标的int turnUP;//用来表示玩家“上”键设的键int turnDOWN;//用来表示玩家“下”键设的键int turnLEFT;//用来表示玩家“左”键设的键int turnRIGHT;//用来表示玩家“右”键设的键int m_num;//用来记录所选水果的编号};再让读者看一下程序主干类的设计,其中以下只列出由我们自己添加的一些变量的说明,其他的是由程序向导自动生成的,我就不说了:public:afx_msg void OnTimer(UINT_PTR nIDEvent);//程序中运行函数,即是一个定时器,时间就是上面类中的m_gameSpeed来控制的CStatic *m_staticArray;//这是一个蛇定义,是用来显示蛇的,上面只告诉蛇身结点的中心点位置坐标,然后在此中心画一个控件就类似于蛇身了afx_msg void OnClose();//结束,主要是在其中销毁定时器的void GameOver(void);//游戏结束函数afx_msg void OnRButtonDown(UINT nFlags, CPoint point);//当点击鼠标右键出现菜单afx_msg void OnNewGame();//菜单选项,新游戏afx_msg void OnPauseOrStart();//菜单选项,暂停/开始游戏afx_msg voidOnUpdateQuick(CCmdUI *pCmdUI);//这3个函数本来是来标记速度的,和上面类中的m_speedNum对应,但是没有标记成功afx_msg void OnUpdateNormal(CCmdUI *pCmdUI);afx_msg void OnUpdateSlow(CCmdUI *pCmdUI);afx_msg void OnNormal();//菜单选项,设定为普通速度afx_msg void OnSlow();//菜单选项,设定为慢速度afx_msg void OnQuick();//菜单选项,设定为快速度afx_msg void OnIntroduce();//游戏介绍,就是弹出一个对话框而以afx_msg void OnMoreprogram();//进入我的博客的函数afx_msg void OnAbout();//关于“贪吃蛇”说明的对话框afx_msg void OnExit();//退出游戏CFont m_font;//这就是上图中显示“空心字体”的字体设置void ShowHollowFont(int cx,int cy, CString str);//显示空心字体函数,在(Cx,Cy)处显示字符串str afx_msg void OnBnClickedExit();//退出游戏private:int m_icon1;//表明蛇吃第1种水果的个数int m_icon2;//表明蛇吃第2种水果的个数int m_icon3;//表明蛇吃第3种水果的个数然后给读者写的是我程序运行很重要的一个函数,WM_TIMER显示函数,里面有食物位置随机出现,判断蛇死,蛇移动等:void CSnakeDlg::OnTimer(UINT_PTR nIDEvent){if(game.m_snakePoint[0].x < 0 || game.m_snakePoint[0].y < LENGTH ||game.m_snakePoint[0].x > 700 || game.m_snakePoint[0].y > 500)//当蛇跑出边界,游戏结束{GameOver();}for(int j=game.m_snakeNum-1; j>0; --j)//蛇移动的量的变化,当重新设定这些控件的位置时也就是让蛇移动起来game.m_snakePoint[j] =game.m_snakePoint[j-1];game.m_snakePoint[0].x += game.m_direction.x * LENGTH * 2;//蛇头移动game.m_snakePoint[0].y += game.m_direction.y * LENGTH * 2;for(int i=0; i<game.m_snakeNum; ++i){m_staticArray[i].SetWindowPos( NULL, game.m_snakePoint[i].x - LENGTH, game.m_snakePoint[i].y - LENGTH, game.m_snakePoint[i].x + LENGTH,game.m_snakePoint[i].y +LENGTH,SW_SHOW);}for(int j=1; j<game.m_snakeNum; ++j)//当蛇撞到自己也结束游戏if(game.m_snakePoint[0]== game.m_snakePoint[j]){GameOver();}m_staticArray[MAX].ModifyStyle(0xF,SS_ICON | SS_CENTERIMAGE);//显示水果m_staticArray[MAX].SetIcon(AfxGetApp()->LoadIcon(game.m_icon));m_staticArray[MAX].SetWindowPos( NULL, game.m_foodPoint.x,game.m_foodPoint.y, 32, 32,SW_SHOW);//当蛇吃到水果if(game.m_snakePoint[0].x < game.m_foodPoint.x+20+LENGTH && game.m_snakePoint[0].x > game.m_foodPoint.x-LENGTH &&game.m_snakePoint[0].y < game.m_foodPoint.y+20+LENGTH &&game.m_snakePoint[0].y > game.m_foodPoint.y-LENGTH){game.m_foodPoint = CPoint(LENGTH*game.RandNum(2,37),LENGTH*game.RandNum(2,27));CString str;if(game.m_num == 0){++m_icon1;str.Format("%d",m_icon1);GetDlgItem(IDC_EDIT1)->SetWindowTextA(str);}else if(game.m_num == 1){++m_icon2;str.Format("%d",m_icon2);GetDlgItem(IDC_EDIT2)->SetWindowTextA(str);}else{++m_icon3;str.Format("%d",m_icon3);GetDlgItem(IDC_EDIT3)->SetWindowTextA(str);}game.m_num = game.RandNum(0,3);game.m_icon = IDI_ICON1 + game.m_num;//重新加1个水果game.m_snakeNum++;//蛇的长度加1 str.Format("%d",game.m_snakeNum);GetDlgItem(IDC_EDIT4)->SetWindowTextA(str);}CDialog::OnTimer(nIDEvent);}如下再介绍应用在对话框中来响应键盘消息,我写的是一个键盘“钩子”,代码如下:HHOOK g_hKeyboard = NULL;HWND g_hWnd = NULL;LRESULT CALLBACK KeyboardProc(int code, // hook code WPARAM wParam, // virtual-key codeLPARAM lParam // keystroke-message information){if(wParam == game.turnUP){if(game.m_direction.y == 0) game.m_direction = UP;}else if(wParam == game.turnDOWN){if(game.m_direction.y == 0) game.m_direction = DOWN;}else if(wParam == game.turnLEFT){if(game.m_direction.x == 0) game.m_direction = LEFT;}else if(wParam == game.turnRIGHT){if(game.m_direction.x == 0) game.m_direction = RIGHT;}else;return 1;}然后介绍一下,点击鼠标右键出现菜单:void CSnakeDlg::OnRButtonDown(UINT nFlags,CPoint point){if(game.m_run)KillTimer(1);CMenu oMenu;if (oMenu.LoadMenu(IDR_MENU1)){CMenu* pPopup = oMenu.GetSubMenu(0);ASSERT(pPopup != NULL);CPoint oPoint;GetCursorPos(&oPoint);SetForegroundWindow();pPopup->TrackPopupMenu(TPM_LEFTALIGN,oPoint.x,oPoint.y,this);}if(game.m_run) SetTimer(1,game.m_gameSpeed,NULL);CDialog::OnRButtonDown(nFlags, point);}然后来介绍一下程序中是怎样来改变按键的,首先说一下,我开始用EDIT控件来让用户输入,但是程序中我用的是键盘“钩子”来处理消息的,所以EDIT控件在程序中是不可以输入信息的,所以我选的是下拉列表,代码如下,解释也在程序中相应给出:int keyNum[40] ={//定义玩家可以设的键,把所有的键信息存在这个数组中VK_UP,VK_DOWN,VK_LEFT,VK_RIGHT, 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X', 'Y','Z',VK_NUMPAD0,VK_NUMPAD1,VK_NUMPAD2, VK_NUMPAD3,VK_NUMPAD4,VK_NUMPAD5, VK_NUMPAD6,VK_NUMPAD7,VK_NUMPAD8,VK_NUMPAD9};void CSnakeDlg::OnKeyset()//键盘设置响应消息函数{// TODO:在此添加命令处理程序代码if(game.m_run)KillTimer(1);CKeySetDlg dlg;if(dlg.DoModal() == IDOK){if(dlg.m_up == dlg.m_down || dlg.m_up == dlg.m_left || dlg.m_up == dlg.m_right ||dlg.m_down == dlg.m_left || dlg.m_down == dlg.m_right || dlg.m_left == dlg.m_right){MessageBox("键位不能设置为重复的,设置失败!");if(game.m_run) SetTimer(1,game.m_gameSpeed,NULL);return;}game.turnUP = keyNum[GetMarkNum(dlg.m_up)];//重新设置键game.turnDOWN =keyNum[GetMarkNum(dlg.m_down)];game.turnLEFT = keyNum[GetMarkNum(dlg.m_left)];game.turnRIGHT = keyNum[GetMarkNum(dlg.m_right)];}if(game.m_run) SetTimer(1,game.m_gameSpeed,NULL);}int CSnakeDlg::GetMarkNum(CString str)//返回重新设置键对应数组的“索引”{int backNum = 0;if(str == "上")backNum = 0;else if(str == "下")backNum = 1;else if(str == "左")backNum = 2;else if(str == "右")backNum = 3;else{CString ss;for(char i='A'; i<='Z'; ++i){ss.Format("%c",i);if(ss == str.Right(1)){backNum = i - 'A' + 4;return backNum;}}for(int i=0; i<=9; ++i){ss.Format("%d",i);if(ss == str.Right(1)){backNum = i + 30;return backNum;}}}return backNum;}最后写一下程序更换皮肤的一段代码,本来觉得不算很难的,不过还是介绍一下吧,对了我用的是Skinmagic做的皮肤,不过这个软件你可以通过网上的说明进行注册,也可以自己把它破解,其实很简单,大家可以试试:void CSnakeDlg::OnChangSkin(){// TODO:在此添加命令处理程序代码if(game.m_run)KillTimer(1);CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY |OFN_OVERWRITEPROMPT, "SkinFiles(*.smf)|*.smf||",AfxGetMainWnd());CString strPath,strText="";if(dlg.DoModal() == IDOK){strPath = dlg.GetPathName();VERIFY(1 == LoadSkinFile(strPath));}if(game.m_run) SetTimer(1,game.m_gameSpeed,NULL);}还有很多小函数,由于都是比较简单的,就不多写了,程序介绍就到这里,呵呵,希望我能够帮你解决你写程序遇到的问题,如果大家想知道如何做程序的皮肤的话,网上有很多这样的博客,我就是在那样的博客里学到的,如果还是想我来介绍的话,那给我留言说下哦,呵呵,谢了,有问题请在下面留言......。

贪吃蛇游戏源代码

贪吃蛇游戏源代码

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;}}}}}。

JAVA贪吃蛇小游戏的程序代码及报告

JAVA贪吃蛇小游戏的程序代码及报告

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此类为画蛇的面板类,是粉色蛇身算法的类。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
this.foodx=((int)(Math.random()*(this.getWidth()-110)/10))*10+50;
this.foody=((int)(Math.random()*(this.getHeight()-110)/10))*10+50;
for(i=0;i<s.length;i++){
this.snake.speed=200;
}
//小蛇前进
this.snake.move();
//检查一下是否撞墙或自己
this.snake.check();
//小蛇吃食物与食物的存在的关系
food=this.snake.eat(this.foodx, this.foody);
g.fillRect(this.snake.x[i], this.snake.y[i], 10, 10);
}
//你的得分
g.setColor(Color.white);
g.drawString("得分:"+(this.snake.length-3)*10, 50,40);
/*
* 这个是贪虼蛇的窗体部分
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Map extends JFrame implements KeyListener,Runnable{
}
//产生食物
public void produceFood(Snake s){
//食物的产生位置是否合法
boolean foodNotOK=true;
while(foodNotOK){
//System.out.println("1111111111");
int i;
new Thread(this).start();
this.setVisible(true);
this.setSize(this.window_width, this.window_height);
this.validate();
this.setResizable(false);
}
//美味的食物
g.setColor(Color.orange);
g.fillRect(this.foodx,this.foody,10, 10);
//lor.green);
for(int i=0;i<this.snake.length;i++){
if(this.foodx==s.x[i]&&this.foody==s.y[i]){
break;
}
}
if(i==s.length){
foodNotOK=false;
}
}
}
@Override
public void keyPressed(KeyEvent arg0) {
}
if(this.snake.length>22&&this.snake.length<33&&this.snake.speed>400){
this.snake.speed=300;
}
if(this.snake.length>32&&this.snake.speed>400){
//重绘窗体
this.repaint();
}
JOptionPane.showMessageDialog(this, "小蛇死了,游戏结束...");
}
}
/*************************************************************************************************************************/
public static void main(String[] args){
new Map();
}
public Map(){
//小蛇进入到窗体里面
snake=new Snake();
this.addKeyListener(this);
//为进入窗体的小蛇开启一个线程
this.snake.speed=500;
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void run() {
this.isLive=false;
}
}
}
//是否吃掉了食物
public boolean eat(int x,int y){
if(this.x[0]==x&&this.y[0]==y){
this.length++;
return true;
e.printStackTrace();
}
//安照小蛇的长度设定其速度,最大速度为200
if(this.snake.length>12&&this.snake.length<23&&this.snake.speed>400){
this.snake.speed=400;
//可爱小蛇的体长,初始长度是3
int length=3;
//可爱小蛇的生死情况
boolean isLive=true;
public Snake(){
//小蛇最多有200个体节
x=new int[200];
y=new int[200];
//初始小蛇的位置
for(int i=this.length-1;i>=0;i--){
this.snake.speed=100;
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode()==KeyEvent.VK_RIGHT||arg0.getKeyCode()==KeyEvent.VK_LEFT||arg0.getKeyCode()==KeyEvent.VK_DOWN||arg0.getKeyCode()==KeyEvent.VK_UP){
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
}
public void paint(Graphics g){
//设置背景
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
//检查是否撞墙
if(this.x[0]<50||this.x[0]>440||this.y[0]<50||this.y[0]>340){
this.isLive=false;
}
//检查是否撞自己
for(int i=1;i<this.length;i++){
if(this.x[0]==this.x[i]&&this.y[0]==this.y[i]){
// TODO Auto-generated method stub
if(arg0.getKeyCode()==KeyEvent.VK_RIGHT&&this.snake.direction!=2){
this.snake.direction=1;
this.snake.speed=100;
}else{
return false;
}
}
}
this.snake.direction=3;
this.snake.speed=100;
}else if(arg0.getKeyCode()==KeyEvent.VK_UP&&this.snake.direction!=3){
this.snake.direction=4;
// TODO Auto-generated method stub
while(this.snake.isLive){
try {
Thread.sleep(this.snake.speed);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
x[0]+=10;
}else if(direction==2){
x[0]-=10;
}else if(direction==3){
y[0]+=10;
}else{
y[0]-=10;
}
}
//检查小蛇是否撞墙或撞自己
public void check(){
y[i]=50;
x[i]=(2-i)*10+50;
}
}
//小蛇前进
public void move(){
相关文档
最新文档