java赛车小游戏代码_java版赛车小游戏源代码
时间: 2023-10-06 19:11:31 浏览: 129
以下是一个简单的 Java 赛车小游戏的源代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RacingGame extends JFrame implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
private JPanel panel;
private Timer timer;
private int carX, carY, carSpeed, roadX, roadY;
private boolean leftPressed, rightPressed, upPressed, downPressed;
public RacingGame() {
setTitle("Racing Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setLocationRelativeTo(null);
setResizable(false);
panel = new JPanel() {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘制背景
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
// 绘制道路
g.fillRect(roadX, roadY, 100, getHeight());
// 绘制赛车
g.setColor(Color.RED);
g.fillRect(carX, carY, 20, 40);
}
};
add(panel);
timer = new Timer(10, this);
timer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
carX = 290;
carY = 500;
carSpeed = 0;
roadX = 250;
roadY = 0;
}
public void actionPerformed(ActionEvent e) {
// 移动赛车
carX += carSpeed;
if (carX < roadX + 20) {
carX = roadX + 20;
}
if (carX > roadX + 60) {
carX = roadX + 60;
}
// 移动道路
roadY += 5;
if (roadY > getHeight()) {
roadY = -getHeight();
}
panel.repaint();
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = true;
carSpeed = -5;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = true;
carSpeed = 5;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = true;
carSpeed = -10;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downPressed = true;
carSpeed = 10;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
if (rightPressed) {
carSpeed = 5;
} else {
carSpeed = 0;
}
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
if (leftPressed) {
carSpeed = -5;
} else {
carSpeed = 0;
}
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = false;
if (downPressed) {
carSpeed = 10;
} else {
carSpeed = 0;
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downPressed = false;
if (upPressed) {
carSpeed = -10;
} else {
carSpeed = 0;
}
}
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
RacingGame game = new RacingGame();
game.setVisible(true);
}
}
```
这个小游戏使用了 Java Swing 库来创建 GUI 界面,实现了一个赛车在道路上运动的效果。玩家可以通过方向键控制赛车的移动,游戏会不断地更新赛车和道路的位置来模拟运动的效果。
阅读全文