From 44324ba5d6cac01048cc5cbecbff255ee56f2fc0 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sat, 14 Mar 2015 16:13:11 -0400 Subject: Wrote simple factory to read map and entity data from XML files --- src/entityfactory.cpp | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 src/entityfactory.cpp (limited to 'src/entityfactory.cpp') diff --git a/src/entityfactory.cpp b/src/entityfactory.cpp new file mode 100644 index 0000000..acf9b8e --- /dev/null +++ b/src/entityfactory.cpp @@ -0,0 +1,101 @@ +#include "entityfactory.h" +#include +#include "components.h" +#include "muxer.h" +#include + +struct EntityData { + char* sprite; + char* action; + bool hasPhysics; + int width; + int height; +}; + +static std::map factories; + +std::shared_ptr EntityFactory::createNamedEntity(const std::string name, const Map& map) +{ + auto it = factories.find(name); + EntityData data = factories[name]; + if (it == factories.end()) + { + xmlDocPtr doc = xmlParseFile(("../entities/" + name + ".xml").c_str()); + if (doc == nullptr) + { + fprintf(stderr, "Error reading entity %s\n", name.c_str()); + exit(-1); + } + + xmlNodePtr top = xmlDocGetRootElement(doc); + if (top == nullptr) + { + fprintf(stderr, "Empty entity %s\n", name.c_str()); + exit(-1); + } + + if (xmlStrcmp(top->name, (const xmlChar*) "entity-def")) + { + fprintf(stderr, "Invalid entity definition %s\n", name.c_str()); + exit(-1); + } + + for (xmlNodePtr node = top->xmlChildrenNode; node != NULL; node = node->next) + { + if (!xmlStrcmp(node->name, (const xmlChar*) "sprite")) + { + xmlChar* key = xmlNodeListGetString(doc, node->xmlChildrenNode, 1); + data.sprite = (char*) calloc(xmlStrlen(key)+1, sizeof(char)); + strcpy(data.sprite, (char*) key); + xmlFree(key); + } else if (!xmlStrcmp(node->name, (const xmlChar*) "action")) + { + xmlChar* key = xmlNodeListGetString(doc, node->xmlChildrenNode, 1); + data.action = (char*) calloc(xmlStrlen(key)+1, sizeof(char)); + strcpy(data.action, (char*) key); + xmlFree(key); + } else if (!xmlStrcmp(node->name, (const xmlChar*) "size")) + { + xmlChar* key = xmlNodeListGetString(doc, node->xmlChildrenNode, 1); + data.hasPhysics = true; + sscanf((char*) key, "%d,%d", &(data.width), &(data.height)); + xmlFree(key); + } + } + + xmlFreeDoc(doc); + + factories[name] = data; + } + + auto entity = std::make_shared(); + + if (data.sprite) + { + auto component = std::make_shared(data.sprite); + entity->addComponent(component); + } + + if (data.action) + { + if (!strcmp(data.action, "save")) + { + auto component = std::make_shared([&] (Game& game, Entity& collider) { + playSound("../res/Pickup_Coin23.wav", 0.25); + + game.saveGame(map, collider.position); + }); + entity->addComponent(component); + } + } + + if (data.hasPhysics) + { + auto component = std::make_shared(); + entity->addComponent(component); + + entity->size = std::make_pair(data.width, data.height); + } + + return entity; +} -- cgit 1.4.1