在大多数或所有面向对象的游戏中,每个类不仅依赖于自己的类,还依赖于父类。这个类连接如何用C++实现?您只是为所需的父类添加一个指针还是有更好的方法?
例如,一场足球比赛,当人类单击时,询问场景类他是否踢了球,然后又移动了。我希望这是可以理解的,而不是太抽象。
最佳答案
我认为在构造函数中传递父代不是一个好主意。相反,您应该使用一个类来维护所有游戏元素和它们之间的设施交互的列表;例如,下面说明的Game类将检查任何两个玩家之间的碰撞,如果检测到,则告诉每个玩家他们被击中以及被谁击中。
我不确定这是否会使您受益,但是我在最初的回答中输入了它,因此我不妨提交。请注意,如果您正在谈论纯文字游戏,那么所有这些仍然是相关的,在这种情况下,请忽略对图形的暗示。游戏设计基于连续的游戏循环,可以简单地认为是:
while(true)
for each tick:
react to user input
update player, enemies, objects, etc.
end while
“tick”是游戏时钟的每次迭代,但是您可以选择实现它-基于fps,每秒一次,无论如何。在您的示例中,用户单击足球,游戏看到该点击并告诉足球移动。为此,请在维护状态的类中维护所有游戏元素的列表。为了说明这一点,这是实现此目标的非常基本的方法:
class Game {
vector<GameElement> elements;
Football football;
Player currentPlayer;
Game() {
this.football = new Football();
}
void update() {
for e in elements:
e.update();
// Once every element has been updated for the current tick, redraw them on the screen
screen.redraw();
}
void addElement(GameElement e) {
elements.add(e);
}
}
class GameElement {
int posx, posy; // screen coordinates
void paint() {}; // method to draw this element to the screen
virtual void update();
}
class Football: public GameElement {
bool kicked;
int anglex, angley;
double velocity;
void update() {
if(kicked){
// update position, angle, velocity; slow it down, check for bounce, whatever
posx = new x position;
posy = new y position;
if(velocity == 0)
kicked = false;
}
paint(); // call the paint method after the new position has been found
}
}
假设您还有一个继承自GameElement的类,即Player,它的方法kick(football)将传递的足球设置为运动-即,设置kicked = True。因此,要初始化游戏,您可以使用以下方法进行设置:
Game game = Game();
game.add(new Football());
game.add(new Player());
while(true) {
if(user_input==X)
game.currentPlayer.kick(football);
game.update();
sleep(1);
}
可以更改这种方式以维护例如图层而不是整个游戏,然后更高级别的类可以按顺序调用每个图层的更新,从而使事物可以相互画图,并且子代只能与同级互动。有很多可能性。