/*
* CreepingGame蚂蚁爬行游戏,定义了相关的规则和玩法
*/
public class CreepingGame {
private Stick stick;
private List <Ant> antsOnStick;
private List <Ant> antsOutofStick;
private int currentTime;
private boolean gameOver;
public CreepingGame() {
antsOnStick = new ArrayList <Ant> ();
antsOutofStick = new ArrayList <Ant> ();
currentTime = 0;
gameOver = false;
}
public void setStick(Stick stick) {
this.stick = stick;
}
public void addAntOnStick(Ant ant) throws CreepingException {
if (stick == null)
throw new CreepingException( "Stick not set yet! ");
else if (stick.isOutofRange(ant.getPosition()))
throw new CreepingException( "The ant is out of stick! ");
antsOnStick.add(ant);
}
/**
* 依照游戏规则,检测是否有蚂蚁碰头了,一旦碰头则两者要同时调头
*/
private void applyCollisionRule(List <Ant> ants) {
List <Ant> antsTobeCheck = new ArrayList <Ant> ();
antsTobeCheck.addAll(ants);
while (!antsTobeCheck.isEmpty()){
Ant antTobeCheck = antsTobeCheck.get(0);
antsTobeCheck.remove(antTobeCheck);
Ant antAtSamePosition = null;
for (Ant ant : antsTobeCheck){
if (ant.isAtCollisionWith(antTobeCheck)){
antAtSamePosition = ant;
break;
}
}
if (antAtSamePosition != null){
antTobeCheck.changeCreepDirection();
antAtSamePosition.changeCreepDirection();
antsTobeCheck.remove(antAtSamePosition);
}
}
}