小球碰壁反弹变色

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq2090466040/article/details/79052705
import java.awt.*;


public class MyTest1 {
public static void main(String[] args) {
Frame a = new Frame();
a.setSize(1064, 764);
MyPanel1 canvas = new MyPanel1();
a.add(canvas);


Thread t = new Thread(canvas);
t.start();
a.show();
}
}


class MyPanel1 extends Panel implements Runnable {
Color[] colors = { Color.red, Color.orange, Color.yellow, Color.green,
Color.cyan, Color.blue, Color.magenta, Color.black };
int i = 0;
int x = (int) (Math.random() * 1000);
int y = (int) (Math.random() * 700);
int way = 0; // 路径


public void paint(Graphics g) {
g.setColor(colors[i]);
g.fillOval(x, y, 30, 30);
}


public void run() {
while (true) {
// 定义飞行路径
if (way == 0) {
x++;
y++;
}
if (way == 1) {
x--;
y++;
}
if (way == 2) {
x--;
y--;
}
if (way == 3) {
x++;
y--;
}
// 定义改变方式
if (i < 7) {
if (x > 1000) {
if (way == 0) {
way = 1;
} else {
way = 2;
}
i++;
}
if (y > 700) {
if (way == 1) {
way = 2;
} else {
way = 3;
}
i++;
}
if (x < 0) {
if (way == 2) {
way = 3;
} else {
way = 0;
}
i++;
}
if (y < 0) {
if (way == 3) {
way = 0;
} else {
way = 1;
}
i++;
}
} else {
i = 0;
}
try {
Thread.sleep(5);
} catch (Exception e) {
e.printStackTrace();
}
repaint();
}
}
}
展开阅读全文

没有更多推荐了,返回首页