设计文档
设计思路
a. What will a jumper do if the location in front of it is empty, but the location two cells in front contains a flower or a rock?
当前方一格为空时,若两格前为花,jumper会直接“吃掉”花并且落到原来花的位置;若两格前是岩石,则先执行move函数,向前进一步,再执行jump函数,跳过岩石。
b. What will a jumper do if the location two cells in front of the jumper is out of the grid?
jumper会先向前进一步,再进行转向两次90度,再执行跳函数或其他情况。
c. What will a jumper do if it is facing an edge of the grid?
jumper会直接两次转向90度,再执行跳函数或其他情况。
d. What will a jumper do if another actor (not a flower or a rock) is in the cell that is two cells in front of the jumper?
jumper会先向前进一步,再进行转向两次90度,再执行跳函数或其他情况。(和岩石一致)
e. What will a jumper do if it encounters another jumper in its path?
其中一个Jumper会前进一格,另一个Jumper会跳一步。
f. Are there any other tests the jumper needs to make?
测试Jumper面对actor并且与之相邻时会有什么动作。
设计过程
一个Jumper运动的时候分三种情况,一种是前面没东西或前面一格有东西直接jump,一种是前面两格处有东西或墙改move,一种是前面就是墙直接turn,写成act函数为
public void act()
{
if (canJump())
{
jump();
}
else if (canMove())
{
move();
}
else
{
turn();
}
其中要判断是否可跳或移动,判断跳写成
public boolean canJump()
{
Grid gr = getGrid();
if (gr == null)
{
return false;
}
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection())
if (!gr.isValid(next))
{
return false;
}
Location next2 = next.getAdjacentLocation(getDirection());
if (!gr.isValid(next2))
{
return false;
}
Actor neighbor = gr.get(next2);
return (neighbor == null) || (neighbor instanceof Flower);
// ok to move into empty location or onto flower
// not ok to move onto any other actor
}
判断移动写成
public boolean canMove()
{
Grid gr = getGrid();
if (gr == null)
{
return false;
}
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (!gr.isValid(next))
{
return false;
}
Actor neighbor = gr.get(next);
return (neighbor == null) || (neighbor instanceof Flower);
// ok to move into empty location or onto flower
// not ok to move onto any other actor
}
至于执行函数和bug没什么太大区别,只是在跳时需要获取相邻的相邻的格子的信息了。
实验体会
这个part的关键点在于理解location、grid、actor这几个类的属性和互相之间的关系。写Jumper类自然要继承Actor类。需要自己写jump函数和判断函数canJump。实际上Jumper的代码和Bug也比较类似,只需要在Bug的基础上修改下就行了。