用java写一个挡板游戏
时间: 2023-07-01 19:17:31 浏览: 211
挡板游戏 java
好的,以下是一个简单的 Java 挡板游戏的实现,你可以根据需要对它进行修改:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PaddleGame extends JFrame implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 600;
private static final int HEIGHT = 500;
private static final int PADDLE_WIDTH = 100;
private static final int PADDLE_HEIGHT = 10;
private static final int BALL_SIZE = 20;
private static final int BALL_SPEED = 5;
private static final int PADDLE_SPEED = 10;
private JPanel gamePanel;
private Timer timer;
private int ballX, ballY, ballDX, ballDY;
private int paddleX, paddleY, paddleDX;
private boolean leftPressed, rightPressed;
public PaddleGame() {
setTitle("Paddle Game");
setSize(WIDTH, HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
gamePanel = new JPanel();
gamePanel.setBackground(Color.BLACK);
getContentPane().add(gamePanel);
ballX = WIDTH / 2 - BALL_SIZE / 2;
ballY = HEIGHT / 2 - BALL_SIZE / 2;
ballDX = BALL_SPEED;
ballDY = BALL_SPEED;
paddleX = WIDTH / 2 - PADDLE_WIDTH / 2;
paddleY = HEIGHT - PADDLE_HEIGHT - 20;
timer = new Timer(10, this);
timer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
g.fillRect(paddleX, paddleY, PADDLE_WIDTH, PADDLE_HEIGHT);
}
public void actionPerformed(ActionEvent e) {
if (leftPressed) {
paddleDX = -PADDLE_SPEED;
} else if (rightPressed) {
paddleDX = PADDLE_SPEED;
} else {
paddleDX = 0;
}
paddleX += paddleDX;
if (paddleX < 0) {
paddleX = 0;
} else if (paddleX + PADDLE_WIDTH > WIDTH) {
paddleX = WIDTH - PADDLE_WIDTH;
}
ballX += ballDX;
ballY += ballDY;
if (ballX < 0 || ballX + BALL_SIZE > WIDTH) {
ballDX = -ballDX;
}
if (ballY < 0) {
ballDY = -ballDY;
} else if (ballY + BALL_SIZE > paddleY && ballX + BALL_SIZE > paddleX && ballX < paddleX + PADDLE_WIDTH) {
ballDY = -ballDY;
} else if (ballY + BALL_SIZE > HEIGHT) {
timer.stop();
JOptionPane.showMessageDialog(this, "Game Over", "Message", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
repaint();
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
leftPressed = true;
} else if (key == KeyEvent.VK_RIGHT) {
rightPressed = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
leftPressed = false;
} else if (key == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new PaddleGame().setVisible(true);
}
}
```
这个例子中,我们使用了 Java 的 Swing 库创建了一个简单的窗口,并在其中实现了一个挡板游戏。在游戏中,玩家需要控制挡板左右移动来让小球弹起,同时避免小球掉落。
在游戏中,我们使用了键盘事件来控制挡板的移动,并使用定时器来不断更新游戏状态。我们还使用了碰撞检测来判断小球是否和挡板碰撞,以及小球是否掉落。
你可以根据需要对这个例子进行修改和扩展,来实现更加丰富的挡板游戏。
阅读全文