服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java实现升级版布谷鸟闯关游戏的示例代码

Java实现升级版布谷鸟闯关游戏的示例代码

2022-08-05 11:56小虚竹and掘金 Java教程

升级版布谷鸟闯关游戏是一个基于java的布谷鸟闯关游戏,鼠标左键点击控制鸟的位置穿过管道间的缝隙。文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下

 

前言

《布谷鸟闯关-升级版》是一个基于java的布谷鸟闯关游戏,鼠标左键点击控制鸟的位置穿过管道间的缝隙,需要做碰撞检测,监听键盘事件,背景图片的切换,障碍物管道产生时y轴上需要随机位置。

 

主要设计

1.设计游戏界面,用swing实现

2.设计背景

3.设计移动墙

4.设计布谷鸟

5.设计障碍物

6.设计背景音乐和音效

7.新增用户账号注册登录功能

8.引用mysql数据库,管理用户账号密码和储存排行榜等信息

  • ​ 需要提前创建好数据库"game",字符集选“utf8mb4”
  • ​ 然后执行mysql表结构和初始化数据脚本
  • ​ 修改代码里的DBUtils的参数值

9.新增游戏商城模块

10.新增排行榜模块

 

功能截图

用户注册:

Java实现升级版布谷鸟闯关游戏的示例代码

游戏欢迎界面:

Java实现升级版布谷鸟闯关游戏的示例代码

游戏开始界面:

Java实现升级版布谷鸟闯关游戏的示例代码

鼠标左键点击控制鸟的位置穿过管道间的缝隙

Java实现升级版布谷鸟闯关游戏的示例代码

 

代码实现

 

游戏启动类

//开始界面
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布谷鸟闯关游戏的资料请关注服务器之家其它相关文章!

原文地址:https://juejin.cn/post/7069294504150302727

延伸 · 阅读

精彩推荐
  • Java教程浅谈MyBatis通用Mapper实现原理

    浅谈MyBatis通用Mapper实现原理

    这篇文章主要介绍了浅谈MyBatis通用Mapper实现原理,本文会先介绍通用 Mapper 的简单原理,然后使用最简单的代码来实现这个过程。感兴趣的小伙伴们可以参...

    isea53312512021-06-06
  • Java教程java 创建自定义数组

    java 创建自定义数组

    本篇文章是关于java 如何自己创建自定义数组,这里给大家一个小实例,希望能帮助有所需要的同学 ...

    LQH6042020-05-25
  • Java教程JVM中四种GC算法案例详解

    JVM中四种GC算法案例详解

    这篇文章主要介绍了JVM中四种GC算法案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下...

    rocketeerli11682021-12-13
  • Java教程解决Tomcat修改get提交请求乱码问题

    解决Tomcat修改get提交请求乱码问题

    这篇文章主要介绍了Tomcat修改get提交请求乱码问题的解决方案,需要的朋友参考下...

    m0_376344722022020-09-12
  • Java教程SpringBoot整合RocketMQ实现消息发送和接收的详细步骤

    SpringBoot整合RocketMQ实现消息发送和接收的详细步骤

    这篇文章主要介绍了SpringBoot整合RocketMQ实现消息发送和接收功能,我们使用主流的SpringBoot框架整合RocketMQ来讲解,使用方便快捷,本文分步骤给大家介绍的非...

    java1234_小锋11902021-12-02
  • Java教程Java gbk转utf-8

    Java gbk转utf-8

    本文主要介绍了Java gbk转utf-8的方法,具有一定的参考价值,下面跟着小编一起来看下吧...

    小明快点跑3832020-08-03
  • Java教程mybatis-plus中BaseMapper入门使用

    mybatis-plus中BaseMapper入门使用

    本文主要介绍了mybatis-plus中BaseMapper入门使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    大田酱紫11192021-11-22
  • Java教程JAVA通过XPath解析XML性能比较详解

    JAVA通过XPath解析XML性能比较详解

    本篇文章主要介绍了JAVA通过XPath解析XML性能比较详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    王中秋2782020-08-12