能不能用Java写一个简单的愤怒的小鸟程序
时间: 2023-09-23 11:03:55 浏览: 150
当然可以,以下是一个简单的愤怒的小鸟程序的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AngryBirds extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel canvas;
private Timer timer;
private int x = 0, y = 100;
private int vx = 5, vy = 0;
private final int RADIUS = 30;
private final int GRAVITY = 1;
public AngryBirds() {
setTitle("Angry Birds");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(x - RADIUS, y - RADIUS, 2 * RADIUS, 2 * RADIUS);
}
};
add(canvas, BorderLayout.CENTER);
timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x += vx;
y += vy;
vy += GRAVITY;
if (y + RADIUS > canvas.getHeight()) {
y = canvas.getHeight() - RADIUS;
vy = -vy / 2;
}
canvas.repaint();
}
});
timer.start();
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
vx = (e.getX() - x) / 10;
vy = (e.getY() - y) / 10;
}
});
}
public static void main(String[] args) {
AngryBirds game = new AngryBirds();
game.setVisible(true);
}
}
```
这个程序使用了Java Swing库,实现了一个简单的小鸟游戏。在游戏中,玩家可以点击屏幕来发射小鸟,小鸟会受到重力的影响,落到地面时会弹起一定高度。玩家需要通过调整角度和力度,让小鸟飞到指定的目标位置。
阅读全文