java龟兔赛跑小程序,有运行界面
时间: 2024-03-26 13:34:25 浏览: 56
好的,我可以为您提供一个简单的Java龟兔赛跑小程序,包含运行界面。以下是程序代码:
```
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class TurtleRabbitRace extends JFrame {
private JPanel panel;
private JLabel rabbitLabel;
private JLabel turtleLabel;
private JLabel finishLineLabel;
public TurtleRabbitRace() {
setTitle("龟兔赛跑");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.WHITE);
rabbitLabel = new JLabel(new ImageIcon("rabbit.png"));
rabbitLabel.setSize(100, 100);
rabbitLabel.setLocation(0, 50);
panel.add(rabbitLabel);
turtleLabel = new JLabel(new ImageIcon("turtle.png"));
turtleLabel.setSize(100, 100);
turtleLabel.setLocation(0, 200);
panel.add(turtleLabel);
finishLineLabel = new JLabel(new ImageIcon("finish_line.png"));
finishLineLabel.setSize(50, 400);
finishLineLabel.setLocation(700, 0);
panel.add(finishLineLabel);
add(panel);
setVisible(true);
}
public void start() {
Random random = new Random();
int rabbitDistance = 0;
int turtleDistance = 0;
while (rabbitDistance < 700 && turtleDistance < 700) {
int rabbitSpeed = random.nextInt(10) + 1;
int turtleSpeed = random.nextInt(5) + 1;
rabbitDistance += rabbitSpeed;
rabbitLabel.setLocation(rabbitDistance, 50);
turtleDistance += turtleSpeed;
turtleLabel.setLocation(turtleDistance, 200);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (rabbitDistance >= 700 && turtleDistance >= 700) {
JOptionPane.showMessageDialog(this, "平局!");
} else if (rabbitDistance >= 700) {
JOptionPane.showMessageDialog(this, "兔子获胜!");
} else {
JOptionPane.showMessageDialog(this, "乌龟获胜!");
}
}
public static void main(String[] args) {
TurtleRabbitRace race = new TurtleRabbitRace();
race.start();
}
}
```
您需要将程序中的图片文件(rabbit.png、turtle.png和finish_line.png)放在与程序同级的目录下。程序中的兔子和乌龟会随机移动,直到有一方到达终点(700像素处)为止。最终会弹出一个提示框,显示哪一方获胜或者是平局。
希望这个程序能够满足您的需求。
阅读全文