首頁 > 軟體

Java實現升級版布穀鳥闖關遊戲的範例程式碼

2022-02-28 10:00:58

前言

《布穀鳥闖關-升級版》是一個基於java的布穀鳥闖關遊戲,滑鼠左鍵點選控制鳥的位置穿過管道間的縫隙,需要做碰撞檢測,監聽鍵盤事件,背景圖片的切換,障礙物管道產生時y軸上需要隨機位置。

主要設計

1.設計遊戲介面,用swing實現

2.設計背景

3.設計移動牆

4.設計布穀鳥

5.設計障礙物

6.設計背景音樂和音效

7.新增使用者賬號註冊登入功能

8.參照mysql資料庫,管理使用者賬號密碼和儲存排行榜等資訊

  • ​ 需要提前建立好資料庫"game",字元集選“utf8mb4”
  • ​ 然後執行mysql表結構和初始化資料指令碼
  • ​ 修改程式碼裡的DBUtils的引數值

9.新增遊戲商城模組

10.新增排行榜模組

功能截圖

使用者註冊:

遊戲歡迎介面:

遊戲開始介面:

滑鼠左鍵點選控制鳥的位置穿過管道間的縫隙

程式碼實現

遊戲啟動類

//開始介面
public class frame extends JFrame {
	private JPanel pane;
	public static frame frame;
	public frame(){
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(240,150);
		 ImageIcon backGround = new ImageIcon("images/frame.png");
	     JLabel bkgImage = new JLabel(backGround);
	     bkgImage.setSize(240,150);
	     bkgImage.setLocation(0,0);
	     JPanel bkgPanel = (JPanel) this.getContentPane();
	     bkgPanel.setOpaque(false);
	
	     //註冊按鈕
		JButton button_regist =new JButton("註冊");
		button_regist.setBounds(30,40, 60,30);
		bkgPanel.add(button_regist);
		
		button_regist.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				new frame_regist().setVisible(true);
			}
		});
		
		//登入按鈕
		JButton button_log=new JButton("登入");
		button_log.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				new frame_log(frame).setVisible(true);
			}
		});
		button_log.setBounds(130,40, 60, 30);
		bkgPanel.add(button_log);
		this.getContentPane().add(bkgImage);
		
	}
	
	//彈出顯示傳入String的提示框
	public static void frame_warning(String warning) {
		JFrame frame=new JFrame();
		JPanel pane=new JPanel();
		frame.setBounds(540, 360, 300, 150);
		frame.setContentPane(pane);
	    pane.setBorder(new EmptyBorder(5, 5, 5, 5));
		pane.setLayout(null);
		JLabel label_warning=new JLabel(warning);
		label_warning.setBounds(50,20,150,50);
		pane.add(label_warning);
		
		JButton button_yes = new JButton("確定");
		button_yes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frame.setVisible(false);
			}
		});
		button_yes.setBounds(80, 80, 93, 23);
		pane.add(button_yes);
		
		frame.setVisible(true);
	}


	public static void main(String[] args){
		
		frame =new frame();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}
	/**
	 * 
	 */
}

核心類

