Java编写的贪吃蛇游戏代码

合集下载

贪吃蛇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){}}。

用java实现简单贪食蛇游戏

用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贪吃蛇游戏源代码

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

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

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

package com.zf.s17;import java.util.*;import jaba.awt.*;import java.awt.event.*;import javax.swing,*;class Move{int move_x;int move_y;Move(int move_x, int move_y)this.move_x=move_x;this.move_y=move_y;}class MoveOperate extends Observable implements Runnable public static final int LEFT = 1;public static final int UP = 2;public static final int RIGHT = 3;public static final int DOWN = 4;private boolean[][] isHave;private LinkedList snake = new LinkList();private Move aliment;private int move_Direction = LEFT;private boolean running = false;private int timeSpace = 300;private double speedChange = 0.75;private boolean paused = false;private int score = 0;private int moveCount = 0;private int X;private int Y;public MoveOperate(int X,int Y){this.X= X;this.Y= Y;resetGame();}public void run(){running = true;while (running){try{Thread.sleep(timeSpace);}catch (Exception e){System.out.println("休眠出错: "+e.getMessage());break;}if (!paused){if (move()){setChanged();notifyObservers();}else{JOptionPane.showMessageDialog(null,"你失败了!", "Game Over",RMA TION_MESSAGE);break;}}}if (!running){JOptionPane.showMessageDialog(null,"你停止了游戏","Game Over",RMA TION_MESSAGE);}}public void resetGame(){move_Direction = MoveOperate.LEFT;timeSpace = 300;paused = false;score = 0;moveCount = 0;isHave = new boolean[X][Y];for (int i = 0, i < X; i++)isHave[i] = new boolean[Y];Arrays.fill(isHave[i],false);}int initLength = X > 20 ? 10 : X / 2;snake.clear();int x = X / 2;int Y = Y / 2;for (int i = 0; i < initLength; i++){snake.addLast(new Move(x,y));isHave[X][Y] = true;x++;}aliment = createAliment();isHave[aliment.move_X][aliment.move_Y] = true;}public boolean move(){move snakeHead = (Move) snake.getFirst();int headX = snakeHead.move_X;int headY = snakeHead.move_Y;switch (move_Direction){case UP:headY--;break;case DOWN:headY++;break;case LEFT:headX--;break;case RIGHT:headX++;break;}if ((0 <= headX && headX < X) && (0 <= headY && headY < Y)) { if (isHave[headX][headY] {if (headX == aliment.move_x && headY == aliment.move_Y){snake.addFirst(aliment);int scoreGet = (10000 - 200 * moveCount) / timeSpace;score += scoreGet > 0 ? scoreGet : 10;moveCount = 0;aliment = createAliment();isHave[aliment.move_X][aliment.move_Y] = true;return true;}else {return false;}}else {snake.addFirst(new Move(headX,headY));isHave[headX][headY] = true;snakeHead = (Move)snake.removeLast();isHave[snakeHead.move_X][snakeHead.move_Y] = false;moveCount++;return true;}}return false;}public void changeDirection(int dir) {if (move_Direction % 2 !=dir % 2) {move_Direction = dir;}}private Move createALiment(){int x = 0;int y = 0;do {Random r = new Random();x = r.nextInt(X);y = r.nextInt(Y);}while (isHave[x][y]);return new Move(x,y);}public void speedUp() {timeSpace *= speedChange;}public void speedDown() {timeSpace /= speedChange;}public void changePauseState() {paused = !paused;}public boolean isRunning() {return running;}public void setRunning(boolean running) {this.running = running;}public LinkedList getMoveList() {return snake;}public Move getAliment() {return aliment;}public int getScore() {return score;}}class SnakeFrame extends JFrame implents Observer { public static final int gridWidth = 10;public static final int gridHeight = 10;private int gameWidth;private int gameHeight;private int gameX = 0;private int gameY = 0;JLabel score;Canvas canvas;public SnakeFrame(){this(30,40,0,0);}public SnakeFrame(int X,int Y) {this(X,Y,0,0);}public SnakeFrame(int X,int Y,int startX, int startY) {this.gameWidth = X * gridWidth;this.gameaHeight = Y * gridHieght;this.gameX = startX;this.startY = startY;init();}private void init(){this.setTitle("贪吃的小蛇");this.setLocation(gameX, startY);Countainer cp = this.getContentPane();score = new JLabel("成绩:");cp.add(score, BorderLayout.SOUTH);canvas = new Canvas();canvas.setSize(gameWidth + 1,gameHeight + 1);cp.add(canvas, BorderLayout.CENTER);this.pack();this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}public void update(0bservable observer,Object obj) {MoveOperate operate = (MoveOperate)observer;Graphics graphics = canvas.getGraphics();graphics.setColor(Color,WHITE);graphics.fillRect(0,0,gameWidth,gameHeight);graphics.setColor(Color.BLACK);LinkedList list = operate.getMoveList();Interator it = List.iterator();while (it.hasNext()){Move move = (Move) it.next();drawMove(graphics,move);}graphics.setColor(Color.RED);Move move = operate.getAliment();drawMove(garphics,move);this.updateScore(operate.getScore());}private void drawMove(Graphicsq, Move n){g.fillRect(n.move_X * gridWidth,n.move_Y * gridHeight,gridWidth-1,gridHeight-1); public void updateScore(int score){String s = "成绩:"+score;this.score.setText(s);}class ControlSnake implements KeyListener{private MoveOperate snake;private SnakeFrame frame;private int X;private int Y;public ControlSnake(){this.X = 30;this.Y = 40;}public ControlSnake(int X,int Y){this();if((10 < X) && (X < 200) && (10 < Y) &&(Y < 200)){this.X = X;this.Y = Y;}else{System.out.println("初始化参数出错!");}initSnake();}private void initSnake(){this.snake = new MoveOperate(X,Y);this.frame = new SnakeFrame(X,Y,500,200);this.snake.addObserver(this.frame);this.frame.addKeyListener(this);(new Thread(this.snake)).start();}public void KeyPressed(KeyEvent e){int keyCode = e.getKeyCode();if(snake.isRunning()){switch(keyCode){case KeyEvent.VK_ADD;case KeyEvent.VK_PAGE_UP;sanke.speedUp();break;case KeyEvent.VK_SUBTRACT;case KeyEvent.VK_PAGE_DOWN;snake.speedDown();break;case KeyEvent.VK_SPACE;case KeyEvent.VK_P;snake.changePauseState();break;case KeyEvent.VK_UP;snake.changeDirection(MoveOperate.UP);break;case KeyEvent.VK_DOWN;snake.changeDirection(MoveOperate.DOWN);break;case KeyEvent.VK_LEFT;snake.changeDirection(MoveOperate.LEFT);break;case KeyEvent.VK_RIGHT;snake.changeDirection(MoveOperate.RIGHT);break;default;}}if (KeyCode == KeyEvent.VK_F || KeyCode == KeyEvent.VK_J ||KeyCode == KeyEvent.VK_ENTER){snake.resetGame();}if (KeyCode == KeyEvent.VK_S){snake.setRunning(false);}}public void KeyReleased(KeyEvent e) {}public void KeyTyped(KeyEvent e) {}public class TextEdaciousSmallSnake{public static void main(String[] args) {new ControlSnake(40,30);}}。

贪吃蛇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设计贪吃蛇游戏下面是一个简单的贪吃蛇游戏的JAVA设计示例,该示例包括游戏画面的显示、控制蛇的移动、食物的生成与吃掉、以及游戏的结束等基本功能。

首先,我们需要创建一个Snake类来表示蛇的身体。

Snake类包括一个ArrayList作为蛇的身体部分,以及一个方向变量来表示蛇的移动方向。

Snake类还有一个方法来控制蛇的移动,根据方向变量移动蛇的身体。

```javaimport java.util.ArrayList;public class Snakeprivate ArrayList<Cell> body;private Direction direction;public Snakbody = new ArrayList<>(;body.add(new Cell(10, 10)); // 初始化蛇的初始位置direction = Direction.RIGHT; // 蛇的初始方向为向右}public void movCell head = body.get(0); // 蛇头Cell newHead;//根据方向变量移动蛇头的位置switch (direction)case UP:newHead = new Cell(head.getX(, head.getY( - 1); break;case DOWN:newHead = new Cell(head.getX(, head.getY( + 1); break;case LEFT:newHead = new Cell(head.getX( - 1, head.getY(); break;case RIGHT:newHead = new Cell(head.getX( + 1, head.getY(); break;default:newHead = head; // 默认不移动}//添加新的蛇头body.add(0, newHead);//删除尾部,即移动效果body.remove(body.size( - 1);}// getter和setter方法```接下来,我们创建一个Cell类来表示每一个游戏格子的位置。

JAVA课程设计贪吃蛇小程序附代码

JAVA课程设计贪吃蛇小程序附代码

Part Two
JAVA贪吃蛇小程序 代码解析
游戏界面实现
游戏窗口:设置游戏窗口大小和位置
游戏背景:设置游戏背景颜色和图片 游戏元素:设置蛇、食物、障碍物等 元素的位置和样式
游戏控制:设置键盘控制和鼠标控制, 实现游戏的开始、暂停和结束
游戏得分:显示游戏得分和等级,以 及游戏结束提示
游戏音效:设置游戏音效和背景音乐, 增加游戏的趣味性和沉浸感
重新开始:提供重新开始游 戏的选项,重新开始游戏时, 重置游戏界面和蛇的位置
游戏控制实现
键盘控制:通过键盘输入控制蛇的移动方向 游戏循环:通过循环实现游戏的持续运行 蛇的移动:通过改变蛇的位置实现蛇的移动 食物生成:随机生成食物,增加游戏的挑战性 碰撞检测:检测蛇与食物或边界的碰撞,实现游戏的结束或重新开始
Part Four
总结
JAVA贪吃蛇小程序的特点和亮点
添加标题
简单易用:界面简洁,操作简单,适合初学者使用
添加标题
功能丰富:支持多种游戏模式,如经典模式、挑战模式等
添加标题
性能优化:采用高效的算法和优化技术,提高游戏运行速度和稳定性
添加标题
扩展性强:支持自定义皮肤、背景音乐等,满足不同用户的需求
程序实现原理
贪吃蛇游戏是一种经典的游戏,通过控制蛇的移动来获取食物,同时避免撞到墙壁或自己的身 体。
JAVA贪吃蛇小程序的实现原理主要是通过JAVA语言编写程序,实现蛇的移动、食物的生成、 碰撞检测等功能。
蛇的移动是通过改变蛇头的位置来实现的,食物的生成则是随机生成在屏幕上的某个位置。
碰撞检测则是通过判断蛇头是否与墙壁或自己的身体发生碰撞来实现的。
游戏界面: 显示贪吃 蛇和食物
游戏操作: 通过键盘 控制贪吃 蛇移动

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

/** 贪吃蛇*/ import java.awt.*;import javax.swing.*;import java.awt.event.*;public class GreedSnack extends JFrame{int i,j;WH_panel panel; JMenuBar wh_bar; // 定义WH_panel 的实例// 定义菜单实例public GreedSnack(){super(" 贪吃蛇--game--");Container c=getContentPane();setBounds(200, 200, 620, 465); c.setLayout(null);wh_bar=new JMenuBar(); setJMenuBar(wh_bar);JMenu[]m={new JMenu(" 文件"),new JMenu(" 编辑")};JMenuItem[][]mi={ // 构造函数// 框架名称// 获得框架容器// 设置frame 的大小// 设置框架布局// 定义菜单实例// 设置菜单// 主菜单// 下拉菜单项{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]);}}mi[0][0].addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e){try{panel.thread.start(); panel.right();}catch(Exception ee){}// 添加菜单// 添加下拉菜单// 小于菜单的长度// 添加//for//for// 设置菜单监听//// 开始线程// 直接执行right 函数// 对线程进行捕获错误// 包含文件}{});addKeyListener(new KeyAdapter()public void keyPressed(KeyEvent e){if(e.getKeyCode()==KeyEvent.VK_LEFT)panel.left();if(e.getKeyCode()==KeyEvent.VK_RIGHT)panel.right();if(e.getKeyCode()==KeyEvent.VK_UP)panel.up();if(e.getKeyCode()==KeyEvent.VK_DOWN)panel.down();}public void keyTyped(KeyEvent e) {}public void keyReleased(KeyEvent e) {} });// 键盘监听// 监听左键// 执行left 函数// 监听右键// 执行right 函数// 监听上键// 执行up 函数// 监听下键// 执行down 函数// 键盘事件panel=new WH_panel();panel.setLayout(null);c.add(panel);//panel 布局// 添加panel}public static void main(String args[]){GreedSnack app=new GreedSnack();app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);app.setVisible(true);}}class WH_panel extends JPanel implements Runnable // 主函数// 设置frame 的实例// 关闭窗口// 设置成可见//main //greedsnack//panel 函数{Thread thread; intx=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); thread=new Thread(this);for(i=0;i<30;i++) // 设置panel 的大小// 创建线程thread // 给数组付初值{for(j=0;j<20;j++) // 列标小于20{{wh_array[i][j]=0; } }}public void left(){if(d_r!=3){ wh_direct=1; d_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; d_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; d_u=5; d_d=7;d_l=0;d_r=0;// 将数组赋为0//for //for//WH_panel() //left函数// 假设现在向右行进//wh_direct 为 1 // 标记左不能运行// 标记上可以运行// 标记下可以运行// 假设现在不是向右行进// 向左可以运行// 右键函数// 假设现在向左行进//wh_direct 为 2// 向右不可以运行// 向上可以运行// 向下可以运行// 假设没有向左行进// 向右可以运行// 向上键函数// 假设现在向下行进//wh_direct 为 3 // 向上不可以运行// 向左可以行进// 向右可以运行}else{ d_u=0;}}public void down(){if(d_u!=5){ wh_direct=4; d_u=5; d_d=7; d_r=0; d_l=0;}else{ d_d=0;}} public void run(){while(true){ 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;} x=x-20; 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;} x=x+20;wh_run();// 假设现在没有向下运行// 可以向上行进// 向下键的函数// 如果现在向上运行//wh_direct 为 4// 现在不可向下行进// 现在可向右行进// 现在向左行进// 如果现在没有向上行进// 可以向下行进// 线程函数//while 循环// 向左方// 规定范围// 当下一个有蛇身//wh_stop=1//x 坐标减小变化// 向右方// 规定范围// 当下一个有蛇身//wh_stop=1}{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;}y=y-20;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;}y=y+20;wh_run();}if(food_x==x&&food_y==y){food_x=((int)(Math.random()*30))*20;food_y=((int)(Math.random()*20))*20;repaint(); 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 的进行绘* 图。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 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();}}。

相关文档
最新文档