TEST(ProcreationTests, SimpleProcreationTest) { bug_list.clear(); for (int i = 0; i < 10; i++) { // The provided code has "if (...health > REPRODUCE_HEALTH) instead of >= bug_list.push_back(initBug(i, i, rand() % 8, REPRODUCE_HEALTH + 2, i, i + 10)); } initWorld(); reproduceBugs(); ASSERT_EQ(bug_list.size(), 20); for (int i = 10; i < bug_list.size(); i++) { auto &bug = bug_list[i]; ASSERT_EQ(bug.x, i - 10); ASSERT_EQ(bug.y, i - 10); ASSERT_EQ(bug.dir, bug_list[i - 10].dir); ASSERT_EQ(bug.health, REPRODUCE_HEALTH / 2 + 1); ASSERT_EQ(bug.generation, i - 9); ASSERT_EQ(bug.age, 0); } }
void Simulator::init(Project &prj, BodyFactory &factory){ initWorld(prj, factory, *this, pairs); initRTS(prj, receivers); std::cout << "number of receivers:" << receivers.size() << std::endl; m_totalTime = prj.totalTime(); m_logTimeStep = prj.logTimeStep(); m_kinematicsOnly = prj.kinematicsOnly(); OpenHRP::CollisionSequence& collisions = state.collisions; collisions.length(pairs.size()); for(size_t colIndex=0; colIndex < pairs.size(); ++colIndex){ hrp::ColdetLinkPairPtr linkPair = pairs[colIndex]; hrp::Link *link0 = linkPair->link(0); hrp::Link *link1 = linkPair->link(1); OpenHRP::LinkPair& pair = collisions[colIndex].pair; pair.charName1 = CORBA::string_dup(link0->body->name().c_str()); pair.charName2 = CORBA::string_dup(link1->body->name().c_str()); pair.linkName1 = CORBA::string_dup(link0->name.c_str()); pair.linkName2 = CORBA::string_dup(link1->name.c_str()); } m_nextLogTime = 0; appendLog(); }
void TestColliderDetector::onEnter() { CCLayer::onEnter(); scheduleUpdate(); //! load data CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo("Cowboy.ExportJson"); //! create armature armature = cocos2d::extension::CCArmature::create("Cowboy"); armature->getAnimation()->play("FireWithoutBullet"); armature->getAnimation()->setSpeedScale(0.2f); armature->setScaleX(-0.2f); armature->setScaleY(0.2f); armature->setPosition(ccp(CCDirector::sharedDirector()->getVisibleSize().width * 0.2, CCDirector::sharedDirector()->getVisibleSize().height * 0.5)); //! bind armature's frame event to onFrameEvent armature->getAnimation()->setFrameEventCallFunc(this, frameEvent_selector(TestColliderDetector::onFrameEvent)); addChild(armature); //! create armature2 armature2 = cocos2d::extension::CCArmature::create("Cowboy"); armature2->getAnimation()->play("Walk"); armature2->setScaleX(-0.2f); armature2->setScaleY(0.2f); armature2->setPosition(ccp(CCDirector::sharedDirector()->getVisibleSize().width * 0.8, CCDirector::sharedDirector()->getVisibleSize().height * 0.5)); addChild(armature2); //! add a CCPhysicsSprite,will show in FrameEvent bullet = CCPhysicsSprite::createWithSpriteFrameName("25.png"); addChild(bullet); initWorld(); }
void init(void) { mode = MOVECAM; object = TORUS; sphere_radius = INITRAD; /* Initial camera location and orientation */ eye_pos0 = XVec4f(2.0, 3.0, 6.0, 1.0); gaze_dir0 = XVec4f(-2.0, -3.0, -6.1, 0.0); // c = (0,0,0); g = c - e top_dir0 = XVec4f(0.0, 1.0, 0.0, 0.0); zNear0 = -0.1; zFar0 = -25.0; fovy0 = 27.0; cam = Camera(eye_pos0, gaze_dir0, top_dir0, zNear0, zFar0, fovy0); glClearColor(0.0, 0.0, 0.0, 1.0); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glGetDoublev(GL_TEXTURE_MATRIX, cmodview); init_properties(); /* YOUR CODE HERE . . . * Initialize your lights: some needs to be positioned * before viewing transform, others after. */ //initialize eye light //glLightfv(lightname,param,value) glLightfv(EYELIGHT, GL_SPOT_DIRECTION, eyelight_position); glLightfv(EYELIGHT, GL_POSITION, eyelight_position); setup_view(); // in viewing.cpp glLightfv(SUNLIGHT, GL_POSITION, sunlight_position); glLightfv(OBJLIGHT, GL_POSITION, objlight_position); /* . . . AND/OR HERE */ //initialize sun light glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* YOUR CODE HERE - enable various other pieces of OpenGL state * 1. Depth test, so that OpenGL has a sense of depth (Cf. glEnable()) * 2. Automatic normalization of normals (Cf. glEnable()) * 3. Back face culling (Cf. glEnable()) * 4. Smooth shading of polygons (Cf. glShadeModel()) * 5. Filled rendering of polygons (Cf. glPolygonMode()) */ glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glEnable(GL_CULL_FACE); glShadeModel(GL_SMOOTH); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor4f(0.0, 0.0, 1.0, 0.4); initWorld(); // TODO in objects.cpp return; }
void CMazeGameEngine::startNextLevel() { //TODO: increase level difficulty _isNextLevelRequested = false; auto mazeDimensions = menu.getChosenMazeDimensions(); initWorld(mazeDimensions.first, mazeDimensions.second, menu.getChosenNumOfAIPlayers(), menu.getChosenAIDifficultyLevel()); setupWorld(); }
/******************************************************************************* * 関数定義 ******************************************************************************/ int main(int argc, char *argv[]) { struct World world; int result; initWorld(&world); // 世界の初期化(パーツ・コマンドリスト生成など) setPlayer(&world); // プレイヤの受付とモンスターの生成 do(judgment(&world, &result) != GAMEOVER) { // 終了判定 setCommand(&world); // 各プレイヤからコマンドを受け付ける runAttack(&world); // コマンドの実行 }
/* Makes sure bugs eat the food they move on top of */ TEST(MovementTests, EatingTest) { bug_list.clear(); bug_list.push_back(initBug(0, 0, 2)); initWorld(); world[0][1] = FOOD; moveBugs(); ASSERT_EQ(world[0][1], 0); ASSERT_EQ(bug_list.size(), 1); ASSERT_EQ(bug_list[0].health, START_HEALTH + EAT_HEALTH - MOVE_HEALTH); }
TEST(BugKillingTests, SimpleBugKillingTest) { bug_list.clear(); bug_list.push_back(initBug(0, 0, 2, MOVE_HEALTH)); bug_list.push_back(initBug(0, 0, 4, MOVE_HEALTH * 2)); initWorld(); moveBugs(); killDeadBugs(); ASSERT_EQ(bug_list.size(), 1); ASSERT_EQ(world[0][0], EMPTY); ASSERT_EQ(world[0][1], EMPTY); ASSERT_EQ(world[1][0], 0); }
TEST(BugKillingTests, NoSkipBugKillingTest) { bug_list.clear(); bug_list.push_back(initBug(0, 0, NORTH, MOVE_HEALTH)); bug_list.push_back(initBug(0, 0, SOUTH, MOVE_HEALTH)); bug_list.push_back(initBug(0, 0, WEST, MOVE_HEALTH * 2)); initWorld(); moveBugs(); killDeadBugs(); ASSERT_EQ(bug_list.size(), 1); ASSERT_EQ(world[0][0], EMPTY); ASSERT_EQ(world[WORLD_SIZE-1][0], EMPTY); ASSERT_EQ(world[1][0], EMPTY); ASSERT_EQ(world[0][WORLD_SIZE-1], 0); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } this->screenSize = CCDirector::sharedDirector()->getVisibleSize(); this->down_bar = NULL; score = 0; this->Xdownbar = 0; this->Xbird = 0; barTag = 0; //加载PLIST this->cache = CCSpriteFrameCache::sharedSpriteFrameCache(); this->cache->addSpriteFramesWithFile("flappy_packer.plist","flappy_packer.png"); CCSprite *startgame = CCSprite::createWithSpriteFrameName("getready.png"); startgame->setPosition(ccp(this->screenSize.width/2,this->screenSize.height/2+300)); addChild(startgame,1); //CCMenuItemImage *startgameItemImage = CCMenuItemImage::create("start.png","start.png",this,menu_selector(HelloWorld::gameEndCallback)); CCMenuItemSprite *startgameItemImage = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("start.png"), CCSprite::createWithSpriteFrameName("start.png"),this,menu_selector(HelloWorld::gameEndCallback)); CCMenu* menu = CCMenu::create(startgameItemImage,NULL); addChild(menu,1); CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect("mp3/fly.mp3"); CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect("mp3/dead.wav"); CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect("mp3/score.mp3"); initWorld(); addBg(); addGround(123); addBrid(); gameend = false; ispass = false; //scheduleOnce(schedule_selector(HelloWorld::startGame),1); return true; }
TEST(BugKillingTests, RemoveLastBugIfDead) { bug_list.clear(); bug_list.push_back(initBug(0, 0, EAST, 0)); bug_list.push_back(initBug(0, 1, EAST, MOVE_HEALTH * 3)); bug_list.push_back(initBug(0, 2, EAST, MOVE_HEALTH * 3)); bug_list.push_back(initBug(0, 3, EAST, 0)); initWorld(); moveBugs(); killDeadBugs(); ASSERT_EQ(bug_list.size(), 2); ASSERT_EQ(world[0][1], EMPTY); ASSERT_GE(world[0][2], 0); ASSERT_GE(world[0][3], 0); ASSERT_EQ(world[0][4], EMPTY); }
World::World(): gen(rd()), dis(0, 1), chanceStartAlive(0.4f), birthLimit(4), deathLimit(3), steps(3) { Debug::print("Chances", chanceStartAlive); Debug::print("Birth limit", birthLimit); Debug::print("Death limit", deathLimit); initWorld(); for (int i = 1; i <= steps; ++i) { doSimulationStep(); Debug::print("Generation step", i); } }
void runGame() { hideCursor(); initWorld(); unsigned long curtime = ccTimeMilliseconds(); double acctime = 0.0; while(true){ ccEvent event = updateWindow(); if(event.type == CC_EVENT_WINDOW_QUIT){ break; }else if(event.type == CC_EVENT_KEY_DOWN){ handleKeyDownWorld(event.keyCode); }else if(event.type == CC_EVENT_KEY_UP){ handleKeyUpWorld(event.keyCode); } unsigned long newtime = ccTimeMilliseconds(); double frametime = (newtime - curtime) * 0.001; curtime = newtime; if(frametime > FRAME_CAP){ frametime = FRAME_CAP; } acctime += frametime; bool redraw = false; while(acctime >= FRAME_DELTA){ acctime -= FRAME_DELTA; redraw = updateWorld(); } if(redraw){ renderWorld(2, 1, getWidth() - getGuiWidth() - 3, getHeight() - 8); renderGui(getWidth() - getGuiWidth(), 0); } renderWindow(2); } }
void HelloWorld::startGame( float dt) { delete this->world; this->score = 0; this->down_bar = NULL; this->Xdownbar = 0; this->Xbird = 0; barTag = 0; barArray[0]=false; barArray[1]=false; isTouch = false; gameend = false; removeAllChildren(); setTouchEnabled(true); initWorld(); CCLabelAtlas* label2 = CCLabelAtlas::create("0123456789", "1.png", 17, 22, '0'); addChild(label2, 1, 9); label2->setPosition(ccp(this->screenSize.width/2-30,this->screenSize.height/2+360)); //label2->setColor(ccWHITE); label2->setScale(4); char string[12] = {0}; sprintf(string,"%d",this->score); label2->setString(string); scheduleUpdate(); schedule(schedule_selector(HelloWorld::addBar),1); //scheduleOnce(schedule_selector(HelloWorld::addBar),1); addBg(); addGround(123); addBrid(); addBarContainer(); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } screenSize = CCDirector::sharedDirector()->getVisibleSize(); initWorld(); addBarContainer(); addBird(); addGround(); setTouchEnabled(true); startGame(); return true; }
// Initialisation void init(void) { // GL modes glEnable(GL_DEPTH_TEST); // Couleur d'arrière plan en gris foncé glClearColor(0, 0, 0, 0); // Mode d'observation glMatrixMode(GL_MODELVIEW); // Matrice identitée glLoadIdentity(); // Placement de l'observateur (camera) gluLookAt(obsX, obsY, obsZ, tarX, tarY, tarZ, repX, repY, repZ); // Init World initWorld(); }
/* Makes sure bugs move properly in all directions */ TEST(MovementTests, SimpleMovementTest) { bug_list.clear(); for (int i = 0; i < 8; i++) { Bug b = initBug(0, 0, i); bug_list.push_back(b); } initWorld(); moveBugs(); ASSERT_EQ(bug_list.size(), 8); ASSERT_EQ(world[0][0], EMPTY); int i = 0; for (auto &bug : bug_list) { ASSERT_EQ(bug.x, newX(0, i)); ASSERT_EQ(bug.y, newY(0, i)); ASSERT_EQ(world[bug.x][bug.y], i++); } }
void initialize (int argc, char **argv) { //Initialize model initPlayer(); initWorld(); //Initialize GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(300,300); //Create a window with rendering context and everything else we need glutCreateWindow("Intro"); glClearColor(0.0,0.0,0.0,0.0); //Assign the two used Msg-routines glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyPress); //Let GLUT get the msgs glutMainLoop(); }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } //////////////////////////////////////////////////// // 下面添加创建自己的Sprite的代码 //////////////////////////////////////////////////// mScreenSize = CCDirector::sharedDirector()->getVisibleSize(); initWorld(); addBird(); addBarContainer(); setTouchEnabled(true); scheduleOnce(schedule_selector(HelloWorld::startGame), 3); return true; }
/* Makes sure bugs update their direction properly for all directions */ TEST(MovementTests, SimpleDirectionTest) { bug_list.clear(); for (int i = 0; i < 8; i++) { Bug b = initBug(0, 0, 0); memset(b.genes, 0, ARRAYSIZE(b.genes)); b.genes[i] = GENE_TOTAL; bug_list.push_back(b); } initWorld(); moveBugs(); ASSERT_EQ(bug_list.size(), 8); // Each bug's direction should now be i int i = 0; for (auto &bug : bug_list) { ASSERT_EQ(bug.dir, i++); } }
/** * Author: Joel Denke, Marcus Isaksson * Description: Run the game on client */ int main(int argc, char *argv[]) { int i, j, no, yb, keysHeld[323] = {0}; int result = 0; SDL_Thread * eventBuffer; SDL_Thread * runBuffer; struct timer_t2 fps; char * server_ip = malloc(sizeof(char) * 16); char * elem = malloc(sizeof(char) * MESSAGE_SIZE); pColor = malloc(sizeof(SDL_Color)); oColor = malloc(sizeof(SDL_Color)); connection = malloc(sizeof(connection_data)); for (i = 0; i < NO_BUFFERS; i++) { cb[i] = malloc(sizeof(cBuffer)); b_lock[i] = SDL_CreateMutex(); } strcpy(server_ip, "127.0.0.1"); pColor->r = 0; pColor->g = 255; pColor->b = 255; oColor->r = 0; oColor->g = 0; oColor->b = 255; initGraphics(); initSound(); printf("Render menu\n"); graphicsMenu(&gameWorld, server_ip); initSlots(cb[0], BUFFER_SIZE); initSlots(cb[1], NO_OBJECTS); initSlots(cb[2], BUFFER_SIZE); state = gStart; if (clientConnect(connection, server_ip) == 0) { eventBuffer = SDL_CreateThread(listenEventBuffer, &connection); while (1) { switch (state) { case gStart: runData(2); break; case gInit: timer_start(&fps); startDraw(); drawLoadScr(SCREEN_WIDTH, SCREEN_HEIGHT); endDraw(); initWorld(); if (timer_get_ticks(&fps) < 1000 / FPS) { //delay the as much time as we need to get desired frames per second SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) ); } break; case gRunning : timer_start(&fps); drawGraphics(); listenInput(keysHeld); // i = 0: players; i = 1: objects; i = 2: messages for (i = 0; i < NO_BUFFERS; i++) { runData(i); } if (timer_get_ticks(&fps) < 1000 / FPS) { //delay the as much time as we need to get desired frames per second SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) ); } break; case gExit : //sprintf(string, "%d,quit", connection->client_id); printf("Freeing music now\n"); pauseMusic(); freeMusic(); end_session(connection); printf("Player is exit game now\n"); exitClient(eventBuffer); break; default : printf("test\n"); break; } } } else { printf("Misslyckade med att kontakta servern på ip-adress: '%s'\n", server_ip); state = gExit; pauseMusic(); freeMusic(); exitClient(eventBuffer); } return 0; }
int main(int argc, char **argv) { int i, j; int x, y, size; int w_breeding, s_breeding, w_starvation, gen_num; char type_code; FILE * input_file; w_number = 0; if(argc <= 5) { printf("ERROR: Expected 5 arguments provided %d.\n", argc); printf("Expected:\n./wolves-squirrels-serial <InputFile> <WolfBreedingPeriod> <SquirrelBreedingPeriod> <WolfStarvationPerior> <Generations>\n"); return -1; } w_breeding = atoi(argv[2]); s_breeding = atoi(argv[3]); w_starvation = atoi(argv[4]); gen_num = atoi(argv[5]); input_file = fopen(argv[1], "r"); if(input_file == NULL) { printf("ERROR: A valid input file is expected. %s is not a valid file.\n", argv[1]); return -1; } fscanf(input_file, "%d", &size); initWorld(size); while(fscanf(input_file, "%d %d %c", &x, &y, &type_code) != EOF) { world[0][x][y].type = type_code; world[1][x][y].type = type_code; if(world[0][x][y].type == wolf) { world[0][x][y].breeding_period = w_breeding; world[0][x][y].starvation_period = w_starvation; } else if(world[0][x][y].type == squirrel || world[0][x][y].type == squirrel_on_tree) { world[0][x][y].breeding_period = s_breeding; } } fclose(input_file); #ifdef VERBOSE printf("INITIAL WORLD - w_number = %d\n", w_number); printWorldDetailed(size); printf("\n"); #endif /* Generate */ while(gen_num != 0) { cleanWorld(size); /* 1st sub-generation - RED */ for(i=0; i<size; i++) { for(j = i%2 == 0 ? 0 : 1 ; j<size; j+=2) { computeCell(i, j, s_breeding, w_breeding, w_starvation, size); } } /* 2nd sub-generation */ for(i=0; i<size; i++) { for(j = i%2 == 0 ? 1 : 0 ; j<size; j+=2) { computeCell(i, j, s_breeding, w_breeding, w_starvation, size); } } #ifdef VERBOSE printf("\n\nIteration %d:\n", gen_num); printWorldDetailed(size); printf("\n"); #endif gen_num--; w_number = (w_number+1) % 2; } /* Output */ printWorldFormatted(size); return 0; }
int main(int argc, char* argv[]) { int width = 1024, height = 768; if(argc == 5 && strcmp(argv[2], "-r") == 0 ){ width = atoi(argv[3]); height = atoi(argv[4]); } else if(argc == 4 && strcmp(argv[1], "-r") == 0 ){ width = atoi(argv[2]); height = atoi(argv[3]); } /*Initialisation SDL, OpenGL etc */ if( initWindow(width, height) == EXIT_FAILURE){ perror("Impossible d'initialiser la fenêtre SDL, le programme va fermer.\n"); exit(-1); } /* initialisation de SDL_TTF*/ if(TTF_Init()== -1){ printf("Error loading TTF: %s\n",TTF_GetError()); exit(1); } bool askedForQuit = false; World world; world.towersList = NULL; world.map.name = NULL; world.map.tabXYConstruct = NULL; world.map.image = NULL; world.map.pathNodeList = NULL; Interface interface; interface.lstButtons = NULL; char* mapName= NULL; BUTTON_OF_MENU.lstMapName = NULL; BUTTON_OF_MENU.lstMapButton = NULL; BUTTON_OF_MENU.lstMapTextureIndex = NULL; bool play = false; List* lstMaps = createEmptyList(); readDirectory(lstMaps); /* selection d'une carte en ligne de commande*/ if (argc >= 2 && strcmp(argv[1], "-r") != 0){ char* curMap = NULL; while( (curMap = (char*) nextData(lstMaps)) != NULL){ if (strcmp(argv[1],curMap)==0){ mapName = (char*) malloc(strlen(argv[1])*sizeof(char)); if(mapName == NULL){ fprintf(stderr, "Erreur fatale : impossible d'allouer la mémoire nécessaire.\n"); exit(EXIT_FAILURE); } strcpy(mapName,argv[1]); play = true; break; } } if(! play) fprintf(stderr, "Erreur le nom donné en paramètre ne correspond à aucun fichier map\n"); } freeListComplete(lstMaps); /*-------------- GESTION DU MENU --------------------*/ do{ interface.lstButtons = NULL; /* chargement des polices */ int playIsPush = 0; int menuOpen = 0; int aideOpen = 0; initMenuGraphics(); /* ouverture du répertoire data */ while(!play && askedForQuit == false) { /* Récupération du temps au début de la boucle */ Uint32 startTime = SDL_GetTicks(); /* Placer ici le code de dessin du menu */ drawMenu(&menuOpen,&aideOpen,&playIsPush,mapName); /* Echange du front et du back buffer : mise à jour de la fenêtre */ SDL_GL_SwapBuffers(); /* Renvoie une chaine de caractère contenant le nom du fichier ITD choisi par l'utilisateur ou NULL si rien n'a encore été choisi */ askedForQuit = handleMenuActions(&mapName,&playIsPush, &menuOpen,&aideOpen); if(playIsPush == 2) play = true; /* Calcul du temps écoulé */ Uint32 elapsedTime = SDL_GetTicks() - startTime; /* Si trop peu de temps s'est écoulé, on met en pause le programme */ if(elapsedTime < FRAMERATE_MILLISECONDS) { SDL_Delay(FRAMERATE_MILLISECONDS - elapsedTime); } } /*-------------- GESTION DU JEU --------------------*/ bool gameFinished = false; //Surtout à appeler APRES avoir initialisé la SDL char mapPath[50] = "data/"; float width = .15;//10% de largeur float height = 1.; //Toute la hauteur float positionX = 0.85; //A 90% de la largeur float positionY = .0; //A 100% de la hauter if(!askedForQuit){ strcat(mapPath, mapName); world = initWorld(mapPath); initGameGraphics(); GAME_TEXTURES_ID.MAP_ID = makeTextureFromSurface(world.map.image); //Initialisation interface interface = initGameInterface(width, height, positionX, positionY); startWorld(&world); } while(!gameFinished && !askedForQuit) { /* Récupération du temps au début de la boucle */ Uint32 startTime = SDL_GetTicks(); /* On tente un nouveau cycle de tours de jeu si besoin. Le temps est géré par la fonction. La plupart du temps plusieurs tours de jeu sont joués d'affilé. */ worldNewStep(&world); drawWorld(&world); drawInterface(&interface, &world); /* Calcul du temps écoulé, si temps < 10 ms, on ne passe pas au tour suivant. */ Uint32 elapsedTime = SDL_GetTicks() - startTime; /* Si trop peu de temps s'est écoulé, on ne dessine rien. */ if(elapsedTime < FRAMERATE_MILLISECONDS) { /* Echange du front et du back buffer : mise à jour de la fenêtre */ SDL_GL_SwapBuffers(); SDL_Delay(FRAMERATE_MILLISECONDS - elapsedTime); } /* Boucle traitant les evenements */ askedForQuit = handleGameActions(&world, &interface, &gameFinished); } play = false; mapName = NULL; cleanWorld(&world); cleanInterface(&interface); }while(! askedForQuit); /* Liberation des ressources */ cleanExit(&world, &interface); return EXIT_SUCCESS; }
void Core::run() { initApp(640,480); initWorld("map/bbb.map"); initView(); while(_app->isOpen()){ _frameTime = _clockFrame.restart().asSeconds(); sf::Event Event; while (_app->pollEvent(Event)){ if (Event.type == sf::Event::Closed) _app->close(); //if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::A)){ //} if(Event.type == sf::Event::KeyReleased && Event.key.code == sf::Keyboard::Escape){ _app->close(); } } /* if(lagrefresh.GetElapsedTime() > 0.5){ sprintf(txt, "%f", 1.f / _app->GetFrameTime()); texte.SetText(txt); lagrefresh.Reset(); } */ _app->setView(*(g_core->getView())); _app->clear(); // UPDATEWORLD() if(_menu->getEtat() != CRAFTER_OFF) _menu->update(); _world->update(); // RENDERWORLD() _world->render(); // DISOLVE() _world->disolve(); // *** VIEW : DEFAULT *** _app->setView(_app->getDefaultView()); // Display Menu if(_menu->getEtat() != CRAFTER_OFF) _menu->render(); // DISPLAY FPS sf::Text fpsMessage; int FPS; ostringstream oss; FPS = 1 / _frameTime; oss << "FPS : " << FPS; fpsMessage.setPosition(50.0f, 100.0f); fpsMessage.setColor(sf::Color(255,0,0,255)); fpsMessage.setString(oss.str()); fpsMessage.setCharacterSize(14); _app->draw(fpsMessage); // DISPLAY COMPLETE BUFFER _app->display(); } }
int main(int argc, char **argv) { int i, j, z; int x, y, size; int w_breeding, s_breeding, w_starvation, gen_num; char type_code; char *file_name; FILE * input_file; double secs; int averow, extra, rank, n_processes, offset, rows; int mtype, dest, rowsAux, source; int aditional, start_line; struct world **proc_world; MPI_Init (&argc, &argv); MPI_Comm_rank (MPI_COMM_WORLD, &rank); //Rank, an integer, is used in MPI to be a process identifier associated with a communicator MPI_Comm_size (MPI_COMM_WORLD, &n_processes); //where size is the total number of processes in the MPI_Comm_world. /* Processo Master */ if (rank == MASTER) { secs = MPI_Wtime(); if(argc <= 5) { printf("ERROR: Expected 5 arguments provided %d.\n", argc); printf("Expected:\n./wolves-squirrels-serial <InputFile> <WolfBreedingPeriod> <SquirrelBreedingPeriod> <WolfStarvationPerior> <Generations>\n"); return -1; } w_breeding = atoi(argv[2]); s_breeding = atoi(argv[3]); w_starvation = atoi(argv[4]); gen_num = atoi(argv[5]); input_file = fopen(argv[1], "r"); if(input_file == NULL) { printf("ERROR: A valid input file is expected. %s is not a valid file.\n", argv[1]); return -1; } /* Talvez dê para melhorar */ fscanf(input_file, "%d", &size); initWorld(size); while(fscanf(input_file, "%d %d %c", &x, &y, &type_code) != EOF) { world_global[x][y].type = type_code; if(world_global[x][y].type == wolf) { world_global[x][y].breeding_period = w_breeding; world_global[x][y].starvation_period = w_starvation; } else if(world_global[x][y].type == squirrel) { world_global[x][y].breeding_period = s_breeding; } } fclose(input_file); /* Envia parcela a cada processo */ averow = size / n_processes; extra = size % n_processes; offset = 0; mtype = FROM_MASTER; for(dest=1; dest<n_processes; dest++) { rowsAux = dest <= extra ? averow+1 : averow; MPI_Send(&offset, 1, MPI_INT, dest, mtype, MPI_COMM_WORLD); MPI_Send(&rowsAux, 1, MPI_INT, dest, mtype, MPI_COMM_WORLD); MPI_Send(&size, 1, MPI_INT, dest, mtype, MPI_COMM_WORLD); for(i=0; i < rowsAux; i++) MPI_Send(world_global[offset+i], sizeof(struct world)*size, MPI_BYTE, dest, mtype, MPI_COMM_WORLD); offset = offset + rowsAux; } proc_world = (struct world**) malloc(sizeof(struct world*)*(averow+1)); for(i = 0; i < averow+1; i++) { proc_world[i] = (struct world*) malloc(sizeof(struct world)*size); for(j = 0; j < size; j ++) { proc_world[i][j].type = empty; proc_world[i][j].count = 0; proc_world[i][j].breeding_period = 0; proc_world[i][j].starvation_period = 0; proc_world[i][j].breed = 0; for(z=0; z < 5; z++) world_global[i][j].conflicts[z]=NULL; } } for(i=1; i< averow+1; i++) proc_world[i] = world_global[offset+i]; #ifdef MPIVERBOSE printf("Distribuição: %lf\n", MPI_Wtime() - secs); secs = MPI_Wtime(); #endif aditional = 1; } else if(rank > 0) { mtype = FROM_MASTER; source = MASTER; MPI_Recv(&offset, 1, MPI_INT, source, mtype, MPI_COMM_WORLD, &status); MPI_Recv(&rowsAux, 1, MPI_INT, source, mtype, MPI_COMM_WORLD, &status); MPI_Recv(&size, 1, MPI_INT, source, mtype, MPI_COMM_WORLD, &status); proc_world = (struct world**) malloc(sizeof(struct world*)*(rowsAux+aditional)); if(rank == 1) { aditional = 1; start_line = 0; } else { aditional = 2; start_line = 1; } for(i = 0; i < rowsAux+aditional; i++) { proc_world[i] = (struct world*) malloc(sizeof(struct world)*size); for(j = 0; j < size; j ++) { proc_world[i][j].type = empty; proc_world[i][j].count = 0; proc_world[i][j].breeding_period = 0; proc_world[i][j].starvation_period = 0; proc_world[i][j].breed = 0; for(z=0; z < 5; z++) world_global[i][j].conflicts[z]=NULL; } } for(i = start_line; i < rowsAux+start_line; i++) { MPI_Recv(proc_world[i], sizeof(struct world)*size, MPI_BYTE, source, mtype, MPI_COMM_WORLD, &status); } } #ifdef VERBOSE // start = clock(); #endif /* Comum a todos os processos */ MPI_Bcast(&w_breeding, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&s_breeding, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&w_starvation, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&gen_num, 1, MPI_INT, 0, MPI_COMM_WORLD); #ifdef MPIVERBOSE // printf("Leitura: %lf\n", MPI_Wtime() - secs); // secs = MPI_Wtime(); #endif /* Generate */ MPI_Status *statuses[2]; MPI_Request *request[2]; struct world *worldaux1, *worldaux2; //worldaux1 = (struct world*) malloc(sizeof(struct world)*size); //worldaux2 = (struct world*) malloc(sizeof(struct world)*size); while(gen_num != 0) { if(rank == 1) { for(i = 0; i < size ; i++) { proc_world[rowsAux][i].type = empty; proc_world[rowsAux][i].count = 0; proc_world[rowsAux][i].breeding_period = 0; proc_world[rowsAux][i].starvation_period = 0; proc_world[rowsAux][i].breed = 0; for(z=0; z < 5; z++) world_global[i][j].conflicts[z]=NULL; } } else if(rank == MASTER) { for(i = 0; i < size ; i++) { proc_world[0][i].type = empty; proc_world[0][i].count = 0; proc_world[0][i].breeding_period = 0; proc_world[0][i].starvation_period = 0; proc_world[0][i].breed = 0; for(z=0; z < 5; z++) world_global[i][j].conflicts[z]=NULL; } } else { for(i = 0; i < size ; i++) { proc_world[0][i].type = empty; proc_world[0][i].count = 0; proc_world[0][i].breeding_period = 0; proc_world[0][i].starvation_period = 0; proc_world[0][i].breed = 0; for(z=0; z < 5; z++) world_global[i][j].conflicts[z]=NULL; proc_world[rowsAux][i].type = empty; proc_world[rowsAux][i].count = 0; proc_world[rowsAux][i].breeding_period = 0; proc_world[rowsAux][i].starvation_period = 0; proc_world[rowsAux][i].breed = 0; for(z=0; z < 5; z++) world_global[i][j].conflicts[z]=NULL; } } for(i = (rank==1? 0 : 1); i< (rank==1 ? rowsAux : rowsAux+1) ; i++) { for(j=0; j<size; j++) { computeCell(i, j, s_breeding, w_breeding, w_starvation, size, rowsAux+aditional, proc_world, rank); } } /*Enviar a linha de coisas estranhas para o(s) processo(s) da fronteira */ if(rank == 1) { MPI_Irecv(worldaux1, sizeof(struct world)*size, MPI_BYTE, rank+1, 2, MPI_COMM_WORLD, request[0]); MPI_Send(proc_world[rowsAux], sizeof(struct world)*size, MPI_BYTE, (rank+1)%n_processes, rank, MPI_COMM_WORLD); MPI_Wait(request[0], statuses[0]); /* Juntar aos conflictos*/ for(i=0; i<size; i++) { proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count] = (conflict*)malloc(sizeof(struct conflicts)); proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count]->type = worldaux1[i].type; proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count]->breeding_period = worldaux1[i].breeding_period; proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count]->starvation_period = worldaux1[i].starvation_period; proc_world[rowsAux][i].count += 1; } } else if(rank == MASTER) { MPI_Irecv(worldaux1, sizeof(struct world)*size, MPI_BYTE, n_processes-1, n_processes-1, MPI_COMM_WORLD, request[0]); MPI_Send(proc_world[averow], sizeof(struct world)*size, MPI_BYTE, n_processes-1, rank, MPI_COMM_WORLD); MPI_Wait(request[0], statuses[0]); for(i=0; i<size; i++) { proc_world[0][i].conflicts[proc_world[0][i].count] = (conflict*)malloc(sizeof(struct conflicts)); proc_world[0][i].conflicts[proc_world[0][i].count]->type = worldaux1[i].type; proc_world[0][i].conflicts[proc_world[0][i].count]->breeding_period = worldaux1[i].breeding_period; proc_world[0][i].conflicts[proc_world[0][i].count]->starvation_period = worldaux1[i].starvation_period; proc_world[0][i].count += 1; } } else { MPI_Irecv(worldaux1, sizeof(struct world)*size, MPI_BYTE, rank+1%n_processes, rank+1%n_processes, MPI_COMM_WORLD, request[0]); MPI_Irecv(worldaux2, sizeof(struct world)*size, MPI_BYTE, rank-1%n_processes, rank-1%n_processes, MPI_COMM_WORLD, request[1]); MPI_Send(proc_world[rowsAux], sizeof(struct world)*size, MPI_BYTE, (rank+1)%n_processes, rank, MPI_COMM_WORLD); MPI_Send(proc_world[rowsAux], sizeof(struct world)*size, MPI_BYTE, (rank-1)%n_processes, rank, MPI_COMM_WORLD); MPI_Wait(request[0], statuses[0]); MPI_Wait(request[1], statuses[1]); for(i=0; i<size; i++) { proc_world[0][i].conflicts[proc_world[0][i].count] = (conflict*)malloc(sizeof(struct conflicts)); proc_world[0][i].conflicts[proc_world[0][i].count]->type = worldaux1[i].type; proc_world[0][i].conflicts[proc_world[0][i].count]->breeding_period = worldaux1[i].breeding_period; proc_world[0][i].conflicts[proc_world[0][i].count]->starvation_period = worldaux1[i].starvation_period; proc_world[0][i].count += 1; } for(i=0; i<size; i++) { proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count] = (conflict*)malloc(sizeof(struct conflicts)); proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count]->type = worldaux1[i].type; proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count]->breeding_period = worldaux1[i].breeding_period; proc_world[rowsAux][i].conflicts[proc_world[rowsAux][i].count]->starvation_period = worldaux1[i].starvation_period; proc_world[rowsAux][i].count += 1; } } /* fix do pequeno mundo do processo */ fixWorld(size, w_starvation, w_breeding, rowsAux, proc_world, rank); gen_num--; } /* Receber tudo no master */ #ifdef VERBOSE end = clock(); printf("Elapsed Time : %lf\n", (double)(end-start) / CLOCKS_PER_SEC); #endif MPI_Finalize(); /* Output */ //printWorldFormatted(size); return 0; }
int GC_init (GC_state s, int argc, char **argv) { char *worldFile; int res; assert (s->alignment >= GC_MODEL_MINALIGN); assert (isAligned (sizeof (struct GC_stack), s->alignment)); // While the following asserts are manifestly true, // they check the asserts in sizeofThread and sizeofWeak. assert (sizeofThread (s) == sizeofThread (s)); assert (sizeofWeak (s) == sizeofWeak (s)); s->amInGC = TRUE; s->amOriginal = TRUE; s->atomicState = 0; s->callFromCHandlerThread = BOGUS_OBJPTR; s->controls.fixedHeap = 0; s->controls.maxHeap = 0; s->controls.mayLoadWorld = TRUE; s->controls.mayPageHeap = FALSE; s->controls.mayProcessAtMLton = TRUE; s->controls.messages = FALSE; s->controls.oldGenSequenceSize = 0x100000; s->controls.ratios.copy = 4.0f; s->controls.ratios.copyGenerational = 4.0f; s->controls.ratios.grow = 8.0f; s->controls.ratios.hashCons = 0.0f; s->controls.ratios.live = 8.0f; s->controls.ratios.markCompact = 1.04f; s->controls.ratios.markCompactGenerational = 8.0f; s->controls.ratios.nursery = 10.0f; s->controls.ratios.ramSlop = 0.5f; s->controls.ratios.stackCurrentGrow = 2.0f; s->controls.ratios.stackCurrentMaxReserved = 32.0f; s->controls.ratios.stackCurrentPermitReserved = 4.0f; s->controls.ratios.stackCurrentShrink = 0.5f; s->controls.ratios.stackMaxReserved = 8.0f; s->controls.ratios.stackShrink = 0.5f; s->controls.summary = FALSE; s->controls.summaryFile = stderr; s->cumulativeStatistics.bytesAllocated = 0; s->cumulativeStatistics.bytesCopied = 0; s->cumulativeStatistics.bytesCopiedMinor = 0; s->cumulativeStatistics.bytesHashConsed = 0; s->cumulativeStatistics.bytesMarkCompacted = 0; s->cumulativeStatistics.bytesScannedMinor = 0; s->cumulativeStatistics.maxBytesLive = 0; s->cumulativeStatistics.maxHeapSize = 0; s->cumulativeStatistics.maxPauseTime = 0; s->cumulativeStatistics.maxStackSize = 0; s->cumulativeStatistics.numCardsMarked = 0; s->cumulativeStatistics.numCopyingGCs = 0; s->cumulativeStatistics.numHashConsGCs = 0; s->cumulativeStatistics.numMarkCompactGCs = 0; s->cumulativeStatistics.numMinorGCs = 0; rusageZero (&s->cumulativeStatistics.ru_gc); rusageZero (&s->cumulativeStatistics.ru_gcCopying); rusageZero (&s->cumulativeStatistics.ru_gcMarkCompact); rusageZero (&s->cumulativeStatistics.ru_gcMinor); s->currentThread = BOGUS_OBJPTR; s->hashConsDuringGC = FALSE; initHeap (s, &s->heap); s->lastMajorStatistics.bytesHashConsed = 0; s->lastMajorStatistics.bytesLive = 0; s->lastMajorStatistics.kind = GC_COPYING; s->lastMajorStatistics.numMinorGCs = 0; s->savedThread = BOGUS_OBJPTR; initHeap (s, &s->secondaryHeap); s->signalHandlerThread = BOGUS_OBJPTR; s->signalsInfo.amInSignalHandler = FALSE; s->signalsInfo.gcSignalHandled = FALSE; s->signalsInfo.gcSignalPending = FALSE; s->signalsInfo.signalIsPending = FALSE; sigemptyset (&s->signalsInfo.signalsHandled); sigemptyset (&s->signalsInfo.signalsPending); s->sysvals.pageSize = GC_pageSize (); s->sysvals.physMem = GC_physMem (); s->weaks = NULL; s->saveWorldStatus = true; initIntInf (s); initSignalStack (s); worldFile = NULL; unless (isAligned (s->sysvals.pageSize, CARD_SIZE)) die ("Page size must be a multiple of card size."); processAtMLton (s, 0, s->atMLtonsLength, s->atMLtons, &worldFile); res = processAtMLton (s, 1, argc, argv, &worldFile); if (s->controls.fixedHeap > 0 and s->controls.maxHeap > 0) die ("Cannot use both fixed-heap and max-heap."); unless (s->controls.ratios.markCompact <= s->controls.ratios.copy and s->controls.ratios.copy <= s->controls.ratios.live) die ("Ratios must satisfy mark-compact-ratio <= copy-ratio <= live-ratio."); unless (s->controls.ratios.stackCurrentPermitReserved <= s->controls.ratios.stackCurrentMaxReserved) die ("Ratios must satisfy stack-current-permit-reserved <= stack-current-max-reserved."); /* We align s->sysvals.ram by s->sysvals.pageSize so that we can * test whether or not we we are using mark-compact by comparing * heap size to ram size. If we didn't round, the size might be * slightly off. */ uintmax_t ram; ram = alignMax ((uintmax_t)(s->controls.ratios.ramSlop * (double)(s->sysvals.physMem)), (uintmax_t)(s->sysvals.pageSize)); ram = min (ram, alignMaxDown((uintmax_t)SIZE_MAX, (uintmax_t)(s->sysvals.pageSize))); s->sysvals.ram = (size_t)ram; if (DEBUG or DEBUG_RESIZING or s->controls.messages) fprintf (stderr, "[GC: Found %s bytes of RAM; using %s bytes (%.1f%% of RAM).]\n", uintmaxToCommaString(s->sysvals.physMem), uintmaxToCommaString(s->sysvals.ram), 100.0 * ((double)ram / (double)(s->sysvals.physMem))); if (DEBUG_SOURCES or DEBUG_PROFILE) { uint32_t i; for (i = 0; i < s->sourceMaps.frameSourcesLength; i++) { uint32_t j; uint32_t *sourceSeq; fprintf (stderr, "%"PRIu32"\n", i); sourceSeq = s->sourceMaps.sourceSeqs[s->sourceMaps.frameSources[i]]; for (j = 1; j <= sourceSeq[0]; j++) fprintf (stderr, "\t%s\n", s->sourceMaps.sourceNames[ s->sourceMaps.sources[sourceSeq[j]].sourceNameIndex ]); } } /* Initialize profiling. This must occur after processing * command-line arguments, because those may just be doing a * show-sources, in which case we don't want to initialize the * atExit. */ initProfiling (s); if (s->amOriginal) { initWorld (s); /* The mutator stack invariant doesn't hold, * because the mutator has yet to run. */ assert (invariantForMutator (s, TRUE, FALSE)); } else { loadWorldFromFileName (s, worldFile); if (s->profiling.isOn and s->profiling.stack) foreachStackFrame (s, enterFrameForProfiling); assert (invariantForMutator (s, TRUE, TRUE)); } s->amInGC = FALSE; return res; }
int main(int argc, char **argv){ int i, j; int x, y, size; int w_breeding, s_breeding, w_starvation, gen_num; char type_code; FILE * input_file; if(argc <= 5){ printf("ERROR: Expected 5 arguments provided %d.\n", argc); printf("Expected:\n./wolves-squirrels-serial <InputFile> <WolfBreedingPeriod> <SquirrelBreedingPeriod> <WolfStarvationPerior> <Generations>\n"); return -1; } omp_set_num_threads(4); w_breeding = atoi(argv[2]); s_breeding = atoi(argv[3]); w_starvation = atoi(argv[4]); gen_num = atoi(argv[5]); input_file = fopen(argv[1], "r"); if(input_file == NULL){ printf("ERROR: A valid input file is expected. %s is not a valid file.\n", argv[1]); return -1; } fscanf(input_file, "%d", &size); initWorld(size); while(fscanf(input_file, "%d %d %c", &x, &y, &type_code) != EOF){ world[x][y].type = type_code; if(world[x][y].type == wolf){ world[x][y].breeding_period = w_breeding; world[x][y].starvation_period = w_starvation; } else if(world[x][y].type == squirrel){ world[x][y].breeding_period = s_breeding; } } fclose(input_file); #ifdef VERBOSE start = omp_get_wtime(); #endif /* Generate */ while(gen_num != 0){ #pragma omp parallel sections { #pragma omp section { /* 1st sub-generation - RED */ #pragma omp parallel for private(i, j) schedule(guided, size/8) for(i=0; i<size; i++){ for(j = i%2 == 0 ? 0 : 1 ; j<size; j+=2){ computeCell(i, j, s_breeding, w_breeding, w_starvation, size); } } } #pragma omp section { /* 2nd sub-generation */ #pragma omp parallel for private(i, j) schedule(guided, size/8) for(i=0; i<size; i++){ for(j = i%2 == 0 ? 1 : 0 ; j<size; j+=2){ computeCell(i, j, s_breeding, w_breeding, w_starvation, size); } } } } fixWorld(size, w_starvation, w_breeding); gen_num--; } #ifdef VERBOSE end = omp_get_wtime(); printf("Elapsed time: %lf\n", end-start); #endif /* Output */ printWorldFormatted(size); return 0; }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } mbirdstr.push_back("birdblue"); mbirdstr.push_back("birdred"); mbirdstr.push_back("birdyellow"); mbirdclolor=rand()%100%3; // EFFECT_PLAY(true,MUSIC_SWOOSHING); //播放背景音乐 // CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(MUSIC_JUMP, true); //////////////////////////////////////////////////// // 下面添加创建自己的Sprite的代码 //////////////////////////////////////////////////// mScreenSize = CCDirector::sharedDirector()->getWinSize(); mFPS=CCDirector::sharedDirector()->getAnimationInterval(); mfac=CCDirector::sharedDirector()->getContentScaleFactor(); mfax = 320.f/mScreenSize.width; //gBardis = 5.f*gUpVelocity/mfac; gBardis = mScreenSize.height*2.f/9.0f-5; //m_addbartime=mScreenSize.width*mFPS*mfax*1.f/2.f/MOVESPEED-10; //m_addbartime=3; initWorld(); for (int i = 0; i<GBACKGROUNDNUM; i++) { addBackGround(i); } int imaxgroundnum=1; for (int i = 0; i<imaxgroundnum; i++) { imaxgroundnum=addGround(i); } m_ilastground=imaxgroundnum-1; CCLOG("m_pLastGround->boundingBox() first x:%f,:%f ", (m_pGroundVec[m_ilastground])->boundingBox().getMaxX(), (m_pGroundVec[m_ilastground])->boundingBox().size.width); addStart(); addTop(); //addRate(); //addFlappyBird(); addBird(); addScore(); addGameOver(); m_pScore->setVisible(false); m_pGameOver->setVisible(false); this->goReady(); addBarContainer(); setTouchEnabled(true); myflag=0; m_istatus=GETREADY; m_bhitbar=false; //scheduleOnce(schedule_selector(HelloWorld::startGame), 1); this->scheduleUpdate(); //创建动画 initAction(); myangle=0.f; return true; }