import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

public class GamePanel extends JPanel implements ActionListener, KeyListener {
    private Timer timer;
    private ArrayList<Bullet> bullets;
    private int targetX, targetY; // 目标位置

    public GamePanel() {
        timer = new Timer(30, this); // 每30ms更新一次
        bullets = new ArrayList<>();
        targetX = 300; // 初始目标位置
        targetY = 300;
        addKeyListener(this);
        setFocusable(true);
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < bullets.size(); i++) {
            Bullet bullet = bullets.get(i);
            if (bullet.isVisible()) {
                bullet.update();
            } else {
                bullets.remove(i);
            }
        }
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.fillRect(targetX, targetY, 20, 20); // 绘制目标
        g.setColor(Color.BLUE);
        for (Bullet bullet : bullets) {
            g.fillOval(bullet.getX(), bullet.getY(), 5, 5); // 绘制子弹
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
            // 发射子弹
            bullets.add(new Bullet(100, 500, targetX, targetY, 5));
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {}

    @Override
    public void keyTyped(KeyEvent e) {}
}