62,612
社区成员
发帖
与我相关
我的任务
分享
if (points.size() >= 1){
if (ball.getX()== points.get(0).getX()
&& ball.getY() == points.get(0).getY()&&points.size()<= 1) {//等于1说明就剩下最后一步,只要等他move完,线程就可以停止了。
flag = false;
}else {
if (ball.getX() == points.get(0).getX()
&& ball.getY() == points.get(0).getY()) {
// 拿Point.get(0)那个Point.get(1)出来比较,就可以确定方向。
Direction dir = getDir(points.get(0),points.get(1));
ball.dir = dir;
points.remove(0);
}
}
}
else{
flag = false;
}
import java.util.List;
class WatcherThread implements Runnable {
boolean flag = true;
private Ball ball;
private List<Point> points;
WatcherThread(Ball ball, List<Point> points) {
this.ball = ball;
this.points = points;
}
@Override
public void run() {
while (flag) {
if (points.size() >= 1) {
if (ball.getX()== points.get(0).getX()
&& ball.getY() == points.get(0).getY()) {
flag = false;
} else {
if (ball.getX() == points.get(0).getX()
&& ball.getY() == points.get(0).getY()) {
// 拿Point.get(0)那个Point.get(1)出来比较,就可以确定方向。
Direction dir = getDir(points.get(0),points.get(1));//这样方向就得到了。
ball.dir = dir;
points.remove(0);
}
}
}
try {
Thread.sleep(20);
ball.move();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Direction getDir(Point point, Point point1){//线程监听临界状况,在判断方向。
if(point1.getX()>point.getX()){
return Direction.LEFT;
}
if(point1.getY()>point.getY()){
return Direction.UP;
}
if(point1.getY()<point.getY()){
return Direction.DOWN;
}
if(point1.getX()<point.getX()){
return Direction.RIGHT;
}
return null;
}
}
enum Direction{//支持上下左右,你可以扩展的。
UP,LEFT,RIGHT,DOWN;
}
class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
class Ball {
static final int SPEED=50;
Direction dir;
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
void move(){
//根据方向和速度,怎么move你知道吧。。。
}
}