黄色网址大全免费-黄色网址你懂得-黄色网址你懂的-黄色网址有那些-免费超爽视频-免费大片黄国产在线观看

專注Java教育14年 全國(guó)咨詢/投訴熱線:400-8080-105
動(dòng)力節(jié)點(diǎn)LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁(yè) hot資訊 Java小游戲源代碼之貪吃蛇

Java小游戲源代碼之貪吃蛇

更新時(shí)間:2021-05-11 10:16:31 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1027次

Java貪吃蛇小游戲之啟動(dòng)界面

package snakeGame;
/* Test類的主要任務(wù)是設(shè)計(jì)程序運(yùn)行后的界面,包括 程序啟動(dòng)的界面和游戲運(yùn)行界面。
 * 程序啟動(dòng)的界面包括背景圖片和進(jìn)入運(yùn)行界面的Button,點(diǎn)擊按鈕之后程序關(guān)閉啟動(dòng)界面進(jìn)入到運(yùn)行界面,
 * 運(yùn)行界面設(shè)置在SnakeGame類中,Test類大體設(shè)置了運(yùn)行界面的大小可見(jiàn)與否等。
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Start    extends JFrame implements ActionListener  {	   
	static  JFrame frame = new  JFrame( );
	public static void main(String[] args) {	
    	 new  Start();                                         
    }
	public  Start(){                                                 //設(shè)置啟動(dòng)界面
		 frame.setUndecorated(true);                                //用于取消邊框背景
         frame.setLayout (null);
         frame.setSize(1600,900);
         frame.setLocation(300, 100);
         frame.setLocationRelativeTo (null);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
         AddButton();
         AddPicture();            
	}  	
	//定義進(jìn)入游戲按鈕	
	public  void  AddButton() {	                                      
		RButton  enterButton =new RButton("進(jìn)入游戲");
        enterButton.setFont(new Font("華文行楷", Font.BOLD, 35));
        enterButton.setForeground(Color.red);
        enterButton.setBounds (700,  600 , 200, 100);
        enterButton.setBackground(Color.white);      
        frame.add(enterButton);
        enterButton.addActionListener(this); 
        //定義按鍵         
	}
  //加入背景圖片
	public  void  AddPicture() {	                                           	
		ImageIcon img = new ImageIcon("F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\timg.jpg");
        JLabel Label= new JLabel(img);
        Label.setBounds(0,0,img.getIconWidth(),img.getIconHeight());            //設(shè)置大小
        frame.getLayeredPane().add(Label,new Integer(Integer.MIN_VALUE));      //設(shè)置圖片底層和按鈕在容器中的順序   
        JPanel  jp  =(JPanel)frame.getContentPane();   
        jp.setOpaque(false);                                                   //設(shè)置透明與否
	}
	
	/*設(shè)置按鈕的監(jiān)聽(tīng)器事件
	 * 進(jìn)入按鈕的監(jiān)聽(tīng)器事件的主要功能是當(dāng)點(diǎn)擊按鈕以后,程序關(guān)掉啟動(dòng)界面,并轉(zhuǎn)入運(yùn)行界面。
	 * 主要實(shí)現(xiàn)原理是定義一個(gè)新界面的類,作為運(yùn)行界面,然后定義一個(gè)關(guān)掉啟動(dòng)界面的方法,然后在監(jiān)聽(tīng)器事件中,
	 * 調(diào)用關(guān)掉界面的方法,實(shí)例化運(yùn)行界面 
	 */
	@Override	 
	public void actionPerformed(ActionEvent e) {                                  
		new  pushButtonMusic ();		 
		// TODO 自動(dòng)生成的方法存根
		closeThis();		                                                       //關(guān)掉新界面的方法
	    try {	    
			new Frame2 ();                                                         //實(shí)例化運(yùn)行界面
		} catch (InterruptedException e1) {
			// TODO 自動(dòng)生成的 catch 塊
			e1.printStackTrace();
		}  //創(chuàng)建新的窗體,以達(dá)到切換窗體的效果
	}	
	 private void closeThis() {
		// TODO 自動(dòng)生成的方法存根
		 frame.dispose();
	}
	 /*
	  * 游戲運(yùn)行界面,實(shí)例化SnakeGame類,并加入到運(yùn)行界面中
	  */
	 class  Frame2 extends JFrame      {  		 	 		   		  			  
		     JFrame    frame1 = new  JFrame(); //游戲圖形界面            
		      public   Frame2() throws InterruptedException{			  				 					    		  		  
			  frame1.setUndecorated(true);
			  frame1.setBounds(200,70,1600,900);		           		 
			//  frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			  frame1.setVisible(true);			  
	          SnakeGame sn = new SnakeGame();	         
	          frame1.add(sn);
	          sn.requestFocus();//布局的中間	         	         
			}			 
      }	 
}

