void GameScene::shipReBorn() { auto config = Config::getInstance(); auto lifes = config->getShipLife(); if (lifes != 0) { //creat a new ship ,may be can add some defeine--- ship = Ship::creatShip(this, 0, SHIP_LIFE_VALUE); auto initPosition = VisibleRect::center(); ship->setPosition(Vec2(initPosition.x, initPosition.y - 120.0f)); ship->setScale(1.2f); this->addChild(ship, SHIP_Z_ORDER); --lifes; } else { this->releaseR(); Director::getInstance()->replaceScene(TransitionFade::create(1.2f, GameOverLayer::createScene())); if (Config::getInstance()->getmusicState()) { SimpleAudioEngine::getInstance()->playBackgroundMusic(main_bg_stage1, true); } } config->setShipLife(lifes); __String life("X"); life.appendWithFormat("%02d", lifes); lifeValue->setString(life.getCString()); }
//Timer to be passed into glutTimerfunc. //Calls the world to update and then redisplays it. void timer(int n) { if (play){ life(); glutPostRedisplay(); glutTimerFunc(T, timer, T); } }
void LifeFarm::moveAntsNew() { life(currentstate,nextstate); //Swap pointers to the begnning of the current and next state arrays int* temp = nextstart; nextstart = currentstart; currentstart = temp; //Move the pointers to the beginning of the newly-swapped arrays currentstate = currentstart; nextstate = nextstart; return; }
std::streamsize Tree::write(OutputStream& ostream) const throw (Exception) { std::streamsize size = 0; wc3lib::write(ostream, treeId(), size); wc3lib::write(ostream, variation(), size); size += position().write(ostream); wc3lib::write(ostream, angle(), size); size += scale().write(ostream); wc3lib::write<byte>(ostream, flags(), size); wc3lib::write(ostream, life(), size); wc3lib::write(ostream, customId(), size); return size; }
void Player::receiveDamage( int damage, const QVector3D * position, const QVector3D * direction ) { if( !mGodMode ) { if( mArmor >= damage ) { mArmor -= damage; } else { int admg = damage - mArmor; mArmor -= (damage - admg); setLife( life() - admg ); if( life() <= 0 ) { if( state() == ALIVE ) setState( DYING ); setLife( 0 ); } } } }
void Dummy::updateSelf( const double & delta ) { switch( state() ) { case SPAWNING: { setPosition( randomPointOnWorld( world() ) + QVector3D(0,10,0) ); setState( ALIVE ); setLife( 100 ); mHeightAboveGround = 6.0f; break; } case ALIVE: { mTarget = world()->teapot()->worldPosition(); QVector3D directionToTarget = ( mTarget - worldPosition() ).normalized(); QQuaternion targetRotation = Quaternion::lookAt( directionToTarget, QVector3D(0,1,0) ); setRotation( QQuaternion::slerp( rotation(), targetRotation, 0.05 ) ); setPosition( position() + direction()*delta*10.0 ); if( life() <= 0 ) setState( DYING ); break; } case DYING: setState( DEAD ); mHeightAboveGround = 3.0f; break; case DEAD: break; } mVelocityY += -3.0f * delta; // apply some gravity setPositionY( position().y() + mVelocityY * delta ); float landscapeHeight; if( world()->landscape()->terrain()->getHeight( position(), landscapeHeight ) ) { if( landscapeHeight + mHeightAboveGround > position().y() ) { setPositionY( landscapeHeight + mHeightAboveGround ); if( mVelocityY < 0.0f ) mVelocityY = 0.0f; } } }
ReturnStateContext GameOfLife::onRun(QKeyboard &kb) { if(InternalState==GAME ) { RunCount++; uint32_t now = HAL_GetTick(); if (now < displayMessageUntil) { gui_lable_multiline(&UtilityBuf[0], 0, 10, 128, 64, 0, 0); } else if (ReInitGame) { initGame(); } else { uint16_t count = 0; uint8_t bitToCheck = CurrentGeneration % 32; for (uint16_t j = 1; j < height - 1; j++) { for (uint16_t k = 1; k < width - 1; k++) { if ((gol[j] & (k << bitToCheck)) != 0) { SSD1306_DrawPixel(k * 2, j, SSD1306_COLOR_WHITE); count++; } } } if (0 == count) { sprintf(&UtilityBuf[0], "ALL DEAD\nAfter %d\ngenerations", CurrentGeneration); displayMessageUntil = now + 3000; ReInitGame = true; } else { unsigned int tmp[sizeof(gol)]; life(&gol[0], Neighborhood, width, height, &tmp[0]); } if (RunCount % 3 == 0) { CurrentGeneration++; if (CurrentGeneration >= Generations) { ReInitGame = true; } } } if((now-kb.getLastPinSelectedTick())>(1000*60*TIMES_SCREEN_SAVER*getContactStore().getSettings().getScreenSaverTime())) { kb.setAllLightsOn(false); InternalState = SLEEP; } } if (kb.getLastKeyReleased() == QKeyboard::NO_PIN_SELECTED) { return ReturnStateContext(this); } else { kb.setAllLightsOn(true); return ReturnStateContext(StateFactory::getMenuState()); } }
int main( int argc, char **argv ) { int rank, N, iters ; double time ; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank) ; /* If I'm process 0, determine the matrix size and # of iterations */ /* This relies on the MPI implementation properly flushing output that does not end in a newline. MPI does not require this, though high-quality implementations will do this. */ #if !defined (SGI_MPI) && !defined (IBM_MPI) if ( rank == 0 ) { printf("Matrix Size : ") ; scanf("%d",&N) ; printf("Iterations : ") ; scanf("%d",&iters) ; } #else N=20; iters=50; #endif /* Broadcast the size and # of iterations to all processes */ MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD) ; MPI_Bcast(&iters, 1, MPI_INT, 0, MPI_COMM_WORLD) ; if (argc > 2 && strcmp( argv[1], "-display" ) == 0) { displayname = malloc( strlen( argv[2] ) + 1 ); strcpy( displayname, argv[2] ); } /* Call the life routine */ time = life( N, iters, MPI_COMM_WORLD ); /* Print the total time taken */ if (rank == 0) printf("[%d] Life finished in %lf seconds\n",rank,time/100); MPE_Close_graphics(&graph); MPI_Finalize(); }
static void asteroid_sound_update(int param, INT16 *buffer, int length) { int samplerate = Machine->sample_rate; while( length-- > 0 ) { int sum = 0; sum += explosion(samplerate) / 7; sum += thrust(samplerate) / 7; sum += thump(samplerate) / 7; sum += saucer(samplerate) / 7; sum += saucerfire(samplerate) / 7; sum += shipfire(samplerate) / 7; sum += life(samplerate) / 7; *buffer++ = sum; } }
static THR_DEF life_thr( void * argVoid ){ void ** argsThr = (void **)argVoid; bool2D * world; /* world to evolve */ int nr, nc; /* row/col size */ int iters; /* number of iterations */ int tid; /* ID */ /* setup */ world = TG_bool2D(argsThr, 0); nr = TG_int(argsThr, 1); nc = TG_int(argsThr, 2); iters = TG_int(argsThr, 3); tid = thr_idSet(); life(tid, *world, nr, nc, iters); THR_END(argsThr); }
void GameClass::DrawGameIntro () const { ALLEGRO_COLOR fontColor = cWhite; if (introScreen == 0) { for (size_t i = 0; i < cGameIntroLines; i++) { al_draw_text(normalFont, fontColor, cWindowWidth/2, 70 + i*45, ALLEGRO_ALIGN_CENTRE, cGameIntroText[language][i].c_str()); } al_draw_text(normalFont, fontColor, cWindowWidth - 20, cWindowHeight - 30, ALLEGRO_ALIGN_RIGHT, cPressAnyKey[language].c_str()); } else { for (size_t i = 0; i < cInstructionsLines; i++) { al_draw_text(normalFont, fontColor, 200, 200 + i*45, ALLEGRO_ALIGN_LEFT, cInstructionsText[language][i].c_str()); } Upgrade jump (jumpUpgrade, 200, 180 + 5*45), speed (speedUpgrade, 200, 180 + 6*45), life (lifeUpgrade, 200, 180 + 7*45), doubleJump(doubleJumpUpgrade, 200, 180 + 8*45), wallJump (wallJumpUpgrade, 200, 180 + 9*45); jump.Draw(); speed.Draw(); life.Draw(); doubleJump.Draw(); wallJump.Draw(); al_draw_text(bigFont, fontColor, cWindowWidth/2, 40, ALLEGRO_ALIGN_CENTRE, cInstructions[language].c_str()); al_draw_text(normalFont, fontColor, cWindowWidth - 20, cWindowHeight - 30, ALLEGRO_ALIGN_RIGHT, cPressAnyKey[language].c_str()); } }
bool GameScene::init() { if (!Layer::init())return false; initPlist(); initEffect(); //set game status Config::getInstance()->setGameSatus(ING); Config::getInstance()->setScore(0);//rest score //loding effect auto _SimpleAudioEngine = SimpleAudioEngine::getInstance(); _SimpleAudioEngine->preloadEffect(air_shoot_effect1); _SimpleAudioEngine->preloadEffect(ship_explode_effect0); //init game map //init enemy type switch (levelNum) { case GAMEMAP1://0 if (Config::getInstance()->getmusicState()) { auto simpleAudio = SimpleAudioEngine::getInstance(); simpleAudio->preloadBackgroundMusic(battle_bg_stage0); simpleAudio->setBackgroundMusicVolume(1.0f); simpleAudio->playBackgroundMusic(battle_bg_stage0, true); } addMap("Map1.png"); levelScore = BOOS_LEVEL1; break; case GAMEMAP2://1 if (Config::getInstance()->getmusicState()) { auto simpleAudio = SimpleAudioEngine::getInstance(); simpleAudio->preloadBackgroundMusic(battle_bg_stage1); simpleAudio->setBackgroundMusicVolume(1.0f); simpleAudio->playBackgroundMusic(battle_bg_stage1, true); } addMap("Map2.png"); levelScore = BOOS_LEVEL2; //add particle Kit::addParticle(snow_plist, this, VisibleRect::top()); break; case GAMEMAP3://2 if (Config::getInstance()->getmusicState()) { auto simpleAudio = SimpleAudioEngine::getInstance(); simpleAudio->preloadBackgroundMusic(battle_bg_stage2); simpleAudio->setBackgroundMusicVolume(1.0f); simpleAudio->playBackgroundMusic(battle_bg_stage2, true); } addMap("Map3.png"); levelScore = BOOS_LEVEL3; break; case GAMEMAP4://3 if (Config::getInstance()->getmusicState()) { auto simpleAudio = SimpleAudioEngine::getInstance(); simpleAudio->preloadBackgroundMusic(battle_bg_stage2); simpleAudio->setBackgroundMusicVolume(1.0f); simpleAudio->playBackgroundMusic(battle_bg_stage2, true); } addMap("Map4.png"); levelScore = BOOS_LEVEL4; //add fire paticle Kit::addParticle(battle_fire_bg_particle_plist, this, VisibleRect::top()); break; default: log("there's no game map to do !"); return false; break; } //add logo one top-left auto logoShip = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(SHIP_FILE_NAME)); float offset = logoShip->getContentSize().width / 2; logoShip->setScale(0.8f); auto winsize = Director::getInstance()->getWinSize(); logoShip->setPosition(Vec2(offset, winsize.height - offset)); this->addChild(logoShip, SHIP_Z_ORDER); //set life value beside of logoShip Config::getInstance()->setShipLife(SHIP_LIFES); __String life("X"); life.appendWithFormat("%02d", Config::getInstance()->getShipLife()); lifeValue = Label::createWithSystemFont(life.getCString(), "Arial", 12); lifeValue->setPosition(Vec2(offset * 3, winsize.height - offset)); lifeValue->setColor(Color3B::RED); this->addChild(lifeValue, SHIP_Z_ORDER); //add score __String tempscore("得分:"); tempscore.appendWithFormat("%07d", Config::getInstance()->getScore()); score = Label::createWithSystemFont(tempscore.getCString(), "Arial", 12); score->setPosition(Vec2(winsize.width - 45, winsize.height - offset)); score->setColor(Color3B::RED); this->addChild(score, SHIP_Z_ORDER); ship = Ship::creatShip(this, 0, SHIP_LIFE_VALUE); auto initPosition = VisibleRect::center(); ship->setPosition(Vec2(initPosition.x, initPosition.y - 120.0f)); this->addChild(ship, SHIP_Z_ORDER); //add bone btn auto bone_btn_sprite = Sprite::create(btn_bone_res); bone_btn_sprite->setScale(0.8f); auto bone_btn = MenuItemSprite::create(bone_btn_sprite, nullptr, [&](Ref* _bone_btn){ //处理炸弹效果 log("bone released ......"); //can shake auto j = JumpBy::create(0.5f, Vec2::ZERO, 5, 5); this->runAction(j); auto config = Config::getInstance(); //remove enemy and bullet for (auto bullet : *config->enemy_bullet_list) { bullet->boneDestory(); } for (auto enemy : *config->enemy_list) { //effect it log("effect it ......"); enemy->boneDestory(this); } config->enemy_bullet_list->clear(); config->enemy_list->clear(); }); auto menue = Menu::create(bone_btn, NULL); menue->setPosition(Vec2(35, 200)); this->addChild(menue, BTN_BACK_Z_ORDER); menue->runAction(Kit::creatEaseSineInOut(100.0f)); //add back btn auto btn_sprite = Sprite::createWithTexture(Director::getInstance()->getTextureCache()->addImage(btn_back_res)); btn_sprite->setColor(Color3B(0, 245, 255)); auto btn_back = MenuItemSprite::create(btn_sprite, nullptr, [&](Ref* item){ auto menuSprite = (MenuItemSprite*)item; auto scale = ScaleBy::create(0.2f, 1.1); auto jumpToGameLevel = CallFunc::create([](){ auto config=Config::getInstance(); if (config->getmusicState()) SimpleAudioEngine::getInstance()->stopBackgroundMusic();// 停止当前背景音乐 if (config->getmusicState()) { SimpleAudioEngine::getInstance()->playBackgroundMusic(main_bg_stage1, true); } Director::getInstance()->replaceScene(TransitionFade::create(1.2f, GameLevelLayer::creatScene())); }); //call back std::function<void()> releaseResources = [&](){ this->releaseR(); }; menuSprite->runAction(Sequence::create(CallFunc::create(releaseResources), scale, scale->reverse(), jumpToGameLevel, NULL)); }); menue = Menu::create(btn_back, NULL); auto btn_back_position = VisibleRect::rightBottom(); offset = btn_sprite->getContentSize().width / 2; menue->setPosition(Vec2(btn_back_position.x - 50, btn_back_position.y + 25)); this->addChild(menue, BTN_BACK_Z_ORDER); menue->runAction(Kit::creatEaseSineInOut(100.0f)); //添加敌机 this->schedule(schedule_selector(GameScene::addEnemy), 2.0f, kRepeatForever, 1.2f); this->scheduleUpdate(); //初始化地图移动 this->scheduleOnce(schedule_selector(GameScene::initMoveMap), 1.2f); return true; }
int main(int argc, char **argv) { int retval; struct timeval t, tod; struct timezone tz; fd_set rset; FD_ZERO(&rset); setbuf(stdout, outbuf); srandomdev(); signal(SIGINT, leave); signal(SIGQUIT, leave); signal(SIGTSTP, suspend); /* process control signal */ initscr(); cbreak(); noecho(); keypad(stdscr, TRUE); slow = (baudrate() <= 1200); clear(); if (COLS < 18 || LINES < 5) { endwin(); errx(1, "screen too small"); } if (argc == 2) start_len = atoi(argv[1]); if ((start_len <= 0) || (start_len > ((LINES-3) * (COLS-2)) / 3)) start_len = LENGTH; stw = newwin(1, COLS-1, 0, 0); tv = newwin(LINES-1, COLS-1, 1, 0); box(tv, '*', '*'); scrollok(tv, FALSE); scrollok(stw, FALSE); wmove(stw, 0, 0); wprintw(stw, " Worm"); refresh(); wrefresh(stw); wrefresh(tv); life(); /* Create the worm */ prize(); /* Put up a goal */ while(1) { if (wantleave) { endwin(); /* XXX signal race */ exit(0); } if (wantsuspend) { move(LINES-1, 0); refresh(); endwin(); fflush(stdout); kill(getpid(), SIGSTOP); signal(SIGTSTP, suspend); cbreak(); noecho(); setup(); wantsuspend = 0; } if (running) { running--; process(lastch); } else { /* fflush(stdout); */ /* Delay could be a command line option */ t.tv_sec = 1; t.tv_usec = 0; (void)gettimeofday(&tod, &tz); FD_SET(STDIN_FILENO, &rset); retval = select(STDIN_FILENO + 1, &rset, NULL, NULL, &t); if (retval > 0) process(getch()); else process(lastch); } } }
Ultra1::StateNumber Ultra1::HelpState::Run( ) { Sim::Image bg( UBD_PREFIX "/images/mountains.jpg" ); Sim::Image but( UBD_PREFIX "/images/button.png", 255, 0, 0 ); Sim::Button menu( 0, 480, 450, 50, 3, 0, 0, 0, 40, 7, true ); menu.SetBackGround( but.image ); menu.SetForeGround( "Main Menu", app->text_writer.GetFont( GALAPOGO_36 ), 0, 0, 0 ); Sim::Button quit( 0, 540, 450, 50, 3, 0, 0, 0, 40, 7, true ); quit.SetBackGround( but.image ); quit.SetForeGround( "Quit", app->text_writer.GetFont( GALAPOGO_36 ), 0, 0, 0 ); Sim::Image bear_i( UBD_PREFIX "/images/bear.png", 0, 0, 255 ); Sim::Sprite bear( 10, 130, 20, 40, 1 ); bear.AddAnimation( 0, 0, 3, true, bear_i.image, 200, true ); Sim::Image armor_i( UBD_PREFIX "/images/armor.png", 0, 0, 255 ); Sim::Sprite armor( 10, 190, 20, 20, 1 ); armor.AddAnimation( 0, 0, 2, true, armor_i.image, 125, false ); Sim::Image force_i( UBD_PREFIX "/images/force.png", 0, 0, 255 ); Sim::Sprite force( 10, 230, 20, 20, 1 ); force.AddAnimation( 0, 0, 2, true, force_i.image, 125, false ); Sim::Image life_i( UBD_PREFIX "/images/extralife.png", 0, 0, 255 ); Sim::Sprite life( 10, 270, 20, 20, 1 ); life.AddAnimation( 0, 0, 2, true, life_i.image, 125, false ); Sim::Image coin_i( UBD_PREFIX "/images/coin.png", 0, 0, 255 ); Sim::Sprite coin( 10, 310, 20, 20, 1 ); coin.AddAnimation( 0, 0, 3, true, coin_i.image, 125, false ); SDL_Event event; while( true ) { while( SDL_PollEvent(&event) ) { if( event.type == SDL_QUIT ) { app->FadeTo( 100 ); return QUIT_STATE; } else if( event.type == SDL_KEYDOWN ) { if( event.key.keysym.sym == SDLK_ESCAPE ) { app->FadeTo( 100 ); return MENU_STATE; } } else if( event.type == SDL_MOUSEBUTTONDOWN ) { menu.HandleMouseDown( event.button.x, event.button.y ); quit.HandleMouseDown( event.button.x, event.button.y ); } else if( event.type == SDL_MOUSEBUTTONUP ) { if( menu.HandleMouseUp( event.button.x, event.button.y ) ) { app->PlaySound( BUTTON_NOISE ); app->FadeTo( 100 ); return MENU_STATE; } if( quit.HandleMouseUp( event.button.x, event.button.y ) ) { app->PlaySound( BUTTON_NOISE ); app->FadeTo( 100 ); return QUIT_STATE; } } } bear.Update( ); armor.Update( ); force.Update( ); life.Update( ); coin.Update( ); app->Clear( 0, 0, 0 ); SDL_BlitSurface( bg.image, NULL, app->screen, NULL ); app->text_writer.WriteText( app->screen, GALAPOGO_72, "Help", 10, 0, 0, 0, 0 ); // Write basic info at top... app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "In this game, you must guide Ultra Bear to the South Pole by working through every level on the map.", 10, 65, 0, 0, 0 ); app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "To beat a level, you must move Ultra Bear to the right while avoiding all of the enemies. You can kill", 10, 82, 0, 0, 0 ); app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "enemies by bouncing on their heads. Here are a few things that you will encounter:", 10, 99, 0,0,0 ); // Info beside UB and crew... app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "Ultra Bear. This is the bear you must guide south. He is very Ultra.", 50, 139, 0, 0, 0 ); app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "Armor. This pickup will protect Ultra Bear from one blow by an enemy.", 50, 190, 0, 0, 0 ); app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "Force. This magic force field will eliminate all enemies Ultra Bear touches. It will wear off though.", 50, 230, 0, 0, 0 ); app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "Extra Life. This pickup will credit Ultra Bear with one extra life.", 50, 270, 0, 0, 0 ); app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "Coin. This pickup deposits one coin in Ultra Bear's account. Once he has 100, he can trade them in for an extra life.", 50, 310, 0, 0, 0 ); app->text_writer.WriteText( app->screen, PLAIN_FONT_14, "The controls can be configured by clicking Options from the Main Menu", 10, 380, 0, 0, 0 ); menu.Draw( app->screen ); quit.Draw( app->screen ); bear.Draw( app->screen ); armor.Draw( app->screen ); force.Draw( app->screen ); life.Draw( app->screen ); coin.Draw( app->screen ); app->Flip( ); } }
/** Checks for collisions between the player and objects */ void Game::collisions() { int tX = yoshi->getLocx(); int tY = yoshi->getLocy(); if(tY+yoshi->getHeight() < 450) { things[0]->setLocy(things[0]->getLocy()+1); things[0]->update(); } if(spawnCnt >= 100) { for(int k=0; k<things.size(); k++) { int pX = things[k]->getLocx(); int pY = things[k]->getLocy(); if(abs(tX-pX) < 32 && abs(tY-pY) < 32) { if(things[k]->type == Thing::goombaEnemy) { life(0); spawnCnt = 0; } else if(things[k]->type == Thing::koopaEnemy) { life(0); spawnCnt = 0; } else if(things[k]->type == Thing::billEnemy) { life(0); spawnCnt = 0; } else if(things[k]->type == Thing::kamekEnemy) { life(0); spawnCnt = 0; } else if(things[k]->type == Thing::ammo) { life(0); spawnCnt = 0; things[k]->del = true; } else if(things[k]->type == Thing::item) { gScene->removeItem(things[k]); things.pop(k); nCoins++; if(nCoins == 5) { life(1); nCoins = 0; } gScene->removeItem(cAmount); QString temp = QString::number(nCoins); cAmount = new QGraphicsSimpleTextItem(temp); cAmount->setPos(210, 460); cAmount->setFont(font); cAmount->setZValue(2); gScene->addItem(cAmount); gScene->removeItem(sAmount); score += 50; temp = QString::number(score); sAmount = new QGraphicsSimpleTextItem(temp); sAmount->setPos(400, 450); sAmount->setFont(fontT); sAmount->setZValue(2); gScene->addItem(sAmount); } else if(things[k]->type == Thing::life) { gScene->removeItem(things[k]); things.pop(k); life(1); } } } } else { spawnCnt++; } }
int main( int argc, /* arg count */ char * argv[] /* arg vector */ ){ static char * context = "main(chain)"; char * stem = NULL; /* dump filename stem */ char * suffix = NULL; /* dump filename suffix */ char * suff2 = NULL; /* last half of suffix */ int nr, nc; /* integer matrix sizes */ int n; /* square matrix/vector size */ real base_x, base_y; /* base of Mandelbrot */ real ext_x, ext_y; /* extent of Mandelbrot */ int limit, seed; /* randmat controls */ real fraction; /* invperc/thresh filling */ int itersLife; /* life iterations */ int itersElastic, relax; /* elastic controls */ int2D i2D; /* integer matrix */ bool2D b2D; /* boolean matrix */ pt1D cities; /* cities point vector */ int n_cities; /* number of cities */ pt1D net; /* net point vector */ int n_net; /* number of net points */ real2D r2D_gauss; /* real matrix for Gaussian */ real2D r2D_sor; /* real matrix for SOR */ real1D r1D_gauss_v; /* real vector input for Gaussian */ real1D r1D_sor_v; /* real vector input for SOR */ real1D r1D_gauss_a; /* real vector answer for Gaussian */ real1D r1D_sor_a; /* real vector answer for SOR */ real1D r1D_gauss_c; /* real vector check for Gaussian */ real1D r1D_sor_c; /* real vector check for SOR */ real tol; /* SOR tolerance */ real realDiff; /* vector difference */ bool choicesSet = FALSE; /* path choices set? */ bool doMandel = TRUE; /* mandel vs. randmat */ bool doInvperc = TRUE; /* invperc vs. thresholding */ bool doDump = FALSE; /* dump intermediate results? */ int argd = 1; /* argument index */ /* arguments */ #if NUMA MAIN_INITENV(,32000000) #endif while (argd < argc){ CHECK(argv[argd][0] == '-', fail(context, "bad argument", "index", "%d", argd, NULL)); switch(argv[argd][1]){ case 'E' : /* elastic */ itersElastic = arg_int(context, argc, argv, argd+1, argv[argd]); relax = arg_int(context, argc, argv, argd+2, argv[argd]); argd += 3; break; case 'F' : /* fraction (invperc/thresh) */ fraction = arg_real(context, argc, argv, argd+1, argv[argd]); argd += 2; break; case 'L' : /* life */ itersLife = arg_int(context, argc, argv, argd+1, argv[argd]); argd += 2; break; case 'M' : /* mandel */ base_x = arg_real(context, argc, argv, argd+1, argv[argd]); base_y = arg_real(context, argc, argv, argd+2, argv[argd]); ext_x = arg_real(context, argc, argv, argd+3, argv[argd]); ext_y = arg_real(context, argc, argv, argd+4, argv[argd]); argd += 5; break; case 'N' : /* winnow */ n_cities = arg_int(context, argc, argv, argd+1, argv[argd]); argd += 2; break; case 'R' : /* randmat */ limit = arg_int(context, argc, argv, argd+1, argv[argd]); seed = arg_int(context, argc, argv, argd+2, argv[argd]); argd += 3; break; case 'S' : /* matrix size */ nr = arg_int(context, argc, argv, argd+1, argv[argd]); nc = arg_int(context, argc, argv, argd+2, argv[argd]); argd += 3; break; case 'T' : /* SOR tolerance */ tol = arg_real(context, argc, argv, argd+1, argv[argd]); argd += 2; break; case 'c' : /* choice */ CHECK(!choicesSet, fail(context, "choices already set", NULL)); suffix = arg_str(context, argc, argv, argd+1, argv[argd]); argd += 2; switch(suffix[0]){ case 'i' : doInvperc = TRUE; break; case 't' : doInvperc = FALSE; break; default : fail(context, "unknown choice(s)", "choice", "%s", suffix, NULL); } switch(suffix[1]){ case 'm' : doMandel = TRUE; break; case 'r' : doMandel = FALSE; break; default : fail(context, "unknown choice(s)", "choice", "%s", suffix, NULL); } suff2 = suffix+1; choicesSet = TRUE; break; case 'd' : /* dump */ doDump = TRUE; argd += 1; if ((argd < argc) && (argv[argd][0] != '-')){ stem = arg_str(context, argc, argv, argd, argv[argd-1]); argd += 1; } break; #if GRAPHICS case 'g' : gfx_open(app_chain, arg_gfxCtrl(context, argc, argv, argd+1, argv[argd])); argd += 2; break; #endif #if MIMD case 'p' : DataDist = arg_dataDist(context, argc, argv, argd+1, argv[argd]); ParWidth = arg_int(context, argc, argv, argd+2, argv[argd]); argd += 3; break; #endif case 'u' : io_init(FALSE); argd += 1; break; default : fail(context, "unknown flag", "flag", "%s", argv[argd], NULL); break; } } CHECK(choicesSet, fail("context", "choices not set using -c flag", NULL)); /* initialize */ #if MIMD sch_init(DataDist); #endif /* mandel vs. randmat */ if (doMandel){ mandel(i2D, nr, nc, base_x, base_y, ext_x, ext_y); if (doDump) io_wrInt2D(context, mkfname(stem, NULL, suff2, "i2"), i2D, nr, nc); } else { randmat(i2D, nr, nc, limit, seed); if (doDump) io_wrInt2D(context, mkfname(stem, NULL, suff2, "i2"), i2D, nr, nc); } /* half */ half(i2D, nr, nc); if (doDump) io_wrInt2D(context, mkfname(stem, "h", suff2, "i2"), i2D, nr, nc); /* invperc vs. thresh */ if (doInvperc){ invperc(i2D, b2D, nr, nc, fraction); if (doDump) io_wrBool2D(context, mkfname(stem, NULL, suffix, "b2"), b2D, nr, nc); } else { thresh(i2D, b2D, nr, nc, fraction); if (doDump) io_wrBool2D(context, mkfname(stem, NULL, suffix, "b2"), b2D, nr, nc); } /* life */ life(b2D, nr, nc, itersLife); if (doDump) io_wrBool2D(context, mkfname(stem, "l", suffix, "b2"), b2D, nr, nc); /* winnow */ winnow(i2D, b2D, nr, nc, cities, n_cities); if (doDump) io_wrPt1D(context, mkfname(stem, "w", suffix, "p1"), cities, n_cities); /* norm */ norm(cities, n_cities); if (doDump) io_wrPt1D(context, mkfname(stem, "n", suffix, "p1"), cities, n_cities); /* elastic */ n_net = (int)(ELASTIC_RATIO * n_cities); CHECK(n_net <= MAXEXT, fail(context, "too many net points required", "number of net points", "%d", n_net, NULL)); elastic(cities, n_cities, net, n_net, itersElastic, relax); if (doDump) io_wrPt1D(context, mkfname(stem, "e", suffix, "p1"), net, n_net); /* outer */ n = n_net; outer(net, r2D_gauss, r1D_gauss_v, n); if (doDump){ io_wrReal2D(context, mkfname(stem, "o", suffix, "r2"), r2D_gauss, n, n); io_wrReal1D(context, mkfname(stem, "o", suffix, "r1"), r1D_gauss_v, n); } cpReal2D(r2D_gauss, r2D_sor, n, n); cpReal1D(r1D_gauss_v, r1D_sor_v, n); /* gauss */ gauss(r2D_gauss, r1D_gauss_v, r1D_gauss_a, n); if (doDump) io_wrReal1D(context, mkfname(stem, "g", suffix, "r1"), r1D_gauss_a, n); /* product (gauss) */ product(r2D_gauss, r1D_gauss_a, r1D_gauss_c, n, n); if (doDump) io_wrReal1D(context, mkfname(stem, "pg", suffix, "r1"), r1D_gauss_c, n); /* sor */ sor(r2D_sor, r1D_sor_v, r1D_sor_a, n, tol); if (doDump) io_wrReal1D(context, mkfname(stem, "s", suffix, "r1"), r1D_gauss_a, n); /* product (sor) */ product(r2D_sor, r1D_sor_a, r1D_sor_c, n, n); if (doDump) io_wrReal1D(context, mkfname(stem, "ps", suffix, "r1"), r1D_gauss_c, n); /* difference */ vecdiff(r1D_gauss_a, r1D_sor_a, n, &realDiff); if (doDump) io_wrReal0D(context, mkfname(stem, "v", suffix, "r0"), realDiff); #if IEEE ieee_retrospective(stderr); #endif #if NUMA MAIN_END; #endif return 0; }
int main(void) { life(); }
int main(int argc, char** argv) { char *fileName = NULL; int width = 0, height = 0; bool manual = false; bool random = true; int step = 50000; struct option long_options[] = { {"file", required_argument, 0, 'f'}, {"width", required_argument, 0, 'w'}, {"height", required_argument, 0, 'h'}, {"manual", optional_argument, 0, 'm'}, {"random", optional_argument, 0, 'r'}, {"step", required_argument, 0, 't'}, {NULL, 0, NULL, 0} }; int option_index = 0; int c; while ((c = getopt_long(argc, argv, "f:w:h:mrt:", long_options, &option_index)) != -1) { switch(c) { case 'f': fileName = optarg; break; case 'w': width = atoi(optarg); break; case 'h': height = atoi(optarg); break; case 'm': manual = true; break; case 'r': random = true; break; case 't': step = atoi(optarg) * 1000; break; } } if(width == 0 || height == 0) { struct winsize w; ioctl(0, TIOCGWINSZ, &w); if(width == 0) { width = w.ws_col - 2; } if(height == 0) { height = w.ws_row - 3; } } TheLife life(width, height); if(fileName) { FILE* f = fopen(fileName, "r"); if(f == NULL) { printf("Failed to open file"); return 1; } int x = 0, y = 0; char c; while(fscanf(f, "%c", &c) == 1) { if(c == '\n') { x = 0; y++; } if(c == '1') { life.setLive(x, y); } x++; } } else if(random) { life.generate(); } life.render(); while(1) { if(manual) { getchar(); } else { usleep(step); } life.step(); life.render(); } }