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

贪吃蛇源代码将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){}}。
用java实现简单贪食蛇游戏

catch(NullPointerException e){
e.printStackTrace();//深层次的输出异常调用的流程
}
finally {
if (br == null){
try{
br.close();
}
catch (IOException e){
e.printStackTrace();
direction="DOWN";
pre_dir="restart";
paint(g);
break;
case "暂停" :
direction="STOP";
break;
case "减速" :
sleeptime+=10;
speed-=10;
g.setColor(Color.CYAN);
g.drawString(" "+(speed+10), 30, 120);
c.setBackground(Color.cyan);
restart=new JButton("重新开始");
pause=new JButton("暂停");
speed_add=new JButton("加速");
speed_sub=new JButton("减速");
mode=new JComboBox(modes);
public snakemove(){
getmap(map);
for(int k=0;k<8;k++)
image[k]=new ImageIcon("pic/"+k+".png");
java贪吃蛇游戏源代码

Java 语言设计贪吃蛇游戏源代码提供者:轻听世音一.(程序入口)snakeMainpackage game;import java.awt.Color;import java.awt.Image;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;public class snakeMain extends JFrame{//无参构造函数(构造一个初始时不可见的新窗体)public snakeMain(){ //在构造函数里面设置窗体的属性snakeWin win = new snakeWin();//Jpanel的子类add(win);//将其添加到窗口setTitle("贪吃蛇游戏");//设置窗口标题// setBackground(Color.orange);setSize(435,390);//设置窗口大小setLocation(200,200);//位置setVisible(true); //可见}public static void main(String[] args){new snakeMain();}}二.snakeAct类package game;public class snakeAct{private int x;private int y;//封装public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}}三,snakeWinpackage game;import java.awt.Color;import java.awt.FlowLayout;import java.awt.Graphics;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.IOException;import java.nio.CharBuffer;import java.util.ArrayList;import java.util.List;import java.util.Random;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;public class snakeWin extends JPanel implements ActionListener,KeyListener,Runnable{JButton newGame,stopGame; //定义两个按钮类型变量int fenShu,speed; //记录游戏的分数和速度boolean start = false; //定义一个开关,用来判断游戏的状态Random r = new Random(); //使用Random 类产生随机数int rx = 0,ry = 0; //定义两个变量记录产生的随机数的坐标List<snakeAct> list = new ArrayList<snakeAct>(); //利用列表来储存蛇块int temp = 0; //定义一个方向变量Thread nThread; //定义一个线程变量int tempeat1= 0,tempeat2 = 0; //定义两个变量,分别用来记录蛇块的量,用它们的插值来记录速度的变化JDialog dialog = new JDialog(); //游戏失败时的对话框JLabel label = new JLabel(); //可以在dialog添加label,用来显示一些信息JButton ok = new JButton("确定"); //在dialog上添加按钮//构造函数(创建具有双缓冲和流布局的新JPanel)public snakeWin(){// setBackground(Color.pink);//newGame = new JButton("开始"); //创建开始按钮newGame = new JButton("开始",new ImageIcon("src/boy.png"));stopGame = new JButton("结束",new ImageIcon("src/boy.png")); //创建结束按钮setLayout(new FlowLayout(FlowLayout.LEFT));// setLayout(new FlowLayout(FlowLayout.LEFT)); //将按钮设置为居左(按钮位置默认为居中)newGame.addActionListener(this); //设置按钮监听stopGame.addActionListener(this); //设置按钮监听ok.addActionListener(this); //设置按钮监听(结束游戏是的按钮)// newGame.addKeyListener(this);this.addKeyListener(this); //添加键盘监听add(newGame); //添加按钮add(stopGame); //添加按钮dialog.setLayout(new GridLayout(2,1));dialog.add(label); //添加labeldialog.add(ok); //添加OK 按钮dialog.setSize(300, 200); //设置dialog 大小dialog.setLocation(300, 300);//出现位置// dialog.setVisible(true); //可见}//画图public void paintComponent(Graphics g){super.paintComponent(g); //重画g.drawRect(10, 40, 400, 300); //游戏的区域在坐标为(10,40)的地方创建一个长400,高300像素的区域g.drawString("分数: "+fenShu, 200, 20); //在(150,20)的地方添加分数g.drawString("速度: "+speed, 200, 35); //在(150,35)的地方添加速度g.setColor(Color.blue); //设置蛇块的颜色if(start){g.fillRect(10+rx*10, 40+ry*10, 10, 10);//画出蛇块; 分别为蛇块的x,y坐标,和蛇块的长度高度for(int i = 0; i < list.size(); i ++){g.setColor(Color.red);g.fillRect(10+list.get(i).getX()*10,40 +list.get(i).getY()*10 , 10,10);//画出蛇体}}}//监听器public void actionPerformed(ActionEvent e){if(e.getSource() == newGame) //监听到得对象是开始按钮{newGame.setEnabled(false); //开始按钮不能再点start = true; //设定游戏开始rx = r.nextInt(40);ry = r.nextInt(30); //随机产生的食物坐标snakeAct tempAct = new snakeAct(); //(snakeAct中保存了蛇块的坐标)tempAct.setX(20); //初始蛇块位置为中总共有40个tempAct.setY(15); //初始蛇块位置为中总共有30个list.add(tempAct); //将蛇块添加到list 列表中requestFocus(true);nThread = new Thread(this);nThread.start(); //执行线程repaint();}if(e.getSource() == stopGame) //如果监听到得对象时结束游戏时{System.exit(0); //关闭窗口}if(e.getSource() == ok) //如果监听到得按钮重新开始{list.clear(); //清空列表fenShu = 0; //分数清零speed = 0; //速度清零start = false; //游戏状态为falsenewGame.setEnabled(true); //开始按钮释放,又可以点击dialog.setVisible(false);repaint();}}public void eat(){if(rx == list.get(0).getX()&&ry == list.get(0).getY()) //如果蛇头的坐标与随机产生的蛇块的坐标相对应,表示吃到食物{rx = r.nextInt(40);ry = r.nextInt(30); //吃到食物之后要产生另外一个随机食物snakeAct tempAct = new snakeAct(); //snakeAct 类中保存着蛇块的坐标属性tempAct.setX(list.get(list.size()-1).getX());tempAct.setY(list.get(list.size()-1).getY()); //直接将吃到的蛇块放到列表的末尾list.add(tempAct); //添加蛇块fenShu += 100+10*speed; //分数为吃一个食物加(100+speed*10)分tempeat1 +=1; //记录吃到的食物if(tempeat1 - tempeat2 >=10) //如果吃到的蛇块第一次相差为十时{//每吃到十个,速度加一tempeat2 = tempeat1; //速度提升的条件speed++;}repaint();}}//移动方法public void move(int x,int y){if(maxYes(x,y)){ //预判,如果minYes(x,y)返回true时,表示可以移动otherMove(); //蛇头之后的蛇块跟着蛇头动list.get(0).setX(list.get(0).getX()+x);list.get(0).setY(list.get(0).getY()+y); //蛇头的移动eat(); //吃蛇块repaint();}else{//死亡方法nThread = null;label.setText("游戏结束,你获得的分数是:"+fenShu);dialog.setVisible(true);}}public void otherMove(){/*让其他的蛇块都跟着蛇头的移动而移动,很简单,就是* 首先将第二个蛇块获得第一个蛇块的坐标,相当于* 第二个蛇块前进到原来第一个蛇块的位置,而后面* 的蛇块只需要彼此交换位置就好了,总的下来蛇块就前进了一个单位的位置,* 总之要保护蛇头,如果蛇头参与相互的交换,则控制蛇头的移动将失效*/snakeAct tempAct = new snakeAct();for(int i = 0;i < list.size();i ++){if(i == 1){list.get(i).setX(list.get(0).getX());list.get(i).setY(list.get(0).getY());}else if(i > 1){tempAct = list.get(i-1);list.set(i-1, list.get(i));list.set(i,tempAct); //交换}}}//方块移动边界的判定// public boolean minYes(int x,int y)// {// if(!maxYes(list.get(0).getX()+x , list.get(0).getY()+y))// {// return false;// }// return true;// }public boolean maxYes(int x,int y){if(list.get(0).getX()+x<0||list.get(0).getX()+x>=40||list.get(0).getY()+y<0||list.get( 0).getY()+y>=30) //如果坐标范围不在游戏设定的区域里面,简而言之就是撞墙了{return false;}for(int i = 0;i < list.size();i ++) //蛇头的坐标和自己身体的坐标相等的时候说明蛇头于身体相撞{if(i>1&&list.get(0).getX()==list.get(i).getX()&&list.get(0).getY()==list.get(i).get Y()){return false;}}return true;}// 键盘监听器public void keyPressed(KeyEvent e){if(start){switch(e.getKeyCode()) //监听到得对象{case KeyEvent.VK_UP: //UPmove(0,-1); //x不变,y减1temp = 1; //标记upbreak;case KeyEvent.VK_DOWN: //downmove(0,1); //x不变,y +1temp = 2; //标记downbreak;case KeyEvent.VK_LEFT: //leftmove(-1,0); //x-1,y不变temp = 3; //标记leftbreak;case KeyEvent.VK_RIGHT: //rightmove(1,0); //x+1,y不变temp = 4; //标记方向rightbreak;}}}public void keyReleased(KeyEvent e) {} //空函数public void keyTyped(KeyEvent e) {} //空方法public void run() //重写的run方法{while(start) //条件是游戏开始{switch(temp){case 1:move(0,-1);break;case 2:move(0,1);break;case 3:move(-1,0);break;case 4:move(1,0);break;default: //设置默认向右移动move(1,0);break;}// fenShu +=10*speed; //速度越快加的分数越高repaint();try{Thread.sleep(500-(50*speed)); //吃的蛇块越多,速度越快}catch (InterruptedException e){e.printStackTrace();}}}}。
贪吃蛇 Java 代码

}
// 打印食物到地图上
public 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简单贪吃蛇代码

for(j=0;j<mi[i].length;j++)
//小于菜单的长度
{
m[i].add(mi[i][j]);
//添加
}
//for
}
//for
mi[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) {
//将数组赋为 0 //for //for //WH_panel()
//left 函数
//假设现在向右行进
//wh_direct 为 1 //标记左不能运行
//标记上可以运行 //标记下可以运行
//假设现在不是向右行进
//向左可以运行
//右键函数
//假设现在向左行进
//wh_direct 为 2
//向右不可以运行 //向上可以运行
wh_stop=1; } x=x+20; wh_run();
//假设现在没有向下运行 //可以向上行进
//向下键的函数 //如果现在向上运行
//wh_direct 为 4 //现在不可向下行进 //现在可向右行进 //现在向左行进 //如果现在没有向上行进 //可以向下行进
java贪吃蛇 代码

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

java课程设计-贪吃蛇代码importjava.awt.Color;importponent;importjava.awt.Graphic;importjava.awt.event.ActionEvent; importjava.awt.event.ActionLitener; importjava.awt.event.KeyEvent;importjava.awt.event.KeyLitener; importjava.util.ArrayLit;importjava某.wing.BorderFactory;importjava某.wing.JFrame;importjava某.wing.JLabel;importjava某.wing.JMenu;importjava某.wing.JMenuBar;importjava某.wing.JMenuItem;importjava某.wing.JPanel; publicclaSnakeGame{publictaticvoidmain(String[]arg){ SnakeFrameframe=newSnakeFrame();frame.etTitle("贪吃蛇");frame.etDefaultCloeOperation(JFrame.E某IT_ON_CLOSE);frame.etViible(true);}}//----------记录状态的线程claStatuRunnableimplementRunnable{publicStatuRunnable(Snakenake,JLabeltatuLabel,JLabelcoreLabe l){thi.tatuLabel=tatuLabel;thi.coreLabel=coreLabel;thi.nake=nake;}publicvoidrun(){Stringta="";Stringpe="";while(true){witch(nake.tatu){caeSnake.RUNNING:ta="Running";break;caeSnake.PAUSED:ta="Paued";break;caeSnake.GAMEOVER:ta="GameOver";break;}tatuLabel.etTe某t(ta); coreLabel.etTe某t(""+nake.core); try{Thread.leep(100);}catch(E某ceptione){}}}privateJLabelcoreLabel; privateJLabeltatuLabel; privateSnakenake;}//----------蛇运动以及记录分数的线程claSnakeRunnableimplementRunnable{ thi.nake=nake;}publicvoidrun(){while(true){try{nake.move();Thread.leep(nake.peed);}catch(E某ceptione){}}}privateSnakenake;}claSnake{booleaniRun;//---------是否运动中ArrayLit<Node>body;//-----蛇体Nodefood;//--------食物intderection;//--------方向intcore;inttatu;intpeed; publictaticfinalintSLOW=500; publictaticfinalintMID=300; publictaticfinalintFAST=100; publictaticfinalintRUNNING=1; publictaticfinalintPAUSED=2; publictaticfinalintGAMEOVER=3; publictaticfinalintLEFT=1; publictaticfinalintUP=2; publictaticfinalintRIGHT=3; publictaticfinalintDOWN=4; publicSnake(){peed=Snake.SLOW;core=0;iRun=fale;tatu=Snake.PAUSED;derection=Snake.RIGHT;body=newArrayLit<Nod e>();body.add(newNode(60,20));body.add(newNode(40,20));body.add(newNode(20,20));makeFood();}//------------判断食物是否被蛇吃掉//-------如果食物在蛇运行方向的正前方,并且与蛇头接触,则被吃掉privatebooleaniEaten(){Nodehead=body.get(0);if(derection==Snake.RIGHT&&(head.某+Node.W)==food.某&&head.y==food.y)returntrue;if(derection==Snake.LEFT&&(head.某-Node.W)==food.某&&head.y==food.y)returntrue;if(derection==Snake.UP&&head.某==food.某&&(head.y-Node.H)==food.y)returntrue;if(derection==Snake.DOWN&&head.某==food.某&&(head.y+Node.H)==food.y)returntrue;elereturnfale;}//----------是否碰撞privatebooleaniCollion(){Nodenode=body.get(0);//------------碰壁if(derection==Snake.RIGHT&&node.某==280) returntrue;if(derection==Snake.UP&&node.y==0) returntrue;if(derection==Snake.LEFT&&node.某==0) returntrue;if(derection==Snake.DOWN&&node.y==380) returntrue;//--------------蛇头碰到蛇身Nodetemp=null;inti=0;for(i=3;i<body.ize();i++){temp=body.get(i);if(temp.某==node.某&&temp.y==node.y) break;}if(i<body.ize())returntrue;elereturnfale;}//-------在随机的地方产生食物publicvoidmakeFood(){Nodenode=newNode(0,0); booleaniInBody=true;int某=0,y=0;int某=0,Y=0;inti=0;while(iInBody){某=(int)(Math.random()某15);y=(int)(Math.random()某20);某=某某Node.W;Y=y某Node.H;for(i=0;i<body.ize();i++){if(某==body.get(i).某&&Y==body.get(i).y)break; }if(i<body.ize())iInBody=true;eleiInBody=fale;}food=newNode(某,Y);}//---------改变运行方向publicvoidchangeDerection(intnewDer){if(derection%2!=newDer%2)//-------如果与原来方向相同或相反,则无法改变derection=newDer;}publicvoidmove(){if(iEaten()){//-----如果食物被吃掉body.add(0,food);//--------把食物当成蛇头成为新的蛇体core+=10;makeFood();//--------产生食物}eleif(iCollion())//---------如果碰壁或自身{iRun=fale;tatu=Snake.GAMEOVER;//-----结束}eleif(iRun){//----正常运行(不吃食物,不碰壁,不碰自身)Nodenode=body.get(0);int某=node.某;intY=node.y;//------------蛇头按运行方向前进一个单位witch(derection){cae1:某-=Node.W;break;cae2:Y-=Node.H;break;cae3:某+=Node.W;break;cae4:Y+=Node.H;break;}body.add(0,newNode(某,Y));//---------------去掉蛇尾body.remove(body.ize()-1);}}}//---------组成蛇身的单位,食物claNode{publictaticfinalintW=20;publictaticfinalintH=20;int某;inty;publicNode(int某,inty){thi.某=某;thi.y=y;}}//------画板claSnakePanele某tendJPanel{Snakenake;publicSnakePanel(Snakenake){thi.nake=nake;}Nodenode=null;for(inti=0;i<nake.body.ize();i++){//---黄绿间隔画蛇身if(i%2==0)g.etColor(Color.green);eleg.etColor(Color.yellow);node=nake.body.get(i);g.fillRect(node.某,node.y,node.H,某某某某某某某某某某某某某某某某某某某试用某某某某某某某某某某某某某某某某某某某某某}node=nake.food;node.W);//g.etColor(Color.blue);g.fillRect(node.某,node.y,node.H,node.W);}}claSnakeFramee某tendJFrame{privateJLabeltatuLabel;privateJLabelpeedLabel;privateJLabelcoreLabel;privateJPanelnakePanel;privateSnakenake;privateJMenuBarbar;JMenugameMenu;JMenuhelpMenu;JMenupeedMenu;JMenuItemnewItem;JMenuItempaueItem; JMenuItembeginItem; JMenuItemhelpItem; JMenuItemaboutItem;JMenuItemlowItem;JMenuItemmidItem;JMenuItemfatItem;publicSnakeFrame(){init();ActionLitenerl=newActionLitener(){ publicvoidactionPerformed(ActionEvente){ if(e.getSource()==paueItem)nake.iRun=fale;if(e.getSource()==beginItem)nake.iRun=true;if(e.getSource()==newItem){newGame();}//------------菜单控制运行速度if(e.getSource()==lowItem){ nake.peed=Snake.SLOW; peedLabel.etTe某t("Slow");}if(e.getSource()==midItem){ nake.peed=Snake.MID; peedLabel.etTe某t("Mid");}if(e.getSource()==fatItem){ nake.peed=Snake.FAST; peedLabel.etTe某t("Fat");}}};paueItem.addActionLitener(l); beginItem.addActionLitener(l);newItem.addActionLitener(l); aboutItem.addActionLitener(l);lowItem.addActionLitener(l);midItem.addActionLitener(l);fatItem.addActionLitener(l); addKeyLitener(newKeyLitener(){ publicvoidkeyPreed(KeyEvente){witch(e.getKeyCode()){//------------方向键改变蛇运行方向caeKeyEvent.VK_DOWN://nake.changeDerection(Snake.DOWN);break; caeKeyEvent.VK_UP://nake.changeDerection(Snake.UP);break; caeKeyEvent.VK_LEFT://nake.changeDerection(Snake.LEFT);break; caeKeyEvent.VK_RIGHT://nake.changeDerection(Snake.RIGHT);break; //空格键,游戏暂停或继续caeKeyEvent.VK_SPACE://if(nake.iRun==true){nake.iRun=fale;nake.tatu=Snake.PAUSED;break;}if(nake.iRun==fale){nake.iRun=true;nake.tatu=Snake.RUNNING;break; }}}publicvoidkeyReleaed(KeyEventk){ }publicvoidkeyTyped(KeyEventk){ }});}privatevoidinit(){peedLabel=newJLabel();nake=newSnake();etSize(380,460);etLayout(null);thi.etReizable(fale);bar=newJMenuBar();gameMenu=newJMenu("Game");newItem=newJMenuItem("NewGame");PaueItem=newJMenuItem("Paue");beginItem=newJMenuItem("Continue");gameMenu.add(paueItem);gameMenu.add(newItem);gameMenu.add(beginItem);helpMenu=newJMenu("Help");aboutItem= newJMenuItem("About");helpMenu.add(aboutItem);peedMenu=newJMenu("Speed");lowItem=newJMenuItem("Slow");fatItem=newJMenuItem("Fat");midItem=newJMenuItem("Middle");peedMenu.add(lowItem);peedMenu.add(midItem);peedMenu.add(fatItem);bar.add(gameMenu);bar.add(helpMenu);bar.add(peedMenu);etJMenuBar(bar);tatuLabel=newJLabel();coreLabel=newJLabel();nakePanel=newJPanel();nakePanel.etBound(0,0,300,400);nakePanel.etBorder(BorderFactory.createLineBorder(Color.dark Gray));add(nakePanel);tatuLabel.etBound(300,25,60,20);add(tatuLabel);coreLabel.etBound(300,20,60,20);add(coreLabel);JLabeltemp=newJLabel("状态");temp.etBound(310,5,60,20);add(temp);temp=newJLabel("速度");temp.etBound(310,105,60,20);add(temp);temp=newJLabel("分数");temp.etBound(310,55,60,20);add(temp);temp.etBound(310,155,60,20);add(temp);temp=newJLabel("14滕月"); temp.etBound(310,175,60,20);add(temp);peedLabel.etBound(310,75,60,20); add(peedLabel);}privatevoidnewGame(){thi.remove(nakePanel);thi.remove(tatuLabel);thi.remove(coreLabel); peedLabel.etTe某t("Slow"); tatuLabel=newJLabel();coreLabel=newJLabel();nakePanel=newJPanel();nake=newSnake();nakePanel=newSnakePanel(nake);nakePanel.etBound(0,0,300,400);nakePanel.etBorder(BorderFactory.createLineBorder(Color.dark Gray));Runnabler1=newSnakeRunnable(nake,nakePanel);Runnabler2=newStatuRunnable(nake,tatuLabel,coreLabel);Thread t1=newThread(r1);Threadt2=newThread(r2);t1.tart();t2.tart();add(nakePanel);tatuLabel.etBound(310,25,60,20);add(tatuLabel);coreLabel.etBound(310,125,60,20);add(coreLabel);}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
贪吃蛇:看了传智博客的视频整理出来的代码Snake类package snake;import java.awt.Color;import java.awt.Graphics;import java.awt.Point;import java.util.HashSet;import java.util.LinkedList;import java.util.Set;public class Snake {//定义方向的常量public static final int UP=-1;public static final int DOWN=1;public static final int LEFT=2;public static final int RIGHT=-2;private int oldDirection,newDirection;private Point oldTail;private boolean life;private LinkedList<Point> body=new LinkedList<Point>(); //蛇的坐标private Set<SnakeListener> listener=new HashSet<SnakeListener>();//蛇没身体要初始化public Snake(){init();}public void init(){//显示区最中间点int x=Global.WIDTH/2;int y=Global.HEIGHT/2;//初始化身体节点for(int i=0;i<3;i++){//添加节点body.addLast(new Point(x--,y));//蛇头在右边默认方向为右oldDirection=newDirection=RIGHT;life=true;}}public void move(){System.out.println("Snake's move");if(!((oldDirection+newDirection)==0)){ oldDirection=newDirection;}//1. 去尾oldTail=body.removeLast();int x=body.getFirst().x; //原坐标int y=body.getFirst().y;switch(oldDirection){case UP:y--;if(y<0){y=Global.HEIGHT-1;}break;case DOWN:y++;if(y>=Global.HEIGHT){y=0;}break;case LEFT:x--;if(x<0){x=Global.WIDTH-1;}break;case RIGHT:x++;if(x>=Global.WIDTH){x=0;}break;}Point newHead=new Point(x,y);//2. 加头body.addFirst(newHead);}public void changeDirection(int direction){System.out.println("Snake's changeDirection");/*if(!(direction+this.direction==0)){this.direction=direction;}*/newDirection=direction;}public void die(){life=false;}public void eatFood(){System.out.println("Snake's eatFood");body.addLast(oldTail);}public boolean isEatBody(){System.out.println("Snake's isEatBody");for(int i=1;i<body.size();i++){if(body.get(i).equals(this.getHead()))return true;}return false;}//显示public void drawMe(Graphics g){System.out.println("Snake's drawMe");g.setColor(Color.BLUE);//蛇身颜色//遍历for(Point p: body)g.fill3DRect(p.x*Global.CELL_SIZE,p.y*Global.CELL_SIZE,Global.CELL_SIZE , Global.CELL_SIZE,true);}//得到蛇头的方法public Point getHead(){return body.getFirst();}//内部类private class SnakeDriver implements Runnable{public void run(){while(life){move();for(SnakeListener l:listener){l.snakeMove(Snake.this);}try{Thread.sleep(1000);}catch(InterruptedException e){e.printStackTrace();}}}}//启动线程public void start(){new Thread(new SnakeDriver()).start();}public void addSnakeListener(SnakeListener l){ if(l!=null){this.listener.add(l);}}}Food类package snake;import java.awt.Graphics;import java.awt.Point;public class Food extends Point {public void newFood(Point p){this.setLocation(p);}public boolean isSnakeEatFood(Snake snake){System.out.println("Food's isAnakeEatFood");return this.equals(snake.getHead());//return false;}public void drawMe(Graphics g){System.out.println("Food's drawMe");//g.fillOval(x*Global.WIDTH, y*Global.HEIGHT, Global.CELL_SIZE,Global.CELL_SIZE);g.fill3DRect(x*Global.CELL_SIZE, y*Global.CELL_SIZE, Global.CELL_SIZE, Global.CELL_SIZE, true);}}Ground类package snake;import java.awt.Color;import java.awt.Graphics;import java.awt.Point;import java.util.Random;public class Ground {private int[][] rocks=new int[Global.WIDTH][Global.HEIGHT];//生成墙public Ground(){for(int y=0;y<Global.WIDTH;y++){rocks[0][y]=1;rocks[Global.HEIGHT-1][y]=1;}for(int x=0;x<Global.WIDTH;x++){rocks[x][0]=1;rocks[x][Global.WIDTH-1]=1;}}public boolean isSnakeEatGround(Snake snake){System.out.println("Ground's isSnakeEatGround ");for(int x=0;x<Global.WIDTH;x++)for(int y=0;y<Global.HEIGHT;y++){if(rocks[x][y]==1&&(x==snake.getHead().x&&y==snake.getHead().y)){//石头和蛇头重合return true;}}return false;//获得随机位置public Point getPoint(){Random ran=new Random();int x=0,y=0;do{x=ran.nextInt(Global.WIDTH);y=ran.nextInt(Global.HEIGHT);}while(rocks[x][y]==1);return new Point(x,y);}public void drawMe(Graphics g){System.out.println("Ground's drawMe");g.setColor(Color.RED);for(int x=0;x<Global.WIDTH;x++)for(int y=0;y<Global.HEIGHT;y++){if(rocks[x][y]==1){g.fill3DRect(x*Global.CELL_SIZE, y*Global.CELL_SIZE, Global.CELL_SIZE, Global.CELL_SIZE, true);}}}}GamePanel类package snake;import java.awt.Color;import java.awt.Graphics;import javax.swing.JPanel;public class GamePanel extends JPanel {private Snake snake;private Food food;private Ground ground;public void display(Snake snake,Food food,Ground ground){System.out.println("CamePanel's display");this.snake=snake;this.food=food;this.ground=ground;this.repaint();protected void paintComponent(Graphics g) {// TODO 自动生成的方法存根//重新显示super.paintComponent(g);g.setColor(new Color(0xcfcfcf));g.fillRect(0, 0, Global.WIDTH*Global.CELL_SIZE, Global.HEIGHT*Global.CELL_SIZE);if(snake!=null&&food!=null&&ground!=null){this.snake.drawMe(g);this.food.drawMe(g);this.ground.drawMe(g);}}/*public void addSnakeListener(Controller controller) {// TODO 自动生成的方法存根}*/}Controller类package snake;import java.awt.Point;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.Random;public class Controller extends KeyAdapter implements SnakeListener{private Snake snake;private Food food;private Ground ground;private GamePanel gamePanel;public void keyPressed(KeyEvent e) {// TODO 自动生成的方法存根//super.keyPressed(e);//转动方向switch(e.getKeyCode()){case KeyEvent.VK_UP:snake.changeDirection(Snake.UP);break;case KeyEvent.VK_DOWN:snake.changeDirection(Snake.DOWN);break;case KeyEvent.VK_LEFT:snake.changeDirection(Snake.LEFT);break;case KeyEvent.VK_RIGHT:snake.changeDirection(Snake.RIGHT);break;}}public Controller(Snake snake, Food food, Ground ground, GamePanel gamePanel) { super();this.snake = snake;this.food = food;this.ground = ground;this.gamePanel = gamePanel;}//逻辑public void snakeMove(Snake snake) {// TODO 自动生成的方法存根if(food.isSnakeEatFood(snake)){snake.eatFood();food.newFood(ground.getPoint());}//吃到石头if(ground.isSnakeEatGround(snake)){snake.die();//让snake里线程退出}//吃到身体if(snake.isEatBody()){snake.die();}gamePanel.display(snake,food,ground);}public void newGame(){snake.start();food.newFood(ground.getPoint());}}SnakeListener接口package snake;public interface SnakeListener {void snakeMove(Snake snake);}Global 类package snake;public class Global {//格子public static final int CELL_SIZE=20;public static final int WIDTH=30;public static final int HEIGHT=30;}TestMyGame 类package snake;import java.awt.BorderLayout;import javax.swing.JFrame;public class TestMyGame {public static void main(String[]args){Snake snake=new Snake();Food food=new Food();Ground ground=new Ground();GamePanel gamePanel=new GamePanel();Controller controller=new Controller(snake,food,ground,gamePanel);JFrame frame=new JFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(Global.WIDTH*Global.CELL_SIZE+15,Global.HEIGHT*Global.CELL_SIZ E+38);frame.add(gamePanel,BorderLayout.CENTER);gamePanel.setSize(Global.WIDTH*Global.CELL_SIZE,Global.HEIGHT*Global.CELL_SI ZE);gamePanel.addKeyListener(controller);snake.addSnakeListener(controller);frame.addKeyListener(controller);frame.setVisible(true);controller.newGame();}}。