TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
定义游戏的角色和特征
一个只能将图片左右移动的游戏是没有意思的。我们现在要对清单1的代码作一些改动,让它变得更有趣些。首先我们要定义游戏显示的边界,这样能保证在所有设备上的大小一致,先定义一些常量,如下代码所示:

//
游戏边界

public
static
final
int
GAME_WIDTH
=
160
;

public
static
final
int
GAME_HEIGHT
=
160
;


//
游戏屏幕的原点坐标(左上角)

public
final
int
GAME_ORIGIN_X
=
(getWidth()
-
GAME_WIDTH)
/
2
;

public
final
int
GAME_ORIGIN_Y
=
(getHeight()
-
GAME_HEIGHT)
/
2
;


//
couple小精灵上下区域的高度

public
final
int
SECTION_HEIGHT
=
64
;


//
couple小精灵来回移动的基准位(base)

public
final
int
BASE
=
GAME_ORIGIN_Y
+
GAME_HEIGHT
-
SECTION_HEIGHT;


//
couple小精灵跳跃的最大高度

public
final
int
MAX_HEIGHT
=
32
;
(注意,我们这里引入了一个游戏特征:couple小精灵很快就可以在屏幕上跳动了)
在游戏屏幕上定义的这些常量规定了游戏的边界,如图2所示。

图 2. 用常量定义游戏边界
当然,我们现在需要修改代码来使用这些常量。在清单1的代码中添加一个buildGameScreen(Graphics g)方法,如下代码所示:

private
void
buildGameScreen(Graphics g)
 

{
// 设置画笔为黑色
g.setColor(0x000000);
// 绘制游戏边界
g.drawRect(GAME_ORIGIN_X, GAME_ORIGIN_Y, GAME_WIDTH, GAME_HEIGHT);

// 绘制基准线
g.drawLine(GAME_ORIGIN_X, BASE, GAME_ORIGIN_X + GAME_WIDTH, BASE);

//标出couple小精灵能跳到的最高位置
g.drawLine(GAME_ORIGIN_X, BASE - MAX_HEIGHT, GAME_ORIGIN_X + GAME_WIDTH, BASE - MAX_HEIGHT);
}
再在updateGameScreen()方法里绘制couple之前添加一个该方法的调用,还要将couple小精灵的开始位置由CENTER_Y改为BASE(在start()方法里设置coupleY = BASE)。 couple小精灵可以左右移动,我们要限制它走出边界,更改calculateCoupleX()方法里左右移动的代码,避免坐标超出边界。修改后的代码如下:

private
void
calculateCoupleX(
int
keyState)
 

{
// 根据移动方向改变x坐标
if((keyState & LEFT_PRESSED) != 0)
 {
coupleX = Math.max(
GAME_ORIGIN_X + coupleImg.getWidth() / 2,
coupleX - dx);
}
else if((keyState & RIGHT_PRESSED) != 0)
 {
coupleX = Math.min(
GAME_ORIGIN_X + GAME_WIDTH - coupleImg.getWidth() / 2,
coupleX + dx);
}
}
方法使用Math.max()和min()函数使图片显示在游戏边界内。注意我们在计算中还考虑了图片的大小。 我们刚才说过要实现couple小精灵在屏幕上跳跃的功能,我们现在增加一个方法使图片在Y轴上移动,跳跃时移动的具体路径将不受玩家影响。 在清单1的代码中添加三个新的实例变量:up、jumpHeight 和random。如下所示:

//
表示couple小精灵移动方向的标识

private
boolean
up
=
true
;


//
跳跃高度,跳跃时随机生成

private
int
jumpHeight
=
MAX_HEIGHT;


//
随机数产生器

public
Random random
=
new
Random();
jumpHeight初始值被设为MAX_HEIGHT。jumpHeight变量会在couple小精灵每次跳跃时动态设为随机值,新增的calculateCoupleY()方法如下:

private
void
calculateCoupleY(
int
keyState)
 

{
// 检查couple小精灵是否在跳跃
if(up)
 {
// 检查小精灵是否跳到了最大高度
if((coupleY > (BASE - jumpHeight + coupleImg.getHeight())))
 {
//没达到最大高度,继续上升
coupleY -= dy;
}
else if(coupleY == (BASE - jumpHeight + coupleImg.getHeight()))
 {
// 到了最大高度,开始下降
coupleY += dy;

// 修改方向标识
up = false;
}
}
else
 {
// 小精灵正在下降,检查是否到地面了?
if(coupleY < BASE)
 {
// 还没有,继续下降
coupleY += dy;
}
else if(coupleY == BASE)
 {
// 到达地面,算一个新的随机高度(小于等于最大高度)
int hyper = random.nextInt(MAX_HEIGHT + 1);
// 保证跳跃高度大于图像高度
if(hyper > coupleImg.getHeight())
 {
jumpHeight = hyper;
}

// 往上跳
coupleY -= dy;

// 重置方向标识
up = true;
}
}
}
你可能已经发觉,这个方法不依赖于用户的按键,传入的keyState信息也没有用到。传入这个值是为了与calculateCoupleX()方法保持一致。方法刚开始时通过渐增coupleY变量值使couple小精灵上升,直到达到这次的跳跃高度(刚开始是MAX_HEIGHT)。达到这个高度后,小精灵开始往下降,降到BASE后又随机生成一个介于MAX_HEIGHT和图像高度之间的数值,按这个高度开始下一次跳跃。 游戏的整个效果是一个以随机高度跳跃的couple小精灵,它可以在用户的操纵下左右移动。图3是游戏的一个截屏:

图 3. 游戏截屏 |
|