java图形用户界面模拟龟兔赛跑;要求要有动画
发布网友
发布时间:2022-07-13 15:02
我来回答
共3个回答
热心网友
时间:2023-11-03 11:56
package 赛跑;
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame {
// 全局变量
static int positionA = 50, positionB = 50, distanceAll = 1600;
static int RecWidth = 50, RecHeight = 50;
static char winner;
static long sleeptime = 300;
static boolean waitA = true, waitB = true, gaming = true, unrepaint = true;
//构造函数
public Test() {
this.setTitle("龟兔赛跑");
this.setBackground(Color.WHITE);
this.setSize(1000, 500);
this.setLocation(0, 200);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//绘图函数
public void paint(Graphics g) {
// TODO Auto-generated method stub
g.clearRect(0, 0, 1600, 900);
g.setColor(Color.RED);
g.fillRect(positionA - 50, 100, RecWidth, RecHeight);
g.setColor(Color.BLUE);
g.fillRect(positionB - 50, 300, RecWidth, RecHeight);
if (!gaming) {
g.setFont(new Font("宋体", ALLBITS, 50));
if (winner == 'A') {
g.setColor(Color.RED);
g.drawString(new String("Winner Is The Red One!"), 350, 250);
} else if (winner == 'B') {
g.setColor(Color.BLUE);
g.drawString(new String("Winner Is The Blue One!"), 350, 250);
}
}
}
public static void main(String[] args) {
waitA = false;
waitB = true;
unrepaint = false;
threadframe tf = new threadframe();
threadA tA = new threadA();
threadB tB = new threadB();
tf.start();
tA.start();
tB.start();
try {
tf.join();
tA.join();
tB.join();
} catch (Exception e) {
// TODO: handle exception
}
return;
}
//兔子的线程
public static class threadA extends Thread {
public void run() {
while (gaming) {
while (waitA) {
if (!gaming)return;
System.out.print("");
}
try {
sleep(sleeptime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int distance = (int) (Math.random() * 100000) % 100;
positionA += distance;
if (positionA >= distanceAll) {
positionA = distanceAll;
unrepaint = false;
gaming = false;
winner = 'A';
}
unrepaint = false;
waitA = true;
waitB = false;
}
}
}
//乌龟的线程
public static class threadB extends Thread {
public void run() {
while (gaming) {
while (waitB) {
if (!gaming)return;
System.out.print("");
}
try {
sleep(sleeptime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int distance = (int) (Math.random() * 100000) % 100;
positionB += distance;
if (positionB >= distanceAll) {
positionB = distanceAll;
unrepaint = false;
gaming = false;
winner = 'B';
}
unrepaint = false;
waitB = true;
waitA = false;
}
}
}
//框架刷新线程
public static class threadframe extends Thread {
Test jiemian = new Test();
public void run() {
while (gaming) {
while (unrepaint) {
if (!gaming)return;
System.out.print("");
}
jiemian.repaint();
unrepaint = true;
}
}
}
}
热心网友
时间:2023-11-03 11:57
急啊!快啊,追加悬赏分!谢谢!
热心网友
时间:2023-11-03 11:57
大哥,大姐们帮帮忙!急啊!