站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2ME 专题TilePuzzle剖析(4)

TilePuzzle剖析(4)

摘要: TilePuzzle剖析(4)
作者:


这一部分主要和游戏的按键操作有关,我们还是通过代码来分析吧!

public void keyPressed(int code) {
if (gameState != PLAYING)//如果游戏状态不适正在游戏,那么退出操作
return;

int game = getGameAction(code);//得到游戏键

int swapx = blankp.x;//得到空方块的位置,作为交换的坐标
int swapy = blankp.y;

int direction = (options.reversed ? -1 : 1);

switch (game) {
case Canvas.UP: //向上按钮
swapy += direction;
break;
case Canvas.DOWN: //向下按钮
swapy -= direction;
break;
case Canvas.LEFT: //向左按钮
swapx += direction;
break;
case Canvas.RIGHT: //向右按钮
swapx -= direction;
break;
default:
return;
}

//超出边界,不执行任何动作
if (swapx < 0 || swapx >= gridw ||
swapy < 0 || swapy >= gridh) {
return;
}

moveBlank(swapx, swapy); //调用moveBlank函数
repaint(); //更新显示

if (isSolved()) {
setState(WON);
}
}

}

//交换方块位置
// swap the piece at sx, sy with the blank piece
// assumes that this is a legal move

void moveBlank(int swapx, int swapy) {
setGrid(grid[swapx][swapy], blankp.x, blankp.y);//调用setGrid函数
setGrid(blankp, swapx, swapy);
}

//除了将它移动到相应的位置之外,还在grid表格中加以标注
void setGrid(Piece p, int x, int y) {
grid[x][y] = p;
p.setLocation(x, y);
}

void setLocation(int nx, int ny) {
x = nx;
y = ny;
}


这样从开始到玩游戏的过程我们都描述完了,可以看到对于这样的游戏,使用数组是必需的,一个用来记录当前的各方块的位置,一个用来记录应当到达的位置,通过比较两者的位置来判断是否赢了。




↑返回目录
前一篇: 制作是男人就撑30秒
后一篇: 优秀的J2ME网站集锦(转贴)