我正在编写一个简单的 2D 游戏,以带有 RPG 元素的迷宫为中心。它主要用于学习目的,以练习课程设计、图论算法、数据结构使用和使用 2D 图形。
该计划的简要概述:
游戏本身是基于瓷砖的。它目前在屏幕上生成并绘制迷宫,允许玩家移动和墙壁碰撞检测;此外,它还可以处理较大迷宫的屏幕滚动。
无论如何,现在我正在构建一个对象来处理在地图周围放置对象。首先是金币,然后是心和物品。我认为这将是练习继承和多态的好时机,但我还没有接受过这种设计的任何正式培训。这是头文件:
#ifndef MAP_OBJECT_H
#define MAP_OBJECT_H
#include "Common.h"
#include "Utility Functions.h"
const int TILE_SIZE = 80;
class MapObject
{
public:
MapObject(unsigned int nClips, unsigned int r, unsigned int c, unsigned int cSize) :
sheet(0), clips(0), row(r), col(c), numClips(nClips), clipSize(cSize)
{
//For those of you who aren't familiar with sprite sheet usage, basically this
// handles which part of the sprite sheet your on, so it will draw the correct sprite to the screen
if(numClips > 0) clips = new SDL_Rect[numClips];
box.h = clipSize;
box.w = clipSize;
}
virtual ~MapObject() //NOt sure if this is right. All the derived classes will
// behave the same upon deletion, since the only resource
// that got allocated was for the box SDL_rect
{
if(clips) delete[] clips;
}
void initBox(int modX, int modY);
//I think each object will draw a little different, so I made it virtual
virtual void draw() = 0;
//Same with interaction--although I'm not sure how my player class is going to be able to handle this yet
virtual void interact() = 0;
SDL_Rect getBox() const;
private:
SDL_Surface* sheet;
SDL_Rect box;
SDL_Rect* clips;
unsigned int row, col;
unsigned int numClips;
unsigned int clipSize;
MapObject() {} //Made this private because I want the memory to be allocated, and
// numClips needs to be initialized for that to happen, so
//basically I'm forcing the user to use the constructor with parameters
};
class Coin : public MapObject
{
enum CoinFace //This represents all the different coin facings in the sprite
//sheet, so that is can animate. Used in the draw function.
{
FRONT,
TURN1,
TURN2,
TURN3,
USED
};
CoinFace active;
public:
virtual void draw(SDL_Surface* destination);
virtual void interact();
};
#endif //MAP_OBJECTS
我最大的问题是一个普遍的问题:这是我设计的一个好的开始吗?他们有明显的问题吗?滥用 OOD 原则/惯例?
像这样定义虚拟析构函数会允许所有派生类使用它吗?还是我需要为每个派生类定义它?
我意识到这很多,我感谢任何帮助。我真的很想了解 OOD 以及如何使用多态性,所以一些专业人士的帮助会非常有用。
再次感谢。
编辑:我的大问题也是开始能够修改派生类中的私有数据成员的问题。如果我需要这样做,我听说这是糟糕的类设计,而且我不知道如何编写一个好的接口,我猜。