在这个项目中, 我们需要解决四个任务. 我会谈到我是怎么处理这四个问题的.
public static boolean emptySpaceExists(Board b)
这个任务要求我们检查 2048 的是否存在空格子. 解决办法很容易想到: 遍历一边所有的格子看看是否有空的即可. 查看其他文件就可以知道要用到什么 API 来完成这个功能. 比如我们可以通过 board.tile(col, row)
来获取对应的格子. 通过返回的状态就可以知道是不是空的.
/** Returns true if at least one space on the Board is empty. * Empty spaces are stored as null. * */ public static boolean emptySpaceExists(Board b) { int size = b.size(); for (int col = 0; col < size; col++) { for (int row = 0; row < size; row++) { if (b.tile(col, row) == null) { return true; } } } return false; }
public static boolean maxTileExists(Board b)
这个其实跟任务一很类似, 只是此时我们不是要判断格子是否为空, 我们是要判断格子的值是否为一个特定的值, 这其实还是很容易想到的. 因为我们还是通过遍历来解决这个问题, 只是判断的条件变为: t.values() == MAX_PIECE
.
/** * Returns true if any tile is equal to the maximum valid value. * Maximum valid value is given by MAX_PIECE. Note that * given a Tile object t, we get its value with t.value(). */ public static boolean maxTileExists(Board b) { int size = b.size(); for (int col = 0; col < size; col++) { for (int row = 0; row < size; row++) { Tile t = b.tile(col, row); // only when t != null should we check t.value() if (t != null && t.value() == MAX_PIECE) { return true; } } } return false; }
public static boolean atLeastOneMoveExists(Board b)
确实, 这个问题对新手来说会比较有挑战性. 问题的关键在于如何判断出 2048 的方格上是否能继续玩下去, 主要有两种情形
emptySpaceExists()
dx
和 dy
实现的, 他们表示不同方向上的增量./** * Returns true if there are any valid moves on the board. * There are two ways that there can be valid moves: * 1. There is at least one empty space on the board. * 2. There are two adjacent tiles with the same value. */ public static boolean atLeastOneMoveExists(Board b) { if (emptySpaceExists(b)) { return true; } // 4 directions, LEFT/UP/RIGHT/DOWN int[] dx = {0, -1, 0, 1}; int[] dy = {-1, 0, 1, 0}; int size = b.size(); for (int col = 0; col < size; col++) { for (int row = 0; row < size; row++) { // Because we have checked emptySpace, t.values() must exist int curTileValue = b.tile(col, row).value(); for (int move = 0; move < 4; move++) { int colNew = col + dx[move]; int rowNew = row + dy[move]; // make sure the tile is within the boundary if (colNew > 0 && colNew < size && rowNew > 0 && rowNew < size) { Tile newTile = b.tile(colNew, rowNew); if (newTile.value() == curTileValue) { return true; } } } } } return false; }
解决这个任务还是花了我不少时间的