android飞翔的小鸟代码
时间: 2024-01-07 18:05:51 浏览: 27
以下是一个简单的 Android 飞翔的小鸟游戏的代码示例,仅供参考:
```
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView bird;
private ImageButton btnJump;
private FrameLayout frame;
private int frameHeight, birdSize;
private int screenHeight, screenWidth;
private int birdYPosition;
private int gravity = 3;
private int jumpPower = -30;
private boolean isJumping = false;
private Handler handler = new Handler();
private Timer timer = new Timer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bird = findViewById(R.id.bird);
btnJump = findViewById(R.id.btnJump);
frame = findViewById(R.id.frame);
// 获取屏幕尺寸
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;
// 设置点击监听器
btnJump.setOnClickListener(this);
// 设置定时器
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
birdYPosition += gravity;
bird.setY(birdYPosition);
if (birdYPosition < 0) {
birdYPosition = 0;
}
if (birdYPosition > frameHeight - birdSize) {
birdYPosition = frameHeight - birdSize;
}
if (isJumping) {
birdYPosition += jumpPower;
bird.setY(birdYPosition);
isJumping = false;
}
}
});
}
}, 0, 20);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnJump) {
isJumping = true;
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
frameHeight = frame.getHeight();
birdSize = bird.getHeight();
birdYPosition = bird.getTop();
}
}
}
```
这段代码中,我们使用了一个定时器来控制小鸟的运动,通过点击按钮来触发小鸟跳跃的动作。在 `onCreate` 方法中,我们获取了屏幕的尺寸,并设置了一个定时器。在定时器中,我们根据重力和跳跃力来控制小鸟的位置,并判断小鸟是否跳跃。在 `onClick` 方法中,我们设置了一个标志来表示小鸟正在跳跃。在 `onWindowFocusChanged` 方法中,我们获取了小鸟和游戏画面的尺寸,并初始化了小鸟的位置。