/*
* CreepingGame螞蟻爬行游戲,定義了相關(guān)的規(guī)則和玩法
*/
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);
}
/**
* 依照游戲規(guī)則,檢測(cè)是否有螞蟻碰頭了,一旦碰頭則兩者要同時(shí)調(diào)頭
*/
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);
}
}
}