当然可以!这里有一个简单的Java赛车游戏案例,它使用Swing库创建了一个基本的图形用户界面。这个游戏允许两个玩家在一条直线上驾驶汽车。
首先,确保你已经安装了Java开发工具包(JDK)。然后,创建一个新的Java项目,并将以下代码保存为RacingGame.java
:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RacingGame extends JFrame {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int CAR_WIDTH = 100;
private static final int CAR_HEIGHT = 50;
private static final int TRACK_LENGTH = 1000;
private static final int CAR_SPEED = 5;
private static final int CARS = 2;
private static final int POSITION_OFFSET = CAR_WIDTH / 2;
private JPanel trackPanel;
private Car[] cars;
private int[] carPositions;
public RacingGame() {
setTitle("Java Racing Game");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
trackPanel = new JPanel();
trackPanel.setPreferredSize(new Dimension(TRACK_LENGTH, HEIGHT));
add(trackPanel, BorderLayout.CENTER);
cars = new Car[CARS];
carPositions = new int[CARS];
for (int i = 0; i < CARS; i++) {
cars[i] = new Car(i);
add(cars[i], BorderLayout.SOUTH);
}
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startRace();
}
});
add(startButton, BorderLayout.NORTH);
setVisible(true);
}
private void startRace() {
for (int i = 0; i < CARS; i++) {
carPositions[i] = 0;
cars[i].start();
}
}
private class Car extends JPanel implements Runnable {
private int id;
private int position;
private Thread thread;
private int speed;
public Car(int id) {
this.id = id;
position = 0;
speed = CAR_SPEED;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(position, 0, CAR_WIDTH, CAR_HEIGHT);
}
public void start() {
thread = new Thread(this);
thread.start();
}
@Override