package race;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Rabit_Turtle_Race extends JFrame {
private JPanel panel;
private int x1 = 0;
private int x2 = 0;
int flag = 0;
int flag1 = 0;
boolean asleep = false;
int possibility;
Rabit_Turtle_Race() {
super("Rabit&Turtle's Race");
panel = new JPanel() {
public void paint(Graphics g) {
super.paint(g);
Image img = null;
Image img1 = null;
try {
img1 = ImageIO.read(new File("image\\t1.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
g.drawImage(img1, x2, 300, this);
try {
if (flag == 1) {
img = ImageIO.read(new File("image\\1.png"));
} else if (flag == 2) {
img = ImageIO.read(new File("image\\2.png"));
} else if (flag == 3) {
img = ImageIO.read(new File("image\\3.png"));
} else if (flag == 4) {
img = ImageIO.read(new File("image\\4.png"));
} else if (flag == 5) {
img = ImageIO.read(new File("image\\5.png"));
} else if (flag == 6) {
img = ImageIO.read(new File("image\\6.png"));
}
if (asleep) {
img = ImageIO.read(new File("image\\1s.png"));
}
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(img, x1, 50, this);
}
};
this.add(panel);
this.setVisible(true);
this.setBounds(300, 300, 1300, 640);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Thread t1 = new Rabit();
Thread t2 = new Turtle();
t1.start();
t2.start();
}
class Rabit extends Thread {
public void run() {
while (true) {
x1 += 20;
if (x1 > panel.getWidth() - 150) {
break;
}
flag = (flag + 1) % 6;
possibility = (int) (Math.random() * 10);
try {
if (possibility > 9) {
asleep = true;
Thread.sleep(5000);
}
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
panel.repaint();
}
}
}
class Turtle extends Thread {
public void run() {
while (true) {
x2 += 50;
if (x2 < panel.getWidth() - 10) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
panel.repaint();
}
}
}
public static void main(String[] args) {
Rabit_Turtle_Race rtr = new Rabit_Turtle_Race();
}
}