nt x;
private int y;
public Position(int x, int y)
{
super();
this.x = x;
this.y = y;
}
/**
* 获取从父节点直接偏移至子节点的距离
*/
public int getOffsetOfDistance(Position position)
{
int x = Math.abs(getX() - position.getX());
int y = Math.abs(getY() - position.getY());
Position offset = new Position(x, y);
if (offset.equals(new Position(0, 1))
|| offset.equals(new Position(1, 0)))
{
return STRAIGHT_DISTANCE;
}
return DIAGONAL_LINE_DISTANCE;
}
/**
* 获取到目标节点的平移距离
*/
public int getDistanceOfTarget(Position position)
{
int verticalDistance = Math.abs(getY() - position.getY());
int horizontalDistance = Math.abs(getX() - position.getX());
return (verticalDistance + horizontalDistance) * STRAIGHT_DISTANCE;
}
public Position offset(Position offset)
{
return new Position(getX() + offset.getX(), getY() + offset.getY());
}
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;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Position other = (Position) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public String toString()
{
return "Position [x=" + x + ", y=" + y + "]";
}
}[java]
/**
* 位置信息的权值
*/
public class PositionWeight
{
/**
* 水平或者垂直移动一格的距离
*/
private final static int STRAIGHT_DISTANCE = 10;
/**
* 当前的位置信息
*/
private Position position;
/**
* 起始点(王子的起始位置),经由当前点的父节点后,到当前点的距离(仅包括垂直和水平直线上的)
*/
private int distanceOfPrince;
/**
* 当前点到目标点(公主位置)的距离
*/
private int distanceOfPrincess;
/**
* 父节点的权值
*/
private PositionWeight father;
/**
* 总开销:包括起始点到当前点和当前点到终点的开销之和
*/
private int cost;
public PositionWeight(Position position)
{
this.position = position;
}
public PositionWeight(Position position, PositionWeight father,
PositionWeight target)
{
this(position);
countDistanceToTarget(target);
updateByFather(father);
}
/**
* 获取父子节点间的距离:对角线为14,水平、垂直为10
*/
public int getDistanceFromAttemptFather(PositionWeight father)
{
Position fatherPosition = father.getPosition();
return fatherPosition.getOffsetOfDistance(getPosition());
}
/**
* 更新父节点,并设置当前点的权值
*/
public void updateByFather(PositionWeight father)
{
setFather(father);
int distanceOfPrince = getDistanceFromAttemptFather(father);
setDistanceOfPrince(distanceOfPrince + father.getDistanceOfPrince());
setCost(getDistanceOfPrince() + getDistanceOfPrincess());
}
public Position getPosition()
{
return position;
}
public PositionWeight getFather()
{
return father;
}
public int getCost()
{
return cost;
}
public int getDistanceOfPrince()
{
return distanceOfPrince;
}
/**
* 获取花费的总开销
*/
public int getSpendTime()
{
return