import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PingPongGame extends JPanel {
int ballX = 0;
int ballY = 0;
int paddleX = 0;
int caughtBalls = 0;
int missedBalls = 0;
public PingPongGame() {
setPreferredSize(new Dimension(500, 360));
setBackground(Color.WHITE);
Timer timer = new Timer(2, new ActionListener() {
public void actionPerformed(ActionEvent e) {
ballY += 1;
if ( ballY > getHeight() -1 && ballY < getHeight() +1) { // 修改这里,当小球的y坐标等于滑块的y坐标时进行判断
if (ballX > paddleX && ballX < paddleX + 50) {
System.out.println(ballY+" "+paddleX);
caughtBalls++;
} else {
System.out.println(ballY+" "+getHeight());
missedBalls++;
}
ballY = 0;
ballX = (int) (Math.random() * getWidth());
}
repaint();
}
});
timer.start();
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
paddleX = e.getX() - 50;
repaint();
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(ballX, ballY, 20, 20);
g.setColor(Color.BLUE);
g.fillRect(paddleX, getHeight() - 20, 100, 10);
g.setColor(Color.BLACK);
g.drawString("Caught: " + caughtBalls + " Missed: " + missedBalls, 20, 20);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Ping Pong Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new PingPongGame());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}