开发过手机游戏的人就知道手机开发的三要素: 画布(用来绘画游戏的画面)键盘事件,实时刷新。 我们知道一般的游戏画面都是由地图, 精灵(由游戏的主角,怪物组成), 那我们现在就看看贪吃蛇是怎样他的地图的:
一、实现游戏的界面 :
1、 先声明用来存放绘画图像的X,Y轴的位置的数组:
private int[][] mTileGrid;//
/***************
Tileindex 图片的索引
X轴的位置:
Y轴的位置:
**************/
2、 编写存放图片索引用图片的X,Y轴位置;
public void tTile(int tileindex, int x, int y) {
mTileGrid[x][y] = tileindex;
}
3、调用以上的方法以循环的方式位置数组赋值以及图片的索引,
private void updateWalls() {
for (int x = 0; x < mXTileCount; x++) {
tTile(GREEN_STAR, x, 0);//设置顶部的界线的位置
tTile(GREEN_STAR, x, mYTileCount - 1);// 设置底部界线的
}
for (int y = 1; y < mYTileCount - 1; y++) {
tTile(GREEN_STAR, 0, y);/设置左边的界线的位置
tTile(GREEN_STAR, mXTileCount - 1, y);/设置右边的界线的位置
}
}
4、重写VIEW 类里面的方法。 把界线画出。
public void onDraw(Canvas canvas) {
Draw(canvas);
for (int x = 0; x < mXTileCount; x += 1) {
for (int y = 0; y < mYTileCount; y += 1) {
if (mTileGrid[x][y] > 0) {
违反廉洁纪律 canvas.drawBitmap(mTileArray[mTileGrid[x][y]],
mXOfft + x * mTileSize,
mYOfft + y * mTileSize,十二星座图片
mPaint);
}
同上可见: 地图其实就是由图片数组拼直面成的。 面图片又是通过他的图片索引找到,并在mTileGrid[x][y],获取他们的位置索引来确定图片的位置。 这样在一个手机的页面就形成了,简单吧。
苹果的位置就是更简单了,他是随机生成的, 而且必须在现在蛇的位置相对远距离:
看看他的代码:
private void addRandomApple() {
Coordinate newCoord = null;
boolean found = fal;
while (!found) { //
// Choo a new location for our apple多愁善感近义词
// 随机生成新的X,Y位置
int newX = 1 + Int(mXTileCount - 2);
int newY = 1 + Int(mYTileCount - 2);
newCoord = new Coordinate(newX, newY);
boolean collision = fal;
int snakelength = mSnakeTrail.size();伋的拼音
for (int index = 0; index < snakelength; index++) {两字词语大全
// 检查一下是存放的位置是否合理流
if ((index).equals(newCoord)) {
collision = true;
}
}
found = !collision;
}
丰田怎么样
if (newCoord == null) {
Log.e(TAG, "Somehow ended up with a null newCoord!");
}
mAppleList.add(newCoord);// 添加到新苹果的列表中,
}
2) 实现键盘事件:
键盘主要起操作作用, 在任何的手机游戏中键盘都是起重要的用,要本游戏中, 他就是起控制蛇的行走方向: 现在我们分析他的代码:
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
if (mDirection != NORTH) {
mNextDirection = SOUTH;
}
return (true);
}
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (mDirection != EAST) {
mNextDirection = WEST;
}
return (true);
}
国画牡丹图
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
if (mDirection != WEST) {
mNextDirection = EAST;
}
return (true);
}
以上的代码大家一看就明白, 就是通过判断那个键按下, 然后再给要走的方向(mDirection)赋值。
以下的代码就是通
switch (mDirection) {
ca EAST: {
newHead = new Coordinate(head.x + 1, head.y);
break;
}
ca WEST: {
newHead = new Coordinate(head.x - 1, head.y);
break;
}
ca NORTH: {
newHead = new Coordinate(head.x, head.y - 1);
break;
}
ca SOUTH: {
newHead = new Coordinate(head.x, head.y + 1);