我试着用SDL-2创建一些C++“类似流氓”的游戏。为此,我学习了Lazy的教程,以了解如何使用SDL。
我已经学习C++/C# 3年了,但现在我学习项目管理,没有更多的IT课程。
下面是代码的github:https://github.com/Paingouin/Roguelike-SDL2-train/tree/master/
我创建了两个类:LTexture帮助管理图片的加载和呈现,Glyph用于管理动画/缩放和图片的定位.
现在,我想要创建一个实体类,由一个Glyph对象组成,我将使用它来表示一个墙、一个怪物、一个项目等等。但是,我想如果我那样做,我会用太多的记忆.
也许我应该通过初始化字形指针数组来使用聚合,并将其关联到实体的对象.我不知道,我迷路了。
你能帮帮我吗?还有,你有什么建议或建议来帮助我正确构造吗?
发布于 2016-07-07 07:28:28
实际上,您的问题可以不用直接回答SDL,任何库(比如sfml)都可能会出现相同的问题,解决方案都是一样的:答案是单例设计模式,因为您的纹理为什么是单例?我们来谈谈墙砖吧。您可能有数千甚至更多的墙砖--所有的都具有相同的纹理,您真的想在每个墙上加载它吗?不是的。这是相同的纹理,您希望拥有每个给定纹理的一个实例,更重要的是:如果您使用包含所有内容或包含3个工作表的sprite工作表,您可以节省资源工作:虽然在sfml中有一个示例,但在SDL中应该是相同的。pattern
下面是一个sfml实现,但其背后的想法应该是清晰的,并且易于传递:
class Resources {
sf::Clock m_clock; //holds clock
sf::Texture m_soma,m_lvl,m_enemies; //holds hero,lvl &enemies textures respectively
sf::Font m_font; //holds game font
Resources();
public:
~Resources() {}
Resources(const Resources &) = delete;
Resources& operator=(const Resources &) = delete;
static Resources& instance();
sf::Texture& texture();
sf::Texture& lvlTexture();
sf::Texture& Enemies();
sf::Clock& clock();
sf::Font & Font();
};cpp文件:请注意,我可以使用向量而不是3个纹理。
Resources::Resources()
{
//loading textures(hero,lvls,enemies)
if (!m_soma.loadFromFile("..\\resources\\sprites\\soma.png"))
{
std::cerr << "problem loading texture\n";
throw ResourceExceptions("couldn't load player sprites!: must have ..\\resources\\sprites\\soma.png");
}
if (!m_lvl.loadFromFile("..\\resources\\sprites\\lv.png"))
{
std::cerr << "problem loading texture\n";
throw ResourceExceptions("couldn't load level sprites!: must have ..\\resources\\sprites\\lv.png");
}
if (!m_enemies.loadFromFile("..\\resources\\sprites\\enemies.png"))
{
std::cerr << "problem loading texture\n";
throw ResourceExceptions("couldn't load enemies sprites!: must have ..\\resources\\sprites\\enemies.png");
}
//loading font once
if (!m_font.loadFromFile("..\\resources\\font\\gothic.otf"))
{
std::cerr << "problem loading font\n";
throw ResourceExceptions("couldn't load game Font: must have ..\\resources\\font\\gothic.otf");
}
}
Resources & Resources::instance()
{
static Resources resource;
return resource;
}
sf::Texture & Resources::texture()
{
return m_soma;
}
sf::Texture & Resources::lvlTexture()
{
return m_lvl;
}
sf::Texture & Resources::Enemies()
{
return m_enemies;
}
sf::Clock & Resources::clock()
{
return m_clock;
}
sf::Font & Resources::Font()
{
return m_font;
}例如:用法如下: m_sprite.setTexture(Resources::instance().texture());
//
同样的想法可以应用在任何地方,甚至更多,如果偶然的话,你会处理3d对象,并呈现那些你会发现单例还不够的设计模式,你可以参考“飞重”设计模式--我建议你读两样东西: gameprogrammingpatterns.com和传说中的书:设计模式:可重用的面向对象软件的元素
您的代码中存在几个代码问题:例如。开关箱在移动。扪心自问:“如果我突然想增加一个额外的动作,会发生什么?”“如果我想让它根据以前的运动表现得不同呢?”您的方法将带您进行广泛和长时间的切换情况。这两种方法都将向您展示允许您更容易地更改代码的方法。
https://stackoverflow.com/questions/38239256
复制相似问题