简单小游戏flappybird制作(六)

本次介绍Pipe类
pipe类主要是实现管道的位置和缝隙大小的在一定范围内的随机

数据成员如下
private BufferedImage image1;
private BufferedImage image2;
public int x;
public int y;
public int width;
private int height;
public int gap;
private Random r = new Random();
private int distance = 240;

image1用来存上半部分管道的图片,image2同理,x和y是管道缝隙中心坐标,width和height是图片宽度和高度,gap是缝隙垂直距离,r用于生成随机数,distance是管道间距。
public Pipe(int n) throws IOException {
		image1 = ImageIO.read(new File("img/pipe1.png"));
		image2 = ImageIO.read(new File("img/pipe2.png"));
		width = image1.getWidth();
		height = image1.getHeight();
		this.x = distance * n +250;
		this.y = r.nextInt(240) + 140;
		gap=r.nextInt(20)-r.nextInt(20)+140;
	}

构造方法参数int n是用来表示第几个管道的,之前提到过这个游戏界面最多同时出现两个管道,所以int n的取值就从1和2里选了。 this.y = r.nextInt(240) + 140;其中240和140是用来限制管道中心位置的,防止出现管道中心位置位于窗口之上或者地面之下。 gap=r.nextInt(20)-r.nextInt(20)+140;里140是缝隙的基准宽度变动范围在+-20之间。
public void step() {
		x--;
		if(x<=-width/2){
			x = distance*2-width/2;
			this.y = r.nextInt(240) + 140;
			gap=r.nextInt(20)-r.nextInt(20)+140;
		}
	}

还是用来刷新位置的方法,其中当管道出窗口边界的时候重置管道位置,并给缝隙宽度赋新值。
public void paint(Graphics g) {
		g.drawImage(image1, x-width/2, y-height-gap/2, null);
		g.drawImage(image2, x-width/2, y+gap/2, null);
	}
绘制上下两个管道的图片。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值