Java貪吃蛇小游戲之運(yùn)行界面:

package snakeGame;
/*
 * SnakeGame類來(lái)設(shè)計(jì)貪吃蛇小游戲的運(yùn)行界面,運(yùn)行界面是貪吃蛇游戲的主體部分,  界面主要包括兩個(gè)方面的內(nèi)容,
 * 一方面是運(yùn)行界面的內(nèi)容,貪吃蛇長(zhǎng)度顯示,游戲說(shuō)明,速度控制,游戲開(kāi)始,暫停退出等按鈕。
 * 另一方面,主要包括貪吃蛇的形狀和移動(dòng),貪吃蛇移動(dòng)區(qū)域,隨機(jī)點(diǎn)的定義
 * 運(yùn)行界面的過(guò)程是這樣的:在開(kāi)始姐愛(ài)你點(diǎn)擊進(jìn)入游戲按鈕以后,程序運(yùn)行到運(yùn)行界面,開(kāi)始播放背景音樂(lè)。
 * 點(diǎn)擊游戲說(shuō)明按鈕,彈出一個(gè)對(duì)話框,說(shuō)明游戲運(yùn)行的操作過(guò)程。點(diǎn)擊開(kāi)始按鈕以后,
 * 貪吃蛇開(kāi)始向上移動(dòng),鼠標(biāo)在向上區(qū)域點(diǎn)擊,貪吃蛇向上,向左區(qū)域點(diǎn)擊,貪吃蛇向左,依次賴推。
 * 當(dāng)貪吃蛇碰到草莓時(shí),吃掉它,蛇身變長(zhǎng),并有背景音樂(lè)顯示,長(zhǎng)度顯示加一,
 * 點(diǎn)擊暫停按鈕游戲暫停,點(diǎn)擊退出按鈕后,退出游戲。
 * 當(dāng)貪吃蛇撞到自己或者墻體的時(shí)候,貪吃蛇會(huì)死亡,然后彈出一個(gè)界面,重啟界面,用來(lái)決定游戲繼續(xù)進(jìn)行或者退出游戲。
 * 貪吃蛇的形狀和移動(dòng)通過(guò)數(shù)組的形式實(shí)現(xiàn),在界面中,定義一個(gè)x軸和y軸定義的坐標(biāo)系,定義一個(gè)數(shù)組,數(shù)組的移動(dòng)就是貪吃蛇的移動(dòng),
 * 移動(dòng)方式是貪吃蛇坐標(biāo)的改變,可以通過(guò)鼠標(biāo)控制或鍵盤控制來(lái)實(shí)現(xiàn)貪吃蛇的移動(dòng),
 * 隨機(jī)點(diǎn)產(chǎn)生是在坐標(biāo)系中產(chǎn)生隨機(jī)數(shù)來(lái)實(shí)現(xiàn),
 */
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Time;
import java.util.Date;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.TimerTask;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
import java.applet.AudioClip;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JApplet;
public class SnakeGame extends JPanel  implements ActionListener   {	 
      private final int length = 15;//定義活動(dòng)范圍
      private final int width = 25;//定義活動(dòng)范圍
      private final int unit = 45;//定義單位長(zhǎng)度
      private final  int GameLOCX=40;
      private final  int  GameLOCY=40;
      private  final int GameWidth=width*unit;
      private  final  int GameLength=length*unit;
      //隨機(jī)點(diǎn)坐標(biāo)   
      int newY1 =0 ; 
      int newX1 = 0 ;        
      int mousex=1;
      int mousey=1;
      //播放背景音樂(lè)
      AudioClip christmas = loadSound ("F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\Music\\backgroundMusic.wav");
      int direction = 1;//定義一個(gè)按下按鈕后要去的方向                 
      private ArrayList<SnakeNode> snake = new ArrayList<>();//定義蛇身的數(shù)組集合
      private int Direction;//定義蛇頭的方向
      private int Length ;//定義蛇身的長(zhǎng)度
      private SnakeNode newNode = new SnakeNode(1,1,Color.BLACK);//定義隨機(jī)點(diǎn)          
       boolean  startFlag  =false;
      //定義按鈕,速度控制,開(kāi)始暫停退出按鈕等
       RButton   SspeedButton , TspeedButton,FspeedButton,THspeedButton ,ShowButton; 
       RButton    startButton , stopButton , quitButton  ,reStartButton,closeButton;
       //定義標(biāo)簽,長(zhǎng)度顯示,方向顯示,按鈕提示等   
       JLabel  snakeScore, label1,  label3,label4;
       //初始速度控制
       private static int Difficult_Degree=1;
       //蛇的移動(dòng)控制,利用線程來(lái)實(shí)現(xiàn)用鼠標(biāo)控制,利用計(jì)時(shí)器來(lái)實(shí)現(xiàn)用鍵盤控制。
      Thread  tr= new Thread(new ThingsListener());
      Timer time = new Timer(1000, new ThingsListener1());//定義一個(gè)定時(shí)器對(duì)象,這里我們還要?jiǎng)?chuàng)建一個(gè)ThingsListener事件      
      public SnakeGame() {//初始化區(qū)域
    	 //循環(huán)播放背景音樂(lè)
    	  christmas.loop ();    	  
    	 // time.start(); 
         tr.start();   	 
    	  //定義按鍵
         //在容器中添加按鈕標(biāo)簽等的時(shí)候,需要說(shuō)明布局管理為空,不然的話,加進(jìn)去的按鈕會(huì)按照一定的布局來(lái)實(shí)現(xiàn),
    	  this.setLayout (null);
    	  //定義按鈕
         startButton = new  RButton("開(kāi)始游戲"); 	 
		  stopButton =new  RButton("暫停游戲");
		  quitButton =new  RButton("退出游戲");		  
		  FspeedButton =new  RButton("速度一");		          
		  SspeedButton =new  RButton("速度二");
		  TspeedButton=new  RButton("速度三");
		  THspeedButton=new  RButton("速度四");		
	      ShowButton  =new   RButton("游戲指南");		  	
	      //定義標(biāo)簽
		  snakeScore =new  JLabel("3");
		  label1 =new  JLabel("當(dāng)前長(zhǎng)度");		   		 
		  label3 =new  JLabel("速度設(shè)置");
		  label4 =new  JLabel( );          
		  //設(shè)置字體
		  startButton.setFont(new Font("華文行楷", Font.BOLD, 35));
		  stopButton.setFont(new Font("華文行楷", Font.BOLD, 35));
		  quitButton.setFont(new Font("華文行楷", Font.BOLD, 35));		 
		  FspeedButton.setFont(new Font("華文行楷", Font.BOLD, 15));
		  TspeedButton.setFont(new Font("華文行楷", Font.BOLD, 15));
		  SspeedButton.setFont(new Font("華文行楷", Font.BOLD, 15));
		  THspeedButton.setFont(new Font("華文行楷", Font.BOLD, 15));		 
		  ShowButton.setFont(new Font("華文行楷", Font.BOLD, 30));		  
		  label1.setFont(new Font("華文行楷", Font.BOLD, 35));
		  snakeScore.setFont(new Font("華文行楷", Font.BOLD, 50));		  		 	 
		  label3.setFont(new Font("華文行楷", Font.BOLD, 30));
		  label4.setFont(new Font("華文行楷", Font.BOLD, 35));
		 //定義按鈕標(biāo)簽位置
	      startButton.setBounds (1390, 500 , 190, 90);
	      stopButton.setBounds (1390,  600 , 190, 90);
	      quitButton.setBounds (1390,  700 , 190, 90);
	      snakeScore.setBounds(1450, 70, 150, 90);
	      label1.setBounds(1390, 10, 190, 90);	      
	      ShowButton.setBounds(1390, 170, 190, 90);	     
	      label3.setBounds(1390, 270, 190, 90);
	      label4.setBounds(0, 0, 190, 90);         
	      FspeedButton.setBounds (1390, 350 , 85, 60);
	      SspeedButton.setBounds (1500,350 , 85, 60);
	      TspeedButton.setBounds (1390, 420 , 85, 60);
	      THspeedButton.setBounds (1500, 420 , 85, 60);	     
	      THspeedButton.setBackground(Color.green);
		  SspeedButton.setBackground(Color.blue);
		  TspeedButton.setBackground(Color.red);
	      FspeedButton.setBackground(Color.red);		  	      
	     // 添加 按鈕和標(biāo)簽,用this關(guān)鍵字指向當(dāng)前容器	   
         this.add(startButton);
         this.add(stopButton);
         this.add(quitButton);
         this.add(FspeedButton);
         this.add(SspeedButton);
         this.add(TspeedButton);
         this.add(THspeedButton);                         
         this.add(label1);
         this.add(snakeScore);        
         this.add( ShowButton);
         this.add(label3);
         this.add(label4);         
        // 添加三個(gè)按鍵的監(jiān)聽(tīng)事件
         startButton.addActionListener(this);
         stopButton.addActionListener(this);
         quitButton.addActionListener(this);            
         THspeedButton.addActionListener(this);
         SspeedButton.addActionListener(this);
         TspeedButton.addActionListener(this);
         FspeedButton.addActionListener(this);
          ShowButton.addActionListener(this);            
         snake.add(new SnakeNode(width/2,length/2 ,Color.red));
         snake.add(new SnakeNode(width/2,length/2+1 ,Color.blue));
         snake.add(new SnakeNode(width/2,length/2+2 ,Color.green));    	 
          Direction = 1;//定義初始方向?yàn)橄蛏?
          Length = 3;//蛇身長(zhǎng)度為3
          CreateNode1();//產(chǎn)生隨機(jī)點(diǎn)
         // CreateNode2();
     /*//采用鍵盤控制的控制模式,利用鍵盤的上下左右鍵,來(lái)實(shí)現(xiàn)讓·direction的變化,從而使貪吃蛇能夠按照鍵盤的控制來(lái)實(shí)現(xiàn)移動(dòng)
        this.addKeyListener(new KeyAdapter() {//捕捉鍵盤的按鍵事件 設(shè)置監(jiān)聽(tīng)器
            public void keyPressed(KeyEvent e) {            	 
                switch(e.getKeyCode()) {
                    case KeyEvent.VK_UP://按下向上,返回1
                        direction = 1;
                        break;
                    case KeyEvent.VK_DOWN://按下向下,返回-1
                        direction = -1;
                        break;
                    case KeyEvent.VK_LEFT://按下相左,返回2
                        direction = 2;
                        break;
                    case KeyEvent.VK_RIGHT://按下向右,返回-2
                        direction = -2;
                        break;
                    default:
                        break;
                }
                if(direction + Direction !=0) {//不能反向運(yùn)動(dòng)
                    Direction = direction;
                    Move(direction);
                    repaint();
                }
            }
        });
        */             
        //采用 鼠標(biāo)控制的控制模式     通過(guò)監(jiān)聽(tīng)鼠標(biāo)在容器中的位置,點(diǎn)擊上下左右區(qū)域,改變direction的值,即可實(shí)現(xiàn)貪吃蛇的移動(dòng),
          this.addMouseListener(new MouseAdapter(){  //匿名內(nèi)部類,鼠標(biāo)事件
              public void  mousePressed(MouseEvent e){ 
            	  int a=0;//鼠標(biāo)完成點(diǎn)擊事件
                     //e.getButton就會(huì)返回點(diǎn)鼠標(biāo)的那個(gè)鍵,左鍵還是右健,3代表右鍵
                       mousex = e.getX();  //得到鼠標(biāo)x坐標(biāo)
                       mousey = e.getY();  //得到鼠標(biāo)y坐標(biāo)
                       double  k=0.6;            //直線斜率
                       double  Y1=0.6*mousex;
                       double  Y2=-0.6*mousex+810;
                       double   X1=1.6*mousey;
                       double   X2=-1.6*mousey+1350;
                       if(mousex > X1&&mousex<X2&&mousey>0&&mousey<405) {   //第一象限  		向上
                    	   label4.setText( "向上" );
                       	a=1;   	 
                       }
                       if(mousex>X2&&mousex<X1&&mousey>405&&mousey<810) {  // 第二象限             向下
                    	   label4.setText( "  向下" );
                       	 a=2;
                           }
                 if(mousex>0&&mousex<675&&mousey>Y1&&mousey<Y2) {    //第三象限     向左
                    	   label4.setText( " 向左" );
                       	 a=3;
                            }   
                       if(mousex>675&&mousex<1350&&mousey>Y2&&mousey<Y1) {   //第四象限    向右
                    	   label4.setText( "  向右" );
                           a=4;
                           } 
                
                      switch( a) {
                      case  1://按下向上,返回1
                          direction = 1;
                          break;
                      case 2://按下向下,返回-1
                          direction = -1;
                          break;
                      case 3://按下相左,返回2
                          direction = 2;
                          break;
                      case 4://按下向右,返回-2
                          direction = -2;
                          break;
                      default:
                          break;
                  }
                      if(direction + Direction !=0) {//不能反向運(yùn)動(dòng)
                          Direction = direction;
                          Move(direction);
                            repaint();
                  }
                }
               
          });         
      } 
   /*定義蛇移動(dòng)的方法  
    *   貪吃蛇的移動(dòng)方法主要包括方向控制,碰到隨機(jī)點(diǎn),碰到自己,碰到邊界以及設(shè)計(jì)貪吃蛇從前向后的移動(dòng)
    * 
    */
      public void Move(int direction) {                 	 
        int FirstX = snake.get(0).getX();            //獲取蛇第一個(gè)點(diǎn)的橫坐標(biāo)
        int FirstY = snake.get(0).getY();            //獲取蛇第一個(gè)點(diǎn)的縱坐標(biāo)                  
        if(!startFlag) 
            return ; 
        //方向控制
        switch(direction) {
            case 1:
                FirstY--;
                break;
            case -1:
                FirstY++;
                break;
            case 2: 
                FirstX--;
                break;
            case -2:
                FirstX++;
                break;
            default:
                break;
        }
      //當(dāng)碰到隨機(jī)點(diǎn)時(shí)
        if(FirstX == newNode.getX()&&FirstY == newNode.getY()) { 
        	new  eatFoodMusic();
            getNode();
            return;
        }
      //當(dāng)碰到蛇身自己時(shí)
        for(int x = 0; x < Length; x++) { 
            if((FirstX==snake.get(x).getX())&&(FirstY == snake.get(x).getY())) {
            	startFlag=false;
            	new  DeadMusic();
            	 new  Restart();   
            	 christmas.stop ();
            }
        }
         //當(dāng)貪吃蛇撞到邊界
        if(FirstX < 1  || FirstX >29  || FirstY < 1 || FirstY >18) {        	
        	startFlag=false;
        	new  DeadMusic();
        	new  Restart();
        	 christmas.stop ();
        //	new  Test();
        } 
        //定義循環(huán),使得貪吃蛇從前向后移動(dòng)
        for(int x = Length - 1; x > 0; x--) {
            snake.get(x).setX(snake.get(x-1).getX());
            snake.get(x).setY(snake.get(x-1).getY());
        }
        snake.get(0).setX(FirstX);
        snake.get(0).setY(FirstY);
        repaint();
    }    
      //獲取隨機(jī)點(diǎn)
	public void getNode() {                            
        snake.add(new SnakeNode());
        Length++;        
        for(int x = Length-1; x >0; x--) {
            snake.get(x).setX(snake.get(x-1).getX());
            snake.get(x).setY(snake.get(x-1).getY());
            snake.get(x).setColor(snake.get(x-1).getColor());
        }
        snakeScore.setText( ""+( Length ));         //定義蛇的長(zhǎng)度
        snake.get(0).setX(newNode.getX());
        snake.get(0).setY(newNode.getY());
        snake.get(0).setColor(newNode.getColor());
        CreateNode1();//產(chǎn)生隨機(jī)點(diǎn)
       // CreateNode2();
        repaint();
        //當(dāng)長(zhǎng)度超過(guò)10的時(shí)候,產(chǎn)生鼓掌聲
        if(Length==10) {
        	new  applauseMusic();
        }
    }   
	public void CreateNode1() {                     //創(chuàng)造隨機(jī)點(diǎn)的方法                                             
           Boolean flag = true;
           while(flag) {
        	  newY1 = new Random().nextInt(15)+1;     
        	  newX1= new Random().nextInt(25)+1; 
        	  for(int x = 0; x < Length; x++) {
        	        if(snake.get(x).getX() == newX1 && snake.get(x).getY() == newY1) {
        	        flag = true;
        	        break;
        	        }
        	        flag = false; 
        	    }
        	//隨機(jī)點(diǎn)不能超出面板,并且不能出現(xiàn)在蛇身上
                   
              for(int i = 0; i < Length; i++) {
                  if(snake.get(i).getX()> 5&& snake.get(i).getX()<newX1  &&snake.get(i).getY() > 5
                		  && snake.get(i).getY()<newY1) {    
                      flag = true;
                      break;
                     }
                    flag= false;
              }
        }                
       Color color = new Color(new Random().nextInt(255),new Random().nextInt(255),new Random().nextInt(255));
        newNode.setColor(color);
        newNode.setX(newX1);                                
        newNode.setY(newY1);                  
    }	
/*
 * 這里是自己新建一個(gè)事件處理,每隔Timer的時(shí)間間隔,就開(kāi)始移動(dòng)Directon的位置,
 * 由因?yàn)镈irection的位置是構(gòu)造方法中定義好的,所以就會(huì)自動(dòng)地移動(dòng)方向。而每當(dāng)玩家使用鍵盤時(shí),Direction的值變化,之后每次自動(dòng)移動(dòng)的方向也隨之變化。
 * 
 * 
 */
	//定義內(nèi)部類,貪吃蛇不斷移動(dòng)	
	public class ThingsListener1 implements ActionListener {
	    public void actionPerformed(ActionEvent e) {
	        Move(direction);
	        }
	    }// 
	public AudioClip loadSound ( String filename )
    {
     URL url = null;
      try
   {
    url = new URL ("file:" + filename);
    }
   catch (MalformedURLException e)
   {}
   return JApplet.newAudioClip (url);
   }	
	/*
	 * 當(dāng)startflag為真的時(shí)候,貪吃蛇在線程時(shí)間的脈沖下繼續(xù)移動(dòng),這個(gè)過(guò)程包含在if語(yǔ)句塊中,當(dāng)程序啟動(dòng)時(shí),每隔1.2s就有一個(gè)響應(yīng), 
	 *上一個(gè)方法采用Timer, Timer的構(gòu)造方法是Timer(int delay, ActionListner listener)通俗的說(shuō)就是創(chuàng)建一個(gè)每 delay秒觸發(fā)一次動(dòng)作的計(jì)時(shí)器,
	 * 每隔特定的時(shí)間就會(huì)觸發(fā)特定的事件。可以使用start方法啟動(dòng)計(jì)時(shí)器。
	 * 優(yōu)點(diǎn)在于形式簡(jiǎn)單,缺點(diǎn)在于當(dāng)采用速度控制的時(shí)候不易控制,而同樣作為時(shí)間觸發(fā)作用的線程控制可以實(shí)現(xiàn)這個(gè)目的,即通過(guò)控制時(shí)間來(lái)控制貪吃蛇的移動(dòng)速度
	 * 之所以之前的設(shè)計(jì)有錯(cuò)誤,在于while后面沒(méi)有用if進(jìn)行startflag的檢驗(yàn),即startflag只有在真的條件下才可以移動(dòng),時(shí)間脈沖觸發(fā)下才可以移動(dòng)。
	 * 
	 * 	 
	*/
	//定義線程類,使得貪吃蛇能夠在線程的控制下不斷移動(dòng)
    class ThingsListener  implements  Runnable   {
		@Override
		public void run() {
			// TODO 自動(dòng)生成的方法存根
			while( true) {
				if(startFlag) {      
				Move(Direction);
				repaint();
				}
				try {					
					Thread.sleep(1200/Difficult_Degree);
				}catch(InterruptedException  e){
					e.printStackTrace();
				}
			}	 		
		}//設(shè)置一個(gè)監(jiān)聽(tīng)器事件,用來(lái)控制蛇的不斷移動(dòng)       
    }
   //定義圖像類,畫出貪吃蛇移動(dòng)的運(yùn)行界面,如貪吃蛇的形狀,背景圖片,蛇頭蛇尾等      
   //描述蛇函數(shù)的主體形狀,隨機(jī)點(diǎn)的形狀和蛇的形狀    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//加背景
        Image  im=Toolkit.getDefaultToolkit().getImage("F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\background1.jpg");
        g.drawImage(im, 0, 0, this.getWidth(), this.getHeight(), this);//畫出蛇頭
      		if(direction ==1||Direction==1){      			     			
      			Toolkit toolup = this.getToolkit();
      	        Image headup =  toolup.getImage( "F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\up.png");
      	        g.drawImage(headup,snake.get(0).getX()*unit, snake.get(0).getY()*unit, unit, unit,this);     	        
      		}else if(direction ==-1){     			      	
      			 Toolkit tooldown = this.getToolkit();
      	        Image headdown =  tooldown.getImage( "F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\down.png");
      	        g.drawImage(headdown,snake.get(0).getX()*unit, snake.get(0).getY()*unit, unit, unit,this);      	        
      		}else if(direction ==2){
            	Toolkit toolleft = this.getToolkit();
      	        Image headleft =  toolleft.getImage( "F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\left.png");
      	        g.drawImage(headleft,snake.get(0).getX()*unit, snake.get(0).getY()*unit, unit, unit,this);      		
      		}else if(direction ==-2){     			 
      			Toolkit toolright = this.getToolkit();
      	        Image headright =  toolright.getImage( "F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\right.png");
      	        g.drawImage(headright,snake.get(0).getX()*unit, snake.get(0).getY()*unit, unit, unit,this);
      	     	}      	      		
      	//畫出食物的形狀	      	 
        Toolkit tool1 = this.getToolkit();
        Image food=  tool1.getImage( "F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\food.png");
        g.drawImage(food,newNode.getX()*unit, newNode.getY()*unit, unit, unit,this);               
        Toolkit tool2 = this.getToolkit();
        Image food1=  tool2.getImage( "F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\food.png");
        g.drawImage(food1,newNode.getX()*unit, newNode.getY()*unit, unit, unit,this);                         
      //繪制指定矩形的邊框。矩形的左邊和右邊位于 x 和 x + width。頂邊和底邊位于 y 和 y + height。使用圖形上下文的當(dāng)前顏色繪制該矩形。
        g.drawRect(40, 30, 1350, 810 );             
        for(int x = 1; x < Length-1; x++) {                   //利用循環(huán),來(lái)繪制蛇的形狀
            g.setColor(snake.get(x).getColor());
            g.fillOval(snake.get(x).getX()*unit, snake.get(x).getY()*unit, unit, unit);   //給蛇的每一個(gè)節(jié)點(diǎn)畫橢圓                  
        }                     
          for(int x = Length-1; x < Length; x++) {        	       
        Toolkit toolright = this.getToolkit();
          Image headright =  toolright.getImage( "F:\\MYJAVA\\Myprogram\\Snakeexample\\src\\image\\body.png");
  	       g.drawImage(headright,snake.get(x).getX()*unit, snake.get(x).getY()*unit, unit,unit,this);//利用循環(huán),來(lái)繪制蛇的形狀           
        }
   }                    
    //設(shè)置按鈕的監(jiān)聽(tīng)器事件
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO 自動(dòng)生成的方法存根
		//按開(kāi)始鍵
		if(e.getSource() == startButton) {
			new  pushButtonMusic ();
            startFlag = true;
            startButton.setEnabled(false);
            stopButton.setEnabled(true);             
        }//按暫停鍵
        if(e.getSource() == stopButton) {
        	new  pushButtonMusic ();
            startFlag = false;
            startButton.setEnabled(true);
            stopButton.setEnabled(false);             
     }
          //        退出程序
        if(e.getSource() == quitButton) {        	 
            System.exit(0);
        }//按游戲指南建
        if(e.getSource() ==  ShowButton) {
        	new  pushButtonMusic ();
        	 JDialog frame = new JDialog();//構(gòu)造一個(gè)新的JFrame,作為新窗口。
             frame.setBounds( 600,300,815,515 );             
             JTextArea  Myarea=new  JTextArea(3,10);
              Myarea.setText( " \n " 
                     +"這個(gè)小游戲點(diǎn)擊開(kāi)始按鈕后貪吃蛇開(kāi)始移動(dòng), 鼠標(biāo)前后左右移動(dòng)\n"+"會(huì)使貪吃蛇也前后左右移動(dòng)。\n"
                     + "你的任務(wù)是通過(guò)控制蛇的移動(dòng)來(lái)吃掉小草莓,這樣貪吃蛇就長(zhǎng)大了。\n"
                     +"點(diǎn)擊暫停游戲按鈕可以使得貪吃蛇停止移動(dòng),"
                     +"點(diǎn)擊退出游戲按鈕自然游\n"+"戲就結(jié)束啦!\n"
                     + "點(diǎn)擊速度一,速度二等按鈕就可以控制貪吃蛇的移動(dòng)速度 \n" 
                     );			 
		     frame.setLayout(null);              
              Myarea.setBounds( 10,10,815,350);             			 
             Myarea.setFont(new Font("華文行楷",Font.BOLD,25));          
             frame.add(Myarea);           
             frame.setModalityType(JDialog.ModalityType.APPLICATION_MODAL);    // 設(shè)置模式類型。
             frame.setVisible(true);              
     }//按速度一鍵
        if(e.getSource() == FspeedButton) {
        	new speedButtonMusic ();
        	  Difficult_Degree= 2;                      	
     }//按速度二鍵
        if(e.getSource() == SspeedButton) {
        	new speedButtonMusic ();            
        	 Difficult_Degree=  3;        	
     }//按速度三鍵
        if(e.getSource() == TspeedButton) {
        	new speedButtonMusic ();
        	 Difficult_Degree= 4;        	        	
     }//按速度四鍵
        if(e.getSource() == THspeedButton) {
        	new  speedButtonMusic ();
        	 Difficult_Degree= 5;      	
     }
        this.requestFocus();
    } 	 
}

