[java]代码库//1510821001廖益利
//练习三 读懂小球撞壁代码,并完善.txt(已完成100%)
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
public class pp{
public static void main(String args[]){
Frame w = new Frame();
MyPanel mp = new MyPanel();
w.add(mp);
Thread th = new Thread(mp);
th.start();
w.setSize(300,400);
w.show();
}
}
class MyPanel extends Panel implements Runnable{
int y=30;
int x=30;
int att=0;
public void paint(Graphics g){
//while(true){
g.fillOval(x, y, 20, 20);
//}
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
// 定义飞行姿态
if (att == 0) {
x++;
y++;
}else if (att == 1) {
x--;
y++;
}else if (att == 2) {
x--;
y--;
}else if (att == 3) {
x++;
y--;
}
// 改变飞行姿态
if (x > 260&&y<360) { //263+20=283,横坐标占用了17个像素,x>263有两种可能,左下或者右上
if(att == 0) att=1;
else att=2;
} else if (x < 260&&y>360){
if(att==1)
att = 2;
else att=3;
} else if (x < 0&&y<360){
if(att==2)
att = 3;
else att=0;
}else if (x < 270&&y<0){
if(att==3)
att = 0;
else att=1;
}
try{
Thread.sleep(8) ;
}catch(Exception e){
}
repaint() ;
}
}
}
[代码运行效果截图]