Answer the following questions on Matrix
Set 2 The source code for the BoxBug class can be found in the boxBug directory.
- What is the role of the instance variable sideLength?
在本题中, sideLength这个变量在BoxBug这个类中表示限定每一次bug沿着某一方向走的最远步长(在不遇到障碍或者边界的情况下),在到达sideLength之后,Boxbug就要调转运动方向,如下则会turn()。
举例如下:
public void act()
{
if (steps < sideLength && canMove())
{
move();
steps++;
}
else
{
turn();
turn();
steps = 0;
}
}
- What is the role of the instance variable steps?
steps用于记录BoxBug这个类中任一个Boxbug在当前所处的这条边上已经移动的步数,如下steps在没有转向时增加1,转向后置为0
if (steps < sideLength && canMove())
{
move();
steps++;
}
else
{
turn();
turn();
steps = 0;
}
- Why is the turn method called twice when steps becomes equal to sideLength?
因为boxbug调用一次turn()只转45度,但是转向需要90度,,所以需要连续调用两次
这是bug(GridWorldCode/framework/info/gridworld/actor/Bug.java)里的turn函数定义:
/**
* Turns the bug 45 degrees to the right without changing its location.
*/
public void turn()
{
setDirection(getDirection() + Location.HALF_RIGHT);
}
- Why can the move method be called in the BoxBug class when there is no move method in the BoxBug code?
因为BoxBug继承了Bug,并且在BoxBug中并没有overwrite Bug的move()函数,所以BoxBug继承了Bug的move函数,所以可以在直线运动遇到障碍时选择调用move函数。
这是bug(GridWorldCode/framework/info/gridworld/actor/Bug.java)里的move函数定义:
/**
* Moves the bug forward, putting a flower into the location it previously
* occupied.
*/
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
Flower flower = new Flower(getColor());
flower.putSelfInGrid(gr, loc);
}
- After a BoxBug is constructed, will the size of its square pattern always be the same? Why or why not?
当BoxBug创建之后,它移动形成的所有的正方形都会一样;因为sideLength在构造函数中已经确定,同时Boxbug类也未提供其他可用的方法来改变sideLength,所以Boxbug移动形成的所有的正方形大小无法都不能被改变了。
/**
* Constructs a box bug that traces a square of a given side length
* @param length the side length
*/
public BoxBug(int length)
{
steps = 0;
sideLength = length;
}
- Can the path a BoxBug travels ever change? Why or why not?
不会,如果BoxBug 遇到障碍物他就会做出一些调整,所以我们可以设置一些不同的障碍物,这样移动路径也就会随之不同了
如下,它每走一步都要检测canMove(),如果我们防止障碍物就可以改变canMove的值了
if (steps < sideLength && canMove())
{
move();
steps++;
}
- When will the value of steps be zero?
当转向后步长会变为0,还有刚开始初始化时也是0
public BoxBug(int length)
{
steps = 0;
sideLength = length;
}
/**
* Moves to the next location of the square.
*/
public void act()
{
if (steps < sideLength && canMove())
{
move();
steps++;
}
else
{
turn();
turn();
steps = 0;
}
}