<转>JAVA代码写的贪吃蛇

上一篇 / 下一篇  2010-09-29 10:56:00 / 个人分类:JAVA

  1. //************************************************************  
  2.   
  3. //游戏:每次产生5个食物,通过上下左右键控制蛇的运动方向  
  4.   
  5. //*************************************************************  
  6.   
  7. //**********************************************  
  8.  //游戏的类,控制其他各个类和游戏的进度  
  9.  //**********************************************  
  10. import java.awt.*;   
  11. import java.awt.event.*;   
  12. import javax.swing.*;   
  13.   
  14. public class GreedSnakeGame extends JFrame.   
  15. {   
  16.  private SnakeBody snakeBody;   
  17.  private GameCanvas canvas;   
  18.  private ControlPanel controlPanel;   
  19.  private boolean playing = false,first = true;   
  20.  private int level,score;   
  21.  /*   
  22.   *构造函数   
  23.   */   
  24.  public GreedSnakeGame()   
  25.  {   
  26.   setTitle("Greed Snake Game");   
  27.   setLayout(new BorderLayout(4,0));   
  28.      
  29.   level = 0;   
  30.   score = 0;   
  31.      
  32.   setSize(500,400);   
  33.   Dimension srcSize = Toolkit.getDefaultToolkit().getScreenSize();   
  34.   int x =  (srcSize.width - getSize().width)/2;   
  35.   int y = (srcSize.height - getSize().height)/2;   
  36.   setLocation(x,y);   
  37.   snakeBody = new SnakeBody(this,3);   
  38.   canvas = GameCanvas.getCanvasInstance();   
  39.   controlPanel = new ControlPanel(this);   
  40.   Container container = getContentPane();   
  41.   container.add(canvas,BorderLayout.CENTER);   
  42.   container.add(controlPanel,BorderLayout.EAST);   
  43.   addWindowListener(   
  44.      new WindowAdapter(){   
  45.     public void windowClosing(WindowEvent event)   
  46.     {   
  47.      stopGame();   
  48.      System.exit(0);   
  49.     }   
  50.    });   
  51.    setVisible(true);   
  52.  }   
  53.  /* 
  54.    * 改变蛇行走的方向 
  55.    */  
  56.  public void changeDirection(int direction)   
  57.  {   
  58.   snakeBody.changeDirection(direction);   
  59.  }   
  60.  /* 
  61.    * 判断是否正在进行 
  62.    */  
  63.  public boolean isPlaying()   
  64.  {   
  65.   return playing;   
  66.  }   
  67.  /* 
  68.   *开始游戏 
  69.   */  
  70.  public void playGame()   
  71.  {   
  72.   if(!first)   
  73.     snakeBody = new SnakeBody(this,3);   
  74.     first = false;   
  75.        controlPanel.setPlayButtonEnabled(false);   
  76.        snakeBody.start();   
  77.        playing = true;   
  78.  }   
  79.  /* 
  80.   *暂停游戏 
  81.   */  
  82.  public void pauseGame()   
  83.  {   
  84.   snakeBody.pauseMove();   
  85.   controlPanel.setPauseButtonLabel(false);   
  86.   playing = false;   
  87.  }   
  88.  /* 
  89.   *回到游戏 
  90.   */  
  91.  public void resumeGame()   
  92.  {   
  93.   snakeBody.resumeMove();   
  94.   controlPanel.setPauseButtonLabel(true);   
  95.   playing = true;   
  96.  }   
  97.  /* 
  98.   *结束游戏 
  99.   */  
  100.  public void stopGame()   
  101.  {   
  102.   snakeBody.stopMove();   
  103.   controlPanel.setPlayButtonEnabled(true);   
  104.   controlPanel.setPauseButtonLabel(true);   
  105.   reset();   
  106.   playing = false;   
  107.  }   
  108.  /* 
  109.   *重置游戏至初始状态 
  110.   */  
  111.  public void reset()   
  112.  {   
  113.   canvas.reset();   
  114.   controlPanel.reset();   
  115.  }   
  116.  /* 
  117.  *获得当前得分 
  118.  */  
  119.  public int getScore()   
  120.  {   
  121.   return score;   
  122.  }   
  123.  /* 
  124.  *设置当前得分 
  125.  */  
  126.  public void setScore(int score)   
  127.  {   
  128.   this.score = score;   
  129.  }   
  130.  /* 
  131.  *获得当前级别 
  132.  */  
  133.  public int getLevel()   
  134.  {   
  135.   return level;   
  136.  }   
  137.  /* 
  138.  *设置当前级别 
  139.  */  
  140.  public void setLevel(int level)   
  141.  {   
  142.   this.level = level;   
  143.  }   
  144.  /* 
  145.  *游戏主函数 
  146.  */  
  147.  public static void main(String []args)   
  148.  {   
  149.   GreedSnakeGame game = new GreedSnakeGame();   
  150.  }   
  151. }   
  152.   
  153. //*************************************************************************  
  154.   
  155. /*   
  156.  *蛇的节点类,保存当前节点所在的(row,col)坐标值   
  157.  *(同时也被用作食物类,因为食物所要保存的信息和此相同,没有再设)   
  158.  */   
  159.   
  160. //***************************************************************************  
  161. public class SnakeNode   
  162. {   
  163.   private int row,col;   
  164.   
  165.  /*   
  166.   *构造函数   
  167.   */   
  168.    public SnakeNode(int row,int col)   
  169.    {   
  170.  this.row = row;   
  171.  this.col = col;   
  172.    }   
  173.   
  174. /* 
  175. * 设置该节点所在的行 
  176. */  
  177.   public void setRow(int row)   
  178.   {   
  179.    this.row = row;   
  180.   }   
  181.   
  182. /* 
  183.  * 获得该节点所在的行 
  184.  */  
  185.   public int getRow()   
  186.   {   
  187.    return row;   
  188.   }   
  189.   
  190.   /* 
  191.    * 设置该节点所在的列 
  192.    */  
  193.   public void setCol(int col)   
  194.   {   
  195.    this.col = col;   
  196.   }   
  197.   
  198. /* 
  199.  * 返回该节点所在的列 
  200.  */  
  201.   public int getCol()   
  202.   {   
  203.    return col;   
  204.   }   
  205. }   
  206.   
  207. //************************************  
  208.  /*   
  209.   *游戏的主画布类   
  210.   */   
  211.   
  212. //************************************  
  213. import javax.swing.*;   
  214. import java.awt.*;   
  215.   
  216. public class GameCanvas extends JPanel   
  217. {   
  218.  private int rows = 30, cols = 30;   
  219.  private int boxWidth, boxHeight;   
  220.  private Color bgColor = Color.darkGray,   
  221.                snakeColor = Color.GREEN;   
  222.  private boolean [][]colorFlags;   
  223.  private static GameCanvas instance = null;   
  224. /*   
  225.  *构造函数私有,使用单例模式,其他类共享一个实例   
  226.  */   
  227.  private GameCanvas()   
  228.  {   
  229.   colorFlags = new boolean[rows][cols];   
  230.    for(int i = 0; i < colorFlags.length; i++)   
  231.      for(int j = 0; j<colorFlags[i].length; j++)   
  232.             colorFlags[i][j] = false;   
  233.  }   
  234.  /* 
  235.   *获得GameCanvas的实例 
  236.   */  
  237.  public static GameCanvas getCanvasInstance()   
  238.  {   
  239.    if(instance == null)   
  240.       instance = new GameCanvas();   
  241.    return instance;   
  242.  }   
  243.  /* 
  244.   *设置面板画布的行数 
  245.   */  
  246.  public void setRows(int rows)   
  247.  {   
  248.   this.rows = rows;   
  249.  }   
  250.  /* 
  251.   *得到画布方格的行数 
  252.   */  
  253.  public int getRows()   
  254.  {   
  255.   return rows;   
  256.  }   
  257.  /* 
  258.   *设置画布方格的列数 
  259.   */  
  260.  public void setCols(int cols)   
  261.  {   
  262.   this.cols = cols;   
  263.  }   
  264.   /* 
  265.    * 得到面板方格的列数 
  266.    */  
  267.  public int getCols()   
  268.  {   
  269.   return cols;   
  270.  }   
  271.  /* 
  272.   *绘图类,在画布上绘图 
  273.   */  
  274.   public void paintComponent(Graphics g)   
  275.   {   
  276.    super.paintComponent(g);   
  277.       
  278.    fanning();   
  279.    for(int i = 0; i < colorFlags.length; i++)   
  280.      for(int j = 0; j < colorFlags[i].length; j++)   
  281.       {   
  282.         Color color = colorFlags[i][j] ? snakeColor : bgColor;   
  283.         g.setColor(color);   
  284.         g.fill3DRect(j * boxWidth, i * boxHeight, boxWidth, boxHeight,true);   
  285.       }   
  286.   }    
  287.   /* 
  288.    *画布重置,恢复画布的原始状态 
  289.    */  
  290.   public void reset()   
  291.   {   
  292.    for(int i = 0; i < colorFlags.length; i++)   
  293.      for(int j = 0; j<colorFlags[i].length; j++)   
  294.             colorFlags[i][j] = false;   
  295.         repaint();   
  296.   }   
  297.   /* 
  298.   *根据窗口大小调整方格的大小 
  299.   */  
  300.   public void fanning()   
  301.   {   
  302.    boxWidth = getSize().width / cols;   
  303.    boxHeight = getSize().height / rows;   
  304.   }   
  305.   /* 
  306.    * 获取画布(row,col)位置颜色的值 
  307.    */  
  308.   public boolean getColorFlag(int row, int col)   
  309.   {   
  310.    return colorFlags[row][col];   
  311.   }   
  312.   /* 
  313.    * 设置画布(row,col)位置颜色的值 
  314.    */  
  315.   public void setColorFlag(int row, int col, boolean colorFlag)   
  316.   {   
  317.    colorFlags[row][col] =  colorFlag;   
  318.   }   
  319. }   
  320. //******************************************  
  321. /*   
  322.  *蛇身线程类,控制蛇的移动及其方向   
  323.  */   
  324.   
  325. //*******************************************  
  326. import javax.swing.*;   
  327. import java.util.*;   
  328.   
  329. class SnakeBody extends Thread   
  330. {   
  331.  private LinkedList snakeList;   
  332.  private int iniSnakeBodyLength;   
  333.  private GreedSnakeGame game;   
  334.  private GameCanvas canvas;   
  335.  public  final static int DOWN = -1;   
  336.  public final static int  LEFT = -2;   
  337.  public final static int UP = 1;   
  338.  public final static int RIGHT = 2;   
  339.  private final static int PER_LEVEL_SPEED_UP = 10;   
  340.  private final static int PER_FOOD_SCORE = 10;   
  341.  private final static int PER_LEVEL_SCORE = 20 *PER_FOOD_SCORE;   
  342.  private int direction = LEFT;   
  343.  private boolean running = true,pause = false;   
  344.  private int timeInterval = 200,curLevelScore;   
  345.  private ArrayList food;   
  346.  /*   
  347.  *构造函数   
  348.  */   
  349.  public SnakeBody(final GreedSnakeGame game,int iniSnakeBodyLength)   
  350.  {   
  351.   this.game = game;   
  352.   this.iniSnakeBodyLength = iniSnakeBodyLength;   
  353.   curLevelScore = 0;   
  354.   food = new ArrayList(5);   
  355.   canvas = GameCanvas.getCanvasInstance();   
  356.   /* 
  357.   * 初始化蛇身 
  358.   */  
  359.   snakeList = new LinkedList();   
  360.   int rows = canvas.getRows();   
  361.   int cols = canvas.getCols();   
  362.   for(int i = 0; i < iniSnakeBodyLength; i++)   
  363.   {   
  364.    snakeList.add(new SnakeNode(rows / 2, cols / 2 + i));   
  365.    canvas.setColorFlag(rows / 2, cols / 2 + i, true);   
  366.   }   
  367.   createFood();   
  368.   canvas.repaint();   
  369.  }   
  370.  /* 
  371.   *暂停移动 
  372.   */  
  373.  public void pauseMove()   
  374.  {   
  375.   pause = true;   
  376.  }   
  377.  /* 
  378.   *恢复移动 
  379.   */  
  380.  public void resumeMove()   
  381.  {   
  382.   pause = false;   
  383.  }   
  384.  /* 
  385.  *停止移动 
  386.  */  
  387.  public void stopMove()   
  388.  {   
  389.   running = false;   
  390.  }   
  391.  /* 
  392.   *每次创建食物 
  393.   */  
  394.  public void createFood()   
  395.  {    
  396.   for(int i = 0;i < 5;i++)   
  397.   {   
  398.    int x = (int)(Math.random() * canvas.getCols());   
  399.    int y = (int)(Math.random() * canvas.getRows());   
  400.    if(canvas.getColorFlag(x,y))   
  401.     i--;   
  402.    else  
  403.     food.add(new SnakeNode(x,y));   
  404.     canvas.setColorFlag(x,y,true);   
  405.    }   
  406.    canvas.repaint();   
  407.  }   
  408.  /* 
  409.   * 改变蛇的移动方向 
  410.   */  
  411.  public void changeDirection(int direction)   
  412.  {   
  413.   this.direction = direction;   
  414.  }   
  415.  /* 
  416.   *在没有改变方向时,控制蛇的移动,以及吃食物 
  417.   */  
  418.  private boolean moveOn()   
  419.  {   
  420.   SnakeNode snakeHead  = (SnakeNode)snakeList.getFirst();   
  421.   int x = snakeHead.getRow();   
  422.   int y = snakeHead.getCol();   
  423.   boolean isFood = false,isBody = false;   
  424.   switch(direction)   
  425.   {   
  426.    case LEFT: y--; break;   
  427.    case RIGHT: y++; break;   
  428.    case DOWN:  x++; break;   
  429.    case UP:   x--; break;   
  430.    default:  break;   
  431.   }   
  432.   if((x >= 0 && x < canvas.getCols()) &&( y >=0 && y < canvas.getRows()))   
  433.   {   
  434.     int i = 0;   
  435.     for(;i < food.size();i++)   
  436.      if(x == ((SnakeNode)food.get(i)).getRow() && y == ((SnakeNode)food.get(i)).getCol())   
  437.      {   
  438.       isFood = true;   
  439.         break;   
  440.      }   
  441.     for(int j=0;j < snakeList.size()-1 ;j++)   
  442.       if(x == ((SnakeNode)snakeList.get(j)).getRow() && y == ((SnakeNode)snakeList.get(j)).getCol())   
  443.       {   
  444.        isBody = true;   
  445.          break;   
  446.       }   
  447.     if(isFood)   
  448.     {   
  449.      int score = game.getScore();   
  450.      score += PER_FOOD_SCORE;   
  451.      game.setScore(score);   
  452.      curLevelScore += PER_FOOD_SCORE;   
  453.      snakeList.addFirst(new SnakeNode(x,y));   
  454.      food.remove(i);   
  455.         
  456.       if(food.size() == 0)   
  457.                {     
  458.              if(curLevelScore >= PER_LEVEL_SCORE)   
  459.              {    
  460.             int level = game.getLevel();   
  461.               level++;   
  462.               game.setLevel(level);   
  463.               curLevelScore -=PER_LEVEL_SCORE;    
  464.               }        
  465.         createFood();   
  466.        }   
  467.     }   
  468.     else if(isBody)   
  469.     {   
  470.      JOptionPane.showMessageDialog(null,"You Failed","Game Over",   
  471.                          JOptionPane.INFORMATION_MESSAGE);   
  472.                  running = false;         
  473.     }   
  474.     else  
  475.     {   
  476.      snakeHead = new SnakeNode(x,y);   
  477.      snakeList.addFirst(snakeHead);   
  478.      canvas.setColorFlag(x,y,true);   
  479.      SnakeNode snakeTail = (SnakeNode)snakeList.getLast();   
  480.      snakeList.removeLast();   
  481.      canvas.setColorFlag(snakeTail.getRow(),snakeTail.getCol(),false);   
  482.      canvas.repaint();   
  483.     }   
  484.     return true;   
  485.   }   
  486.     return false;     
  487.  }   
  488.  /* 
  489.   *run方法,控制线程运行要处理的事务 
  490.   */  
  491.  public void run()   
  492.  {   
  493.   while(running)   
  494.   {   
  495.    try  
  496.    {   
  497.     sleep(timeInterval-game.getLevel() * PER_LEVEL_SPEED_UP);   
  498.        
  499.    }catch(InterruptedException e)   
  500.    {   
  501.     e.printStackTrace();   
  502.    }   
  503.    if(!pause)   
  504.    {   
  505.     if(!moveOn())   
  506.     {   
  507.       JOptionPane.showMessageDialog(null,"You Failed","Game Over",   
  508.                                          JOptionPane.INFORMATION_MESSAGE);   
  509.                   running = false;                                  
  510.      }   
  511.    }   
  512.   }   
  513.  }   
  514. }   
  515.   
  516. //********************************  
  517. /*   
  518.  *控制面板类   
  519.  */   
  520.   
  521. //*********************************  
  522. import java.awt.*;   
  523. import java.awt.event.*;   
  524. import javax.swing.*;   
  525. import javax.swing.border.*;   
  526.   
  527. class ControlPanel extends JPanel   
  528. {   
  529.  private JPanel infoPanel,buttonPanel;   
  530.  private SnakePanel snakePanel;   
  531.  private JTextField levelField;   
  532.  private JTextField scoreField;   
  533.  private JButton playButton, pauseButton, stopButton,   
  534.                  turnEasilyButton, turnHarderButton;   
  535.  private Timer timer;   
  536.  private GreedSnakeGame game;   
  537.  private EtchedBorder border = new EtchedBorder(EtchedBorder.RAISED,Color.white,Color.lightGray);   
  538. /*   
  539.  *构造函数   
  540.  */    
  541.  public ControlPanel(final GreedSnakeGame game)   
  542.  {   
  543.    this.game = game;   
  544.    setLayout(new GridLayout(3,1,0,4));   
  545.       
  546.    snakePanel = new SnakePanel();   
  547.    snakePanel.setBorder(border);   
  548.    levelField = new JTextField("0");   
  549.    scoreField = new JTextField("0");   
  550.    infoPanel = new JPanel(new GridLayout(4,1,0,0));   
  551.    infoPanel.add(new JLabel("Level:"));   
  552.    infoPanel.add(levelField);   
  553.    infoPanel.add(new JLabel("Score:"));   
  554.    infoPanel.add(scoreField);   
  555.    infoPanel.setBorder(border);   
  556.       
  557.    playButton = new JButton("Play");   
  558.    pauseButton = new JButton("Pause");   
  559.    stopButton = new JButton("Stop");   
  560.    turnEasilyButton = new JButton("Turn Easily");   
  561.    turnHarderButton = new JButton("Turn Harder");   
  562.    buttonPanel = new JPanel(new GridLayout(5,1,0,1));   
  563.    buttonPanel.add(playButton);   
  564.    b

TAG:

 

评分:0

我来说两句

Open Toolbar