World::World(WorldListener* listener) : bob(5, 1), castle(-1,-1) { this->listener = listener; generateLevel(); this->heightSoFar = 0; this->score = 0; this->state = WORLD_STATE_RUNNING; }
void SceneManager::fillStack() { // Get instance of director Director* director = Director::getInstance(); // Empty the stack director->popToRootScene(); // Add scenes to stack director->replaceScene(TransitionFade::create(4, generateLevel(1, 0), Color3B::BLACK)); level = 1; }
Dungeon* DungeonGenerator::generateDungeon(int width, int height) { width = std::max(MIN_DUNGEON_WIDTH, std::min(MAX_DUNGEON_WIDTH, width)); height = std::max(MIN_DUNGEON_HEIGHT, std::min(MAX_DUNGEON_HEIGHT, height)); auto* dungeon = new Dungeon(width, height, MAX_DUNGEON_LEVEL); std::random_device device; std::default_random_engine engine(device()); generateLevel(0, dungeon, width, height, engine); ConnectAllUnconnectedRooms(dungeon); return dungeon; }
//-------------------------------------------------------------- void testApp::setup(){ ofSetFrameRate(60); // Kinect initialization code kinect.initSensor(); // We first set up data streams for the Kinect (color, depth and skeleton tracking) kinect.initColorStream(640, 480, true); kinect.initDepthStream(640, 480, true); kinect.initSkeletonStream(false); // Launch Kinect kinect.start(); box2d.init(); box2d.setGravity(0, 10); box2d.createBounds(); box2d.setFPS(30.0); box2d.registerGrabbing(); ambientCanyon.loadImage("westernvalley.gif"); LHumerusTrack.setup(box2d.getWorld(),0,0, 80, 20); RHumerusTrack.setup(box2d.getWorld(),0,0, 80, 20); LRadiusTrack.setup( box2d.getWorld(),0,0, 70, 20); RRadiusTrack.setup( box2d.getWorld(),0,0, 70, 20); explosion.loadSound("explosion.wav"); explosion.setVolume(1.0f); explosion.setLoop(false); splash.loadSound("splash.wav"); splash.setVolume(1.0f); splash.setLoop(false); mines.loadSound("mines.mp3"); mines.setVolume(0.6f); mines.setLoop(true); mines.play(); score = 0; level = 1; started = false; //SET UP THE TRACKS: generateLevel(); }
void GameEngine::restart() { //Reinitialize the inventory and message log log = MessageLog(); invLog = InventoryLog(); log.init(&lib); invLog.init(&lib, hero, &log); //Re initialize the hero deadHero = false; delete hero; hero = new Hero(main, Point(0, 0), true); currLevel = 1; inBossRoom = false; generateLevel(); }
//-------------------------------------------------------------- void testApp::update(){ kinect.update(); box2d.update(); if(vehicles.size() == 0){ vehicles.push_back(ofPtr<Vehicle>(new Vehicle)); vehicles.back().get()->setPhysics(3.0, 0.0, 0.1); vehicles.back().get()->setVelocity(5,0); vehicles.back().get()->setup(box2d.getWorld(), 20, 230 , 30, 30); } if(started != false){ //SE ACTUALIZAN LOS VEHICULOS for(int i=0; i< vehicles.size(); i++) { vehicles[i].get()->update(); if(vehicles[i].get()->getPosition().x > ofGetWidth()-20){ //vehicles[i].get()->destroy(); //vehicles[i].get()->setPosition(20,220); score += 1; } } for(int i=0; i<vehicles.size(); i++) { //SI LLEGAN AL FINAL SE ENVIAN AL LIMBO A ESPERAR (PORQUE NO SE PUEDEN DESTRUIR...?) if( vehicles[i].get()->getPosition().x > ofGetWidth()-20){ vehicles[i].get()->setPosition(2000,2000); //generateLevel(); } } for(int i = 0 ; i < vehicles.size() ; i++){ //SI CAEN AL AGUA SE REINICIA EL NIVEL if( vehicles[i].get()->getPosition().y > ofGetHeight()-50 && vehicles[i].get()->getPosition().x > 0 && vehicles[i].get()->getPosition().x < ofGetWidth()){ splash.play(); //vehicles[i].get()->setPosition(20,220); started = false; resetTrains(); } } //if all trains are done: if(allTrainsDone() == true){ level++; generateLevel(); started = false; for(int i=0; i<vehicles.size(); i++) { vehicles[i].get()->setPosition(15,230); } if(level%3 == 0){ vehicles.push_back(ofPtr<Vehicle>(new Vehicle)); vehicles.back().get()->setPhysics(3.0, 0.0, 0.1); vehicles.back().get()->setVelocity(5,0); vehicles.back().get()->setup(box2d.getWorld(), 20, 230 , 30, 30); } } } }
int main() { sf2d_init(); sf2d_set_vblank_wait(0); // this will depend on the level uint8_t mapWidth = 4; uint8_t mapHeight = 3; uint16_t mapDim = mapWidth*mapHeight; uint8_t map_u[mapDim]; uint16_t mapLength = generateLevel(map_u, mapWidth, mapHeight, 12); uint8_t map[mapDim]; memcpy(map, map_u, mapDim); // get some drawing parameters uint16_t areaWidth = TWIDTH*2/3; uint16_t areaHeight = THEIGHT*2/3; uint16_t recWidth = areaWidth/mapWidth; uint16_t recHeight = areaHeight/mapHeight; uint16_t areaTop = (THEIGHT-mapHeight*recHeight)/2; uint16_t areaLeft = (TWIDTH-mapWidth*recWidth)/2; uint8_t curX = 0; uint8_t curY = 0; uint16_t playerLength = 0; float colorInterpolation = 0; u64 oldTime = 0; u64 keyTime = 0; while (aptMainLoop()) { // manage timer according to time passed since last frame u64 newTime = osGetTime(); keyTime += newTime-oldTime; oldTime = newTime; hidScanInput(); if (hidKeysDown() & KEY_START) break; // move cursor according to input uint16_t oldCurXY = curY*mapWidth+curX; curX += mapWidth; curY += mapHeight; if (hidKeysDown() & KEY_LEFT) curX--; if (hidKeysDown() & KEY_RIGHT) curX++; if (hidKeysDown() & KEY_UP) curY--; if (hidKeysDown() & KEY_DOWN) curY++; curX %= mapWidth; curY %= mapHeight; uint16_t newCurXY = curY*mapWidth+curX; if (newCurXY != oldCurXY) { map[newCurXY]--; playerLength++; keyTime=0; // force cursor display now } if (map[newCurXY] == 255) { // reset level curX = 0; curY = 0; playerLength = 0; memcpy(map, map_u, mapDim); } if (playerLength == mapLength) break; // TODO should be "you won" u32 targetColor = RGBA8(0x00,0xaa,0xaa,255); float targetInterpolation = (float)playerLength/(float)mapLength; if (newTime%256==0) colorInterpolation = (colorInterpolation*3+targetInterpolation*1)/4; u32 darkColor = interpolate(targetColor, greyed(targetColor), colorInterpolation); u32 liteColor = interpolate(darkColor, 0xffffffff, 1.0f/3.0f); // white is too clear u32 bgColor = interpolate(darkColor, 0, 0.5f); sf2d_set_clear_color(bgColor); sf2d_start_frame(GFX_TOP, GFX_LEFT); { // draw tiles for (uint8_t x=0; x<mapWidth; x++) for (uint8_t y=0; y<mapHeight; y++) { sf2d_draw_rectangle(x*recWidth+areaLeft, y*recHeight+areaTop, recWidth, recHeight, interpolate(darkColor, liteColor, ((float)map[y*mapWidth+x])/3)); } // draw cursor float t = (float)(keyTime%2048)/2048.0f; uint8_t op = pow(fabs(t-0.5f)*2,4)*255; sf2d_draw_rectangle(curX*recWidth+areaLeft, curY*recHeight+areaTop, recWidth, recHeight, RGBA8(0,0,0,op)); } sf2d_end_frame(); sf2d_swapbuffers(); } sf2d_fini(); return 0; }
void generateLevel(const std::string &level) { cleanLevel(); Json::Value root; // will contains the root value after parsing. curLevel = new Level(level, &root); if(!loadJSONLevel(level, root)) { printf("Error parsing JSON file for level %s!\n", level.c_str()); generateLevel("worldmap"); return; // TODO: Load from a default? } Json::Value tileset = root["tileset"]; Json::Value customEntities = root["entities"]; char line[201] = ""; std::string filename = "levels/"+level+".lvl"; if(DEBUG) printf("Reading file %s\n", filename.c_str()); FILE *fp = fopen(filename.c_str(), "r"); if(!fp) { printf("ERROR: Level %s not found!\n", filename.c_str()); generateLevel("worldmap"); return; } char blockC[] = "-"; int x=0, y=0, biggestX=0, biggestY=0; Entity *ent; for(y=0; fgets(line, sizeof(line), fp); y++) { if(DEBUG) printf("Read line: %s", line); for(x=0; line[x]; x++) { if(line[x] <= 32) continue; blockC[0] = line[x]; if(!!tileset[blockC]) { if(DEBUG) printf("Spawning block(%d,%d) type(%d,%c)\n", x, y, line[x], line[x]); ent = constructEntity(tileset[blockC], x, y); posLookup[x][y] = ent; // TODO: Remove from list, ensure consistency across block movements setEntityProperties(ent, tileset[blockC]); if(x > biggestX) biggestX = x; if(y > biggestY) biggestY = y; } else { printf("Unknown Block: '%c' (%d)\n", line[x], line[x]); } } memset(line, '\0', sizeof(line)); } curLevel->w = max((biggestX+1)*BLOCK_SIZE, WIDTH); curLevel->h = max((biggestY+1)*BLOCK_SIZE, HEIGHT); char sPos[20]; for(Json::ValueIterator iter = customEntities.begin(); iter != customEntities.end(); iter++ ) { strncpy(sPos, iter.memberName(), sizeof(sPos)-1); x = atoi(strtok(sPos+1, ",")); y = atoi(strtok(NULL, ")")); if((ent = posLookup[x][y]) == NULL) { printf("Level setup error: Entity(%d,%d) not found!\n", x, y); continue; } if(DEBUG) printf("Applying Entity(%d,%d) specifics...\n", x, y); setEntityProperties(ent, *iter); } compileBackground(renderer); }
void SceneManager::nextLevel(int score) { level++; Director::getInstance()->replaceScene(TransitionFade::create(4, generateLevel(level,score), Color3B::BLACK)); }
void ServerPacketHandlerSystem::handleLoading() { while( m_server->hasNewPackets() ) { Packet packet = m_server->popNewPacket(); char packetType; packetType = packet.getPacketType(); if(packetType == (char)PacketType::ChangeStatePacket){ ChangeStatePacket statePacket; statePacket.unpack(packet); if(statePacket.m_gameState == GameStates::LOADING){ m_readyLoadingPlayers++; } } } PlayerSystem* playerSys = static_cast<PlayerSystem*>( m_world->getSystem(SystemType::PlayerSystem)); if(m_readyLoadingPlayers == playerSys->getActiveEntities().size()){ /************************************************************************/ /* Generates the level here based on the existing amount of players */ /* LevelGen, LevelHandler and SpawnPoints need to be reset before */ /* generating a new level. */ /************************************************************************/ auto levelGen = static_cast<LevelGenSystem*>( m_world->getSystem(SystemType::LevelGenSystem)); auto levelHandler = static_cast<LevelHandlerSystem*>( m_world->getSystem(SystemType::LevelHandlerSystem)); auto spawnPointSys = static_cast<SpawnPointSystem*>( m_world->getSystem(SystemType::SpawnPointSystem)); if (!levelGen->isLevelGenerated()) { levelHandler->destroyLevel(); spawnPointSys->clearSpawnPoints(); levelGen->generateLevel(m_readyLoadingPlayers); } if (levelHandler->hasLevel() && spawnPointSys->isSpawnPointsReady()) { /************************************************************************/ /* Send the already networkSynced objects located on the server to the */ /* newly connected client. */ /************************************************************************/ NetworkSynced* netSync; Transform* transform; vector<Entity*> dynamicEntities = static_cast<ServerDynamicObjectsSystem*>( m_world->getSystem(SystemType::ServerDynamicObjectsSystem))->getActiveEntities(); for( unsigned int i=0; i<dynamicEntities.size(); i++ ) { int entityId = dynamicEntities[i]->getIndex(); netSync = (NetworkSynced*)m_world->getComponentManager()-> getComponent( entityId, ComponentType::NetworkSynced ); transform = (Transform*)m_world->getComponentManager()-> getComponent( entityId, ComponentType::Transform ); EntityCreationPacket data; data.entityType = static_cast<char>(netSync->getNetworkType()); data.owner = netSync->getNetworkOwner(); data.playerID = netSync->getPlayerID(); data.networkIdentity = netSync->getNetworkIdentity(); data.meshInfo = 0; //Temp if (transform) { data.translation = transform->getTranslation(); data.rotation = transform->getRotation(); data.scale = transform->getScale(); } ///MESH INFO MUST BE MADE INTO A COMPONENT //data.meshInfo = 1; m_server->broadcastPacket( data.pack() ); } /************************************************************************/ /* Send static objects to the newly connected client. */ /************************************************************************/ vector<Entity*> entities = static_cast<ServerStaticObjectsSystem*>(m_world-> getSystem(SystemType::ServerStaticObjectsSystem))->getStaticObjects(); for (unsigned int i= 0; i < entities.size(); i++) { transform = static_cast<Transform*>(entities[i]-> getComponent(ComponentType::Transform)); StaticProp* prop = static_cast<StaticProp*>(entities[i]-> getComponent(ComponentType::StaticProp)); EntityCreationPacket data; data.entityType = static_cast<char>(EntityType::Other); data.owner = -1; //NO OWNER data.networkIdentity = entities[i]->getIndex(); data.translation = transform->getTranslation(); data.rotation = transform->getRotation(); data.scale = transform->getScale(); data.isLevelProp = false;//prop->isLevelPiece; // isLevelProp is no longer // used here. MiscData is // instead. data.meshInfo = prop->meshInfo; data.miscData = prop->propType; LevelPieceRoot* root = static_cast<LevelPieceRoot*>(entities[i]->getComponent(ComponentType::LevelPieceRoot)); if (root) { //data.bsPos = root->boundingSphere.position; //data.bsRadius = root->boundingSphere.radius; /*RootBoundingSpherePacket bspacket; bspacket.targetNetworkIdentity = entities[i]->getIndex(); bspacket.position = root->boundingSphere.position; bspacket.radius = root->boundingSphere.radius;*/ data.networkIdentity = root->pieceId; int miscSize = root->connectedRootPieces.size(); if (miscSize > 0) { data.additionalMisc.resize(miscSize); for (int misc = 0; misc < miscSize; misc++) data.additionalMisc[misc] = root->connectedRootPieces[misc]; } } m_server->broadcastPacket( data.pack() ); } /************************************************************************/ /* Create and send the ship entities. */ /************************************************************************/ //for(unsigned int i=0; i<m_server->getActiveConnections().size(); i++) //{ // createAndBroadCastShip(m_server->getActiveConnections().at(i), (int)i); //} auto playerComps = playerSys->getPlayerComponents(); for (unsigned int i = 0; i < playerComps.size(); i++) { if (playerComps[i]) createAndBroadCastShip(playerComps[i]->m_networkID, playerComps[i]->m_playerID); } // Reset the level state. This sets "ready" to true, and "level generated" to // false. levelGen->resetState(); ChangeStatePacket changeState; changeState.m_serverState = ServerStates::SENTALLPACKETS; m_server->broadcastPacket(changeState.pack()); m_stateSystem->setQueuedState(ServerStates::SENTALLPACKETS); } } }
//Structors GameEngine::GameEngine(char* title, int xScreenRes, int yScreenRes, char* tiles, int tileSize, int tileRes, int worldSize) { lib.init(title, xScreenRes, yScreenRes, tiles, tileSize, tileRes); this->worldSize = worldSize; currLevel = 1; screenOrientation = lib.res() / 2; //Add monster table actordefs = { rat, spider, ant, bee, beetle, snake, dingo, fox, plant, puppy, giant_rat, tarantula, fire_ant, hornet, snow_wolf, werewolf, hyena, eye_djinn, cerberus, tent_mon, priest, hpriest, sad_bag, ass_goblin }; //Add boss table bossdefs = { boss1, boss2, boss3, boss4, boss5, boss6 }; hero = new Hero(main, Point(0, 0), true); //Add pickup table stuff for sloppy pickupdefs = { //health pots PickupDef(0x227, "Small Health Potion", "Restores 10 HP", 1, 100, [&]() { hero->changeHP(10); }), PickupDef(0x237, "Big Health Potion", "Restores 20 HP", 2, 200, [&]() { hero->changeHP(20); }), PickupDef(0x220, "Large Health Potion", "Restores 30 HP", 3, 300, [&]() { hero->changeHP(30); }), //mana pots PickupDef(0x22A, "Small Mana Potion", "Restores 5 mana", 1, 100, [&]() { hero->changeMana(5); }), PickupDef(0x23A, "Mana Potion", "Restores 10 mana", 2, 100, [&]() { hero->changeMana(10); }), PickupDef(0x223, "Large Mana Potion", "Restores 20 mana", 3, 300, [&]() { hero->changeMana(20); }), //helms PickupDef(0x2DC, "Crude Helmet", "Increases defense by 1", 1, 5, 1, 100, [&]() { hero->changeDEF(1); }, [&]() { hero->changeDEF(-1); }), PickupDef(0x2DD, "Steel Helmet", "Increases defense by 2", 1, 5, 2, 200, [&]() { hero->changeDEF(2); }, [&]() { hero->changeDEF(-2); }), PickupDef(0x2D9, "Magician's Hat", "Increases max health by 10", 1, 5, 4, 400, [&]() { hero->changeMaxHP(10); }, [&]() { hero->changeMaxHP(-10); }), //necks PickupDef(0x337, "Worn Necklace", "Increases max health by 5", 2, 10, 1, 100, [&]() { hero->changeMaxHP(5); }, [&]() { hero->changeMaxHP(-5); }), PickupDef(0x338, "Fine Necklace", "Increases defense by 2", 2, 5, 2, 200, [&]() { hero->changeDEF(2); }, [&]() { hero->changeDEF(-2); }), PickupDef(0x33B, "Cross of Al'tair", "Increases defense by 4", 2, 5, 4, 400, [&]() { hero->changeDEF(4); }, [&]() { hero->changeDEF(-4); }), //shirts PickupDef(0x2D0, "Tattered Shirt", "Increases max health by 5", 3, 5, 1, 100, [&]() { hero->changeMaxHP(5); }, [&]() { hero->changeMaxHP(-5); }), PickupDef(0x2D1, "Gold Chainmail", "Increases max health by 10", 3, 5, 2, 200, [&]() { hero->changeMaxHP(10); }, [&]() { hero->changeMaxHP(-10); }), PickupDef(0x2D2, "Vest of the Thief's Guild", "Increases defense by 3", 3, 5, 4, 400, [&]() { hero->changeDEF(3); }, [&]() { hero->changeDEF(-3); }), //gloves PickupDef(0x2E7, "Worn Leather Glove", "Increases defense by 1", 4, 4, 1, 100, [&]() { hero->changeDEF(1); }, [&]() { hero->changeDEF(-1); }), PickupDef(0x2E9, "Chainmail Glove", "Increases defense by 2", 4, 4, 2, 200, [&]() { hero->changeDEF(2); }, [&]() { hero->changeDEF(-2); }), PickupDef(0x2EA, "Glove of the Magi", "Increases max health by 10", 4, 4, 4, 400, [&]() { hero->changeMaxHP(10); }, [&]() { hero->changeMaxHP(-10); }), //shoes PickupDef(0x2E1, "Smelly Old Shoe", "Increases defense by 1", 5, 5, 1, 100, [&]() { hero->changeDEF(1); }, [&]() { hero->changeDEF(-1); }), PickupDef(0x2E2, "Fine Leather Shoe", "Increases defense by 2", 5, 5, 2, 200, [&]() { hero->changeDEF(2); }, [&]() { hero->changeDEF(-2); }), PickupDef(0x2E3, "Knight's Boot", "Increases defense by 3", 5, 5, 4, 400, [&]() { hero->changeDEF(3); }, [&]() { hero->changeDEF(-3); }), //journals PickupDef(0x3D1, "Standard Spell Journal", "Increases max health by 5", 6, 10, 1, 100, [&]() { hero->changeMaxHP(5); }, [&]() { hero->changeMaxHP(-5); }), PickupDef(0x3D3, "Mage's Necronomicon", "Increases max health by 7", 6, 10, 2, 200, [&]() { hero->changeMaxHP(7); }, [&]() { hero->changeMaxHP(-7); }), PickupDef(0x3D4, "Death Note", "Increases max health by 9", 6, 10, 4, 400, [&]() { hero->changeMaxHP(9); }, [&]() { hero->changeMaxHP(-9); }), //swords PickupDef(0x260, "Crude Dagger", "Attack: (2, 14)", 7, 5, 1, 100, [&]() { hero->changeATK(Dice(7, 2)); }, [&]() { hero->revertATK(); }), PickupDef(0x253, "Fine Longsword", "Attack: (3, 15)", 7, 5, 2, 200, [&]() { hero->changeATK(Dice(5, 3)); }, [&]() { hero->revertATK(); }), PickupDef(0x2A2, "Ogre's Battleaxe", "Attack: (4, 16)", 7, 5, 3, 300, [&]() { hero->changeATK(Dice(4, 4)); }, [&]() { hero->revertATK(); }), //shields PickupDef(0x2C0, "Broken Shield", "Increases defense by 1", 8, 2, 1, 100, [&]() { hero->changeDEF(1); }, [&]() { hero->changeDEF(-1); }), PickupDef(0x2C2, "Fine Wooden Shield", "Increases defense by 4", 8, 2, 2, 200, [&]() { hero->changeDEF(4); }, [&]() { hero->changeDEF(-4); }), PickupDef(0x2C3, "Tower Shield", "Increases defense by 5", 8, 2, 4, 400, [&]() { hero->changeDEF(5); }, [&]() { hero->changeDEF(-5); }) }; //Legendary items legendarydefs = { PickupDef(0x2D7, "Hakar's Skull", "Increases defense by 7", 1, 15, 4, 4000, [&]() { hero->changeDEF(7); }, [&]() { hero->changeDEF(-7); }), PickupDef(0x336, "Akator's Blessing", "Increases defense by 6", 2, 15, 4, 4000, [&]() { hero->changeDEF(6); }, [&]() { hero->changeDEF(-6); }), PickupDef(0x2D6, "Hakar's Skin", "Increases defense by 7", 3, 15, 4, 4000, [&]() { hero->changeDEF(7); }, [&]() { hero->changeDEF(-7); }), PickupDef(0x2ED, "Shadowborn Glove", "Increases max health by 40", 4, 15, 4, 4000, [&]() { hero->changeMaxHP(40); }, [&]() { hero->changeMaxHP(-40); }), PickupDef(0x2E5, "Shadowborn Shoe", "Increases defense by 5", 5, 15, 4, 4000, [&]() { hero->changeDEF(5); }, [&]() { hero->changeDEF(-5); }), PickupDef(0x3D6, "Hakar's Bible", "Increases max health by 50", 6, 15, 4, 4000, [&]() { hero->changeMaxHP(50); }, [&]() { hero->changeMaxHP(-50); }), PickupDef(0x390, "Akator's Right Hand", "Attack: (10, 20)", 7, 15, 4, 4000, [&]() { hero->changeATK(Dice(10, 2)); }, [&]() { hero->revertATK(); }), PickupDef(0x2C4, "Hakar's Left Hand", "Increases defense by 6", 8, 15, 4, 4000, [&]() { hero->changeDEF(6); }, [&]() { hero->changeDEF(-6); }), }; //Set up MessageLog / Inventory log.init(&lib); invLog.init(&lib, hero, &log); generateLevel(); }
//main void GameEngine::run() { lib.framestart(); if (!gameStart) renderGameMenu(); else { //Move the char left, right, up, and down if (!deadHero && !shop.isShopping()) { onPlayerTurn((lib.keywentdown("left") || lib.keywentdown("a")), Point(-1, 0)); onPlayerTurn((lib.keywentdown("up") || lib.keywentdown("w")), Point(0, -1)); onPlayerTurn((lib.keywentdown("right") || lib.keywentdown("d")), Point(1, 0)); onPlayerTurn((lib.keywentdown("down") || lib.keywentdown("s")), Point(0, 1)); //Enter stairs if (lib.keywentdown("return") || lib.keywentdown("enter")) { if (hero->getLoc() == stairLoc) { currLevel++; generateLevel(); } if (hero->getLoc() == shop.getLoc()) shop.activateShop(); if (hero->getLoc() == bossLoc) enterBossRoom(); if (hero->getLoc() == stairAscend) leaveBossRoom(); } if (tl_buttonwentdown(1)) { Pickup p = registerInventoryClick(); if (p.getLoc() != Point(-1, -1)) { if (p.getPickupDef().getType() == 0) log.registerEvent(("Used a " + p.getPickupDef().getName() + "!").c_str()); else log.registerEvent(("Equipped a " + p.getPickupDef().getName() + "!").c_str()); } if (lib.mouseLoc() >= Point(lib.res().x() / 2 - 3, lib.res().y() - 4) && lib.mouseLoc() <= Point(lib.res().x() / 2 + 3, lib.res().y() - 4)) useSpell(lib.mouseLoc()); } if (tl_buttonwentdown(3)) { Pickup p; if (invLog.overInvOrGear(lib.mouseLoc()) == 0) { p = invLog.dropItem(lib.mouseLoc()); if (p.getLoc() != Point(-1, -1)) log.registerEvent(("Dropped the " + p.getPickupDef().getName() + "!").c_str()); } else if (invLog.overInvOrGear(lib.mouseLoc()) == 1) { OutputDebugString("herpderp"); p = invLog.unequipGear(lib.mouseLoc()); if (p.getLoc() != Point(-1, -1)) log.registerEvent(("Unequipped the " + p.getPickupDef().getName() + "!").c_str()); } } } drawMap(); onMouseOver(); if(deadHero) { if (lib.keywentdown("escape")) gameStart = false; } } }
int main(int argc, char *argv[]) { static SDL_Window *window; if(initWindow(&window, &renderer, argc, argv)) return 1; initVariables(WIDTH, HEIGHT); initTextures(); initFonts(); initInput(); //initHUD(); generateLevel(FIRSTLEVEL); hud = new Hud(); /*==============*/ /* Test Stuff */ /*==============*/ /*PhysicsEntity *goomba = new PhysicsEntity(getTexture("goomba"), 500, 50); goomba->patrolling = 1; Interactable *healthUp = new Interactable(getTexture("concrete"), 800, 500); healthUp->target = ply; healthUp->action = HEALTH_UP; Interactable *scrapUp = new Interactable(getTexture("sand"), 850, 500); scrapUp->target = ply; scrapUp->action = SCRAP_UP;*/ /*=================*/ /*End of Test Stuff*/ /*=================*/ int lastFrame = curtime_u() - 1; double dt; while(!quit) { if(DEBUG) fpsCounter(); // Calculate dt int curFrame = curtime_u(); if(lastFrame > curFrame) { dt = ((1000000 - lastFrame) + curFrame) / 1000000.0; } else { dt = (curFrame - lastFrame) / 1000000.0; } if(dt > 0.05) { dt = 0.05; // Clamp dt so objects don't have collision issues } lastFrame = curFrame; // =================== // Update if(nextlevel != "") { printf("Switching to level %s\n", nextlevel.c_str()); generateLevel(nextlevel); nextlevel = ""; } TimerRun(); for(int enti=0; enti<entsC; enti++) { if(ents[enti] == NULL) continue; ents[enti]->Update(dt); if(ents[enti]->isKilled) delete ents[enti]; } // ==================== // Drawing for(int rli=0; rli<RL_MAX; rli++) { if(rli == RL_BACKGROUND) { drawBackground(renderer, dt); continue; // Done in drawBackground } Drawable** layer = renderLayers[rli]; for(int enti=0; enti<renderLayersC[rli]; enti++) { if(layer[enti] == NULL) continue; layer[enti]->Draw(dt); } } // Flip render buffer SDL_RenderPresent(renderer); // Frame limiting, not needed if we're using vsync //SDL_Delay((1000 / 66) - (curtime_u() - lastFrame)/1000); } printf("\nShutting down...\n"); cleanLevel(); // Destroy old textures for(std::map<std::string, TextureData>::iterator it = blockTDs.begin(); it != blockTDs.end(); ++it) { SDL_DestroyTexture(it->second.texture); } blockTDs.clear(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); Mix_CloseAudio(); Mix_Quit(); IMG_Quit(); SDL_Quit(); return 0; }
void Game::startGame(bool isStartingGame) { gfx.pal.clear(); if(isStartingGame) { if(settings.regenerateLevel || settings.randomLevel != oldRandomLevel || settings.levelFile != oldLevelFile) { generateLevel(); } initGame(); for(std::size_t i = 0; i < viewports.size(); ++i) { viewports[i]->x = 0; viewports[i]->y = 0; } selectWeapons(); sfx.play(22, 22); cycles = 0; for(int w = 0; w < 40; ++w) { weapons[w].computedLoadingTime = (settings.loadingTime * weapons[w].loadingTime) / 100; if(weapons[w].computedLoadingTime == 0) weapons[w].computedLoadingTime = 1; } } int fadeAmount = isStartingGame ? 180 : 0; bool shutDown = false; do { ++cycles; if(!H[HBonusDisable] && settings.maxBonuses > 0 && rand(C[BonusDropChance]) == 0) { createBonus(); } for(std::size_t i = 0; i < worms.size(); ++i) { worms[i]->process(); } for(std::size_t i = 0; i < worms.size(); ++i) { worms[i]->ninjarope.process(*worms[i]); } switch(game.settings.gameMode) { case Settings::GMGameOfTag: { bool someInvisible = false; for(std::size_t i = 0; i < worms.size(); ++i) { if(!worms[i]->visible) { someInvisible = true; break; } } if(!someInvisible && lastKilled && (cycles % 70) == 0 && lastKilled->timer < settings.timeToLose) { ++lastKilled->timer; } } break; } processViewports(); drawViewports(); for(BonusList::iterator i = bonuses.begin(); i != bonuses.end(); ++i) { i->process(); } if((cycles & 1) == 0) { for(std::size_t i = 0; i < viewports.size(); ++i) { Viewport& v = *viewports[i]; bool down = false; if(v.worm->killedTimer > 16) down = true; if(down) { if(v.bannerY < 2) ++v.bannerY; } else { if(v.bannerY > -8) --v.bannerY; } } } for(SObjectList::iterator i = game.sobjects.begin(); i != game.sobjects.end(); ++i) { i->process(); } // TODO: Check processing order of bonuses, wobjects etc. for(WObjectList::iterator i = wobjects.begin(); i != wobjects.end(); ++i) { i->process(); } for(NObjectList::iterator i = nobjects.begin(); i != nobjects.end(); ++i) { i->process(); } for(BObjectList::iterator i = bobjects.begin(); i != bobjects.end(); ++i) { i->process(); } if((cycles & 3) == 0) { for(int w = 0; w < 4; ++w) { gfx.origpal.rotate(gfx.colourAnim[w].from, gfx.colourAnim[w].to); } } gfx.pal = gfx.origpal; if(fadeAmount <= 32) gfx.pal.fade(fadeAmount); if(gfx.screenFlash > 0) { gfx.pal.lightUp(gfx.screenFlash); } gfx.flip(); gfx.process(); if(gfx.screenFlash > 0) --gfx.screenFlash; if(isGameOver()) { gfx.firstMenuItem = 1; shutDown = true; } for(std::size_t i = 0; i < viewports.size(); ++i) { if(viewports[i]->shake > 0) viewports[i]->shake -= 4000; // TODO: Read 4000 from exe? } if(gfx.testSDLKeyOnce(SDLK_ESCAPE) && !shutDown) { gfx.firstMenuItem = 0; fadeAmount = 31; shutDown = true; } if(shutDown) { fadeAmount -= 1; } else if(!isStartingGame) { if(fadeAmount < 33) { fadeAmount += 1; if(fadeAmount >= 33) fadeAmount = 180; } } } while(fadeAmount > 0); gfx.clearKeys(); }
void DungeonGenerator::generateLevel(int floorIndex, Dungeon* dungeon, int width, int height, std::default_random_engine engine, int startRoomX, int startRoomY) { RoomDescriptionGenerator roomDescriptionGenerator; for (auto x = 0; x < width; x++) { for (auto y = 0; y < height; y++) { dungeon->setRoom(new Room(floorIndex, x, y, roomDescriptionGenerator.getRandomDescription()), x, y, floorIndex); } } for (auto x = 0; x < width; x++) { for (auto y = 0; y < height; y++) { resetPossibleRandomDirections(); if (x == 0) { removeFromPossibleRandomDirections(Direction::WEST); } else if (x == (width - 1)) { removeFromPossibleRandomDirections(Direction::EAST); } if (y == 0) { removeFromPossibleRandomDirections(Direction::NORTH); } else if (y == (height - 1)) { removeFromPossibleRandomDirections(Direction::SOUTH); } std::uniform_int_distribution<int> amountOfRoomsDistibution {1, static_cast<int>(possibleRandomDirections_ ->size())}; Direction roomDirection; auto amountOfConnectedRooms = amountOfRoomsDistibution(engine); if (dungeon->getRoom(x, y, floorIndex)->getRoom(Direction::NORTH) != nullptr) { amountOfConnectedRooms--; } if (dungeon->getRoom(x, y, floorIndex)->getRoom(Direction::EAST) != nullptr) { amountOfConnectedRooms--; } if (dungeon->getRoom(x, y, floorIndex)->getRoom(Direction::SOUTH) != nullptr) { amountOfConnectedRooms--; } if (dungeon->getRoom(x, y, floorIndex)->getRoom(Direction::WEST) != nullptr) { amountOfConnectedRooms--; } for (auto i = 0; i < amountOfConnectedRooms; i++) { do { roomDirection = possibleRandomDirections_->at(amountOfRoomsDistibution(engine) - 1); } while (dungeon->getRoom(x, y, floorIndex)->getRoom(roomDirection) != nullptr); dungeon->createDirection(x, y, floorIndex, roomDirection); } } } std::uniform_int_distribution<int> xDistribution { 0, (width - 1) }; std::uniform_int_distribution<int> yDistribution { 0, (height - 1) }; auto finishRoomX = xDistribution(engine); auto finishRoomY = yDistribution(engine); if (floorIndex <= 0) { dungeon->setStartRoom(dungeon->getRoom(finishRoomX, finishRoomY, floorIndex)); } if (floorIndex > 0) { while (startRoomX == finishRoomX && startRoomY == finishRoomY) { finishRoomX = xDistribution(engine); finishRoomY = yDistribution(engine); } dungeon->getRoom(finishRoomX, finishRoomY, floorIndex - 1)->setRoom(Direction::DOWN, dungeon->getRoom(finishRoomX, finishRoomY, floorIndex)); dungeon->getRoom(finishRoomX, finishRoomY, floorIndex)->setRoom(Direction::UP, dungeon->getRoom(finishRoomX, finishRoomY, floorIndex - 1)); } if (floorIndex < (MAX_DUNGEON_LEVEL - 1)) { int nPokemon = static_cast<int>((dungeon->getWidth() * dungeon->getHeight()) * POKEMON_PER_ROOM); Pokemon* pokemon = nullptr; for (auto counter = 0; counter < nPokemon; ++counter) { pokemon = pokemonGenerator_->getRandomPokemon(); if (pokemon != nullptr) { pokemon->levelUpTo(floorIndex + 1); pokemon->setCurrentRoom(dungeon->getRoom(xDistribution(engine), yDistribution(engine), floorIndex)); } } auto nItems =static_cast<int>((dungeon->getWidth() * dungeon->getHeight()) * ITEMS_PER_ROOM); for (auto counter = 0; counter < nItems; ++counter) { dungeon->getRoom(xDistribution(engine), yDistribution(engine), floorIndex)->addItem(itemGenerator_->getRandomItem()); } auto nTraps = static_cast<int>((dungeon->getWidth() * dungeon->getHeight()) * TRAPS_PER_ROOM); Room* trapRoom; std::map<Direction, Trap*>* traps = nullptr; std::map<Direction, Room*> rooms; std::vector<Direction> directions; Direction randomDirection; bool setTrap; for (auto counter = 0; counter < nTraps; ++counter) { setTrap = false; do { trapRoom = dungeon->getRoom(xDistribution(engine), yDistribution(engine), floorIndex); traps = trapRoom->getTraps(); rooms = trapRoom->getAccessableRooms(); if (traps->size() < rooms.size()) { directions.clear(); for (auto i : rooms) { directions.push_back(i.first); } do { std::random_shuffle(directions.begin(), directions.end()); randomDirection = directions.at(0); } while (traps->count(randomDirection) > 0); trapRoom->setTrap(randomDirection, trapGenerator_->getRandomTrap()); setTrap = true; } } while (!setTrap); } generateLevel(++floorIndex, dungeon, width, height, engine, finishRoomX, finishRoomY); } else { auto mewXLoc = xDistribution(engine); auto mewYLoc = yDistribution(engine); int mewtwoXLoc; int mewtwoYLoc; do { mewtwoXLoc = xDistribution(engine); mewtwoYLoc = yDistribution(engine); } while (mewXLoc == mewtwoXLoc && mewYLoc == mewtwoYLoc); auto boss1 = pokemonGenerator_->getBoss(0); auto boss2 = pokemonGenerator_->getBoss(1); boss1->levelUpTo(BOSS_LEVEL); boss2->levelUpTo(BOSS_LEVEL); dungeon->getRoom(mewtwoXLoc, mewtwoYLoc, floorIndex)->setBoss(boss1); boss1->setCurrentRoom(dungeon->getRoom(mewtwoXLoc, mewtwoYLoc, floorIndex)); dungeon->getRoom(mewXLoc, mewYLoc, floorIndex)->setBoss(boss2); boss2->setCurrentRoom(dungeon->getRoom(mewXLoc, mewYLoc, floorIndex)); } }