使用java 编写一个模拟龟兔赛跑的窗体应用程序,绘制不同颜色的两个圆分别代表乌龟和兔子,设置一个按钮,单击按键后,龟兔开始赛跑。
时间: 2023-07-16 15:15:41 浏览: 97
一个用Java语言编写的龟兔赛跑的程序
以下是使用Java编写的模拟龟兔赛跑的窗体应用程序的示例代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
public class TurtleRabbitRace extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton startButton;
private int turtleX, rabbitX;
private final int Y = 150;
private final int RADIUS = 20;
private final int FINISH_LINE = 500;
private final int DELAY_TIME = 50;
private final int SLEEP_TIME = 100;
private final int SLOW_DOWN_TIME = 200;
private Random random = new Random();
public TurtleRabbitRace() {
// Initialize the window
JFrame frame = new JFrame("Turtle Rabbit Race");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
// Initialize the start button
startButton = new JButton("Start");
startButton.addActionListener(this);
// Add components to the window
frame.add(this);
frame.add(startButton, "South");
// Show the window
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
// Start the race
turtleX = 0;
rabbitX = 0;
repaint();
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException ex) {}
while (turtleX < FINISH_LINE && rabbitX < FINISH_LINE) {
// Calculate the distance that the turtle and the rabbit move
int turtleDistance = random.nextInt(10);
int rabbitDistance = random.nextInt(100);
// Move the turtle and the rabbit
turtleX += turtleDistance;
rabbitX += rabbitDistance;
// Slow down the rabbit if it is too fast
if (rabbitDistance > 50) {
try {
Thread.sleep(SLOW_DOWN_TIME);
} catch (InterruptedException ex) {}
}
// Repaint the window
repaint();
try {
Thread.sleep(DELAY_TIME);
} catch (InterruptedException ex) {}
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the finish line
g.drawLine(FINISH_LINE, 0, FINISH_LINE, getHeight());
// Draw the turtle and the rabbit
g.setColor(Color.GREEN);
g.fillOval(turtleX, Y, RADIUS, RADIUS);
g.setColor(Color.RED);
g.fillOval(rabbitX, Y - 50, RADIUS, RADIUS);
}
public static void main(String[] args) {
new TurtleRabbitRace();
}
}
```
这个程序创建了一个窗体应用程序,包含一个绘制龟兔赛跑的面板和一个开始按钮。单击开始按钮后,龟兔开始赛跑。龟兔的移动距离是随机生成的,其中兔子的移动距离比乌龟的移动距离大,但如果兔子移动距离过大,它会被减速。程序会在每次移动后重新绘制龟兔的位置,直到有一只动物到达终点线。
阅读全文