import static java.lang.Thread.sleep;
 public class GameplayingFrame extends JFrame{

	private static final long serialVersionUID = 1L;
	user_inf user;
	MainFrame mainframe;
	List<rank_information> rfs;
	Graphics g=this.getGraphics();
	GameplayingFrame(user_inf user,List<rank_information> rfs,MainFrame mainframe)
	{
		this.mainframe=mainframe;
		this.rfs=rfs;
		this.user=user;
		this.setTitle("Fly Bird");
        this.setSize(Constant.Frame_Width,Constant.Frame_Height);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        Scene stage = new Scene(user);
        Graphics g = this.getGraphics(); 
        ImageIcon backGround = new ImageIcon("images/bg_day.png");
        JLabel bkgImage = new JLabel(backGround);
        bkgImage.setSize(288,512);
        bkgImage.setLocation(0,0);
        JPanel bkgPanel = (JPanel) this.getContentPane();
        bkgPanel.setOpaque(false);
        this.getContentPane().add(bkgImage);
        //為介面加入滑鼠的響應事件
        this.addMouseListener(new MouseListener(){
			@Override
			public void mouseReleased(MouseEvent e) {}
			@Override
			public void mousePressed(MouseEvent e) {	
			}
			@Override
			public void mouseExited(MouseEvent e) {	
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {	
			}
			@Override
			public void mouseClicked(MouseEvent e) {
			    stage.speed_y=-175;
			}
		});
        JLabel scoreText = new JLabel();
        Font font = new Font(Font.SERIF, Font.ITALIC, 30);
        scoreText.setFont(font);
        scoreText.setText(String.valueOf(0));
        this.setLayout(null);
        scoreText.setBounds(129,0,30,30);
        this.add(scoreText);
        //新增一個執行緒物件,用於重複繪圖,來節約主執行緒的資源,使遊戲執行更加流暢
        new Thread(new playingThread(stage,g,this,user,rfs,mainframe)).start(); 
    }		

	}
	
 /*
  * 場景類,包含了遊戲介面的物品以及遊戲實現的演演算法
  */
class  Scene{
    //字尾_x/_y表示橫/縱座標,視窗左上角為原點
    public final int bird_x = 88;
    //重力加速度
    public final int G = 300;
    public double bird_y;
    public double birdRadius;
    //速度——正值為向下,負值為向上
    public int speed_x;
    public int speed_y;
    private  Ground land= new Ground(GameUtil.toBufferedImage(GameUtil.getImage("ioo/land.png")));
    BufferedImage back=  GameUtil.toBufferedImage(GameUtil.getImage("ioo/bg_day.png")) ;   
    Barrier barrier;
    Barrier barrier1;
    Ground ground;
    FlyingBird bird=null;
    Scene(user_inf user){
    	bird_y = 200;
        bird=new FlyingBird(bird_x,bird_y,user);
        birdRadius = 22;
        speed_x = 3;
        speed_y = 0;
        ground = new Ground(GameUtil.toBufferedImage(GameUtil.getImage("ioo/land.png")));
        barrier= new Barrier(GameUtil.toBufferedImage(GameUtil.getImage("ioo/pipe_down1.png")));
        barrier1= new Barrier(GameUtil.toBufferedImage(GameUtil.getImage("ioo/pipe_down.png")));      
    } 
    
    //返回true是遊戲已經結束,返回false表示遊戲繼續進行
    	 boolean ifGameOver(){
    	        //碰到地面
    	        if(bird_y + birdRadius > 512 - ground.getHeight()){
    	            System.out.println("hit ground");
    	            return true;
    	        }
    	        //碰到頂
    	        if(bird_y - birdRadius < 0){
    	            System.out.println("hit sky");
    	            return true;
    	        }
    	        //未過左邊界時
    	        if(bird_x + birdRadius <= barrier.location_x){
    	            return false;
    	        }
    	        //接近左邊界時
    	        if(bird_x + birdRadius > barrier.location_x && bird_x < barrier.location_x){
    	            if(bird_y < barrier.topHeight || bird_y + birdRadius*0.7 > 512 - barrier.bottomHeight){
    	                System.out.println("hit left edge");
    	                return true;
    	            }
    	            return false;
    	        }
    	        //通過管道時
    	        if(bird_x >= barrier.location_x && bird_x < barrier.location_x + barrier.width){

    	            boolean y1 = bird_y + birdRadius > 512 - barrier.bottomHeight;
    	            boolean y2 = bird_y  <barrier.topHeight;
    	            if(y1 || y2){
    	                System.out.println("hit inside");
    	            }
    	            return y1 || y2;
    	        }
    	        //已通過管道
    	        if(bird_x >= barrier.location_x + barrier.width){
    	            return false;
    	        }
    	        return false;
    	    }
    //ifGameOver=false時才執行
    boolean ifGetScore(){
        return bird_x + birdRadius > barrier.location_x;
    }
    //第二次之後的繪圖
    public void drawItems(Graphics g){
        //鳥 
        bird.draw(g);
    	//下障礙物
    	g.drawImage(barrier.img, barrier.location_x, 512 - barrier.bottomHeight,33,barrier.bottomHeight, null);
        //上障礙物
    	g.drawImage(barrier1.img,barrier.location_x, 0,33,barrier.topHeight, null);
    
        //地面
        g.drawImage(ground.getBufferedImage(),0,512-30, null);
        ground.checkGround();
        barrier.checkBarrier();
    }
    //更新各個物體的位置(每秒30次)
    public void itemMove() {
        //計算鳥的速度
        speed_y += G*0.033;

        //鳥最大的向下速度為220
        if(speed_y > 220){
            speed_y = 220;
        }

        //計算鳥的縱座標
        bird_y += speed_y*0.033;
          bird.y=bird_y;
        //計算障礙物和地面的橫座標
        barrier.location_x -= speed_x;
        ground.setX(ground.getX()-speed_x);
    }
    
  //變速方法,根據分數調整速度
    public void shift(int score){
        if(score < 1) {
            speed_x = 3;
        }
        else if (score < 100){
            speed_x = 4;
        }
        else if (score < 200){
            speed_x = 5;
        }
        else if (score < 300){
            speed_x = 6;
        }
        else if (score < 400){
            speed_x = 7;
        }
        else if (score < 500){
            speed_x = 8;
        }
        else speed_x = 9;
    }
    
    
    
}

執行緒類用於重複繪圖

public class playingThread implements Runnable {
	Scene stage;
	private Image iBuffer;
    private Graphics gBuffer;
    List<rank_information> rfs;
    user_inf user;
    MainFrame mainframe;
	Graphics g ;
	GameplayingFrame playingframe ;
	public static boolean flag = true;//控制計分板的變數
	public int score = 0;//分數
	playingThread(Scene stage,Graphics g,GameplayingFrame playingframe ,user_inf user,List<rank_information> rfs,MainFrame mainframe)
	{
		this.mainframe=mainframe;
		this.rfs=rfs;
		this.user=user;
		this.stage=stage;
		this.g=g;
		this.playingframe=playingframe;
		
	}
	@Override
	public void run() {
		 while (!stage.ifGameOver()){
	             stage.drawItems(g);//繪畫
	             stage.itemMove();//物體移動
	            //33ms重新整理一次
	            try {
	                sleep(33);
	            } catch (InterruptedException e) {
	                e.printStackTrace();
	            }
	            if(stage.ifGetScore()){
	                    score++;
	            }
	            stage.shift(score);
	            //playingframe.update(g);
	            //清除上一次繪畫結果
	          //雙緩衝方法清除上一次繪畫結果
	            if (iBuffer == null){
	                iBuffer = playingframe.createImage(playingframe.getSize().width,playingframe.getSize().height);
	                gBuffer = iBuffer.getGraphics();
	            }
	            playingframe.paint(gBuffer);
	            g.drawImage(iBuffer,0,0,null);
	          //  stage.drawItems(g);//再繪畫
	        }
		     user.setCoin(user.getCoin()+score);
		     new user_dao().update(user);
		     playingframe.setVisible(false);
		     rank_information rf=new rank_information();
		     rf.setScore(score);
		     rf.setName(user.getUser_name());
		     rfs.add(rf);
		      new rank_dao().update_rank(rfs);
		      new  resultFrame(score,user,rfs,mainframe);
		      System.out.println("game over");
	  
	        
		
		
		
	}

}

總結

通過此次的《布穀鳥闖關-升級版》實現,讓我對JAVA的相關知識有了進一步的瞭解,對java這門語言也有了比以前更深刻的認識。

java的一些基本語法,比如資料型別、運運算元、程式流程控制和陣列等,理解更加透徹。java最核心的核心就是物件導向思想,對於這一個概念,終於悟到了一些。

以上就是Java實現升級版布穀鳥闖關遊戲的範例程式碼的詳細內容,更多關於Java布穀鳥闖關遊戲的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com