本文实例为大家分享了java实现flappy Bird游戏的具体代码,供大家参考,具体内容如下
整个游戏由3个类构成。Bird类,Pipe类,stage类
第一步:首先写一个Bird类
//鸟类
public class Bird {
private int flyHeight;//飞行高度
private int xpos;//距离y轴(窗口左边缘)的位置,
public static int Up=1;//向上飞
public static int Down=-1;//向下飞
public Bird()
{
flyHeight=200;
xpos=30;
}
public void fly(int direction)
{
if(direction==Bird.Up)
flyHeight-=20;//每次向上飞20m
if(direction==Bird.Down)
flyHeight+=20;//每次向下飞20m
}
public int getFlyHeight()//获得当前飞行高度
{
return flyHeight;
}
public int getXpos()//获得当前鸟的水平位置
{
return xpos;
}
public Boolean hit(Pipe pipe[])//检测是否碰到管道。只有在鸟经过管道的过程才有可能相撞
{
for(int i=0;i=pipe[i].getXpos()&&getXpos()<=pipe[i].getXpos()+20)//鸟经过管道
if(flyHeightpipe[i].getDownHeight())//鸟与管道相撞
return true;
}
return false;
}
}
第二步:写一个Pipe类,Pipe类 里有3个成员,upHeight表示顶管道端的高度,downHeight表示底端管道段的高度,同样要记录管道的水平位置。
public class Pipe {
private int upHeight;//表示顶管道端的高度
private int downHeight;//表示底端管道段的高度
private int xpos;
public Pipe()
{
upHeight=0;
downHeight=0;
xpos=0;
}
public Pipe(int maxHeight,int xpos)//给管道一个最大总长度(maxHeight)=upHeight+downHeight。还有管道的水平位置
{
double num;
num=Math.random();
while(num==0)
num=Math.random();
upHeight=(int) (maxHeight*num);//随机产生一个顶端管道段高度(
最后一步,写好舞台类,即操作游戏的类
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.lang.reflect.Array;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.Jframe;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class stage extends JPanel{
private Pipe pipe[];//管道数组
private Bird bird;//鸟
private int space;//上下管道之间的间隔
public JLabel scoreBoard;//计分面板
private int score;//计分
public stage()
{
space=150;//上下管道之间的间隔为150
score=0;
scoreBoard=new JLabel("得分:"+score);
pipe=new Pipe[5];//总共5跟根
for(int i=0;i
程序截图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