以上就是動(dòng)力節(jié)點(diǎn)小編介紹的"Java小游戲源代碼之貪吃蛇",希望對(duì)大家有幫助,如有疑問(wèn),請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為您服務(wù)。

提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)

  • 全國(guó)校區(qū) 2025-05-15 搶座中
  • 全國(guó)校區(qū) 2025-06-05 搶座中
  • 全國(guó)校區(qū) 2025-06-26 搶座中
免費(fèi)課程推薦 >>
技術(shù)文檔推薦 >>
主站蜘蛛池模板: 五月婷婷爱 | 亚洲 欧美 激情 另类 自拍 | 高清日韩在线 | 极品嫩模众筹福利写真视频 | 久久精品国产免费中文 | 欧美不卡精品中文字幕日韩 | 免费在线观看日韩 | 黄色a一级视频 | 国产 欧美 日本 | 国产成人综合在线 | 乱系列h全文阅读小黄文肉 乱色美www女麻豆 | 国产亚洲欧美日韩在线一区 | 黄色一级免费 | 国内精品 大秀视频 日韩精品 | 一级欧美日韩 | 欧美中文在线视频 | 曰鲁夜鲁鲁狠狠综合 | 在线观看国产一区二三区 | 天天搞天天色 | a级毛片无码免费真人 | 最近2019年最中文字幕视频 | 99九九视频高清在线 | 日韩福利社 | 国产麻豆久久 | 91精品国产高清久久久久久91 | 免费看大片视频 | 欧美第一福利 | 看全色黄大色黄大片色责看的 | 伊人热人久久中文字幕 | 青青网视频 | 欧美性猛交xxx黑人猛交 | 国产黄色在线网站 | 一本无线乱码不卡一二三四 | 亚洲免费网站观看视频 | 欧美成人伦理 | 91妖精视频 | 2018日日夜夜操 | 欧美在线视频你懂的 | 国产字幕制服中文在线 | 欧美成人怡红院在线观看 | 欧美午夜在线观看 |