java龟兔赛跑图形化演示
时间: 2023-08-01 21:14:17 浏览: 117
Java龟兔赛跑
好的,我可以为您提供一个简单的Java程序,来演示龟兔赛跑的图形化界面。以下是程序代码:
```java
import java.awt.*;
import javax.swing.*;
public class TurtleRabbitRace extends JFrame {
private JLabel turtleLabel, rabbitLabel;
private JPanel raceTrackPanel;
private int turtlePos = 0, rabbitPos = 0;
public TurtleRabbitRace() {
turtleLabel = new JLabel(new ImageIcon("turtle.gif"));
rabbitLabel = new JLabel(new ImageIcon("rabbit.gif"));
raceTrackPanel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0, 100, 1000, 100);
g.drawLine(0, 200, 1000, 200);
g.drawLine(0, 300, 1000, 300);
g.drawLine(0, 400, 1000, 400);
g.drawLine(0, 500, 1000, 500);
g.drawLine(0, 600, 1000, 600);
g.drawLine(0, 700, 1000, 700);
}
};
setLayout(new FlowLayout());
raceTrackPanel.setPreferredSize(new Dimension(1000, 800));
raceTrackPanel.add(turtleLabel);
raceTrackPanel.add(rabbitLabel);
add(raceTrackPanel);
setSize(1020, 850);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
startRace();
}
public void startRace() {
while (turtlePos < 1000 && rabbitPos < 1000) {
turtlePos += (int)(Math.random() * 10);
rabbitPos += (int)(Math.random() * 10);
turtleLabel.setLocation(turtlePos, 50);
rabbitLabel.setLocation(rabbitPos, 150);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (turtlePos > rabbitPos) {
JOptionPane.showMessageDialog(this, "Turtle wins!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
} else if (rabbitPos > turtlePos) {
JOptionPane.showMessageDialog(this, "Rabbit wins!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "It's a tie!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String[] args) {
new TurtleRabbitRace();
}
}
```
这个程序使用了JFrame和JPanel类来创建图形化界面,并且使用了线程来模拟龟兔赛跑的过程。您可以将程序中的turtle.gif和rabbit.gif替换成您自己的图片,并且可以修改程序中的其他部分来实现更多的功能。希望这个程序能够帮到您!
阅读全文