我正在制作一个游戏,当你向下移动屏幕时,你可以避开由'X'组成的墙壁,如果你击中X,你将失去一个盾牌并继续掠过X而不会再失去任何盾牌,直到你弹出一个角色空间哪里没有X.
但是,当运行下面的代码以及其他一些不必要的代码时,如果我在Visual Studio中停止运行,它会完美地运行,但是当我在代码运行时开始撞到'X'墙并且墙壁移动得非常快时它不会工作正确,你最终做了耕作,但你失去了过程中的所有盾牌,并且当你"犁"穿过它们时,X不会消失.
这是代码:
char coll; // the buffer for the collided char
if (theScreen.check_collision(player, xMove, yMove, coll) != true) {
// no collision
// get rid of old player placing
theScreen.Insert(' ', player.get_location()[0], player.get_location()[1]);
// put in new charater placing
player.move(xMove, yMove);
theScreen.Insert(player);
numb_coll = 0;
} else {
// collision
if (coll == 'X' && player.get_shield() > 0) {
for (int I = 0; I < numb_coll && numb_coll < player.get_location()[1]; I++) {
theScreen.Insert(' ', player.get_location()[0],
player.get_location()[1] - (I + 1));
}
if (numb_coll == 0)
player.set_shield(player.get_shield() - 1);
numb_coll++;
theScreen.Insert(player);
}
if (coll == 'X' && player.get_shield() <= 0)
dead = true;
};
Run Code Online (Sandbox Code Playgroud)
我建议对代码进行彻底的重组.此例程似乎与在屏幕上绘制播放器和更改播放器的屏蔽等级有关.我相信如果你将播放器的显示与播放器的修改分开,你的代码将更容易阅读和维护.
考虑一下:
theScreen.check_collision(player, xMove, yMove, coll) {
/* your current check_collision code, which I hope is correct */
if (collision)
player.destroy_a_shield();
return collision;
}
Run Code Online (Sandbox Code Playgroud)
在你的player对象中:
player.destroy_a_shield() {
self.shield--;
if (self.shield == 0)
player.dead = true;
}
Run Code Online (Sandbox Code Playgroud)
然后这段代码看起来更像是:
if (theScreen.check_collision(player, xMove, yMove, coll) {
if (player.dead)
theScreen.insert("Ooops. Game over. Better luck next life.");
else {
for (int I = 0; I < numb_coll && numb_coll < player.get_location()[1]; I++) {
theScreen.Insert(' ', player.get_location()[0],
player.get_location()[1] - (I + 1));
}
numb_coll++;
theScreen.Insert(player);
}
} else {
theScreen.Insert(' ', player.get_location()[0], player.get_location()[1]);
player.move(xMove, yMove);
theScreen.Insert(player);
}
Run Code Online (Sandbox Code Playgroud)
这些修改的想法(以伪代码呈现,因为我很懒,因为我不知道你的代码的其余部分是什么样子)是将屏幕显示与游戏机制分开.(您之前可能已经听过"模型 - 视图 - 控制器"一词 - 这种模式准确地描述了我的建议.将业务规则从您的视图中移出.:)