bool game(Element *array, int number) { int i, j, k; Element temp[number - 1]; if(number == 1) { if(fabs(array[0].value - TARGET) < PRECISION) { printf("%d = %s\n", TARGET, array[0].expression); return TRUE; } else { return FALSE; } } for(i = 0; i < number - 1; i++) { for(j = i + 1; j < number; j++) { int kk = 0; for(k = 0; k < number; k++) { if(k != i && k != j) { temp[kk].value = array[k].value; sprintf(temp[kk].expression, "%s", array[k].expression); kk++; } } temp[number-2].value = array[i].value + array[j].value; sprintf(temp[number - 2].expression, "(%s + %s)", array[i].expression, array[j].expression); if(game(temp, number - 1)) return TRUE; if(array[i].value > array[j].value) { temp[number - 2].value = array[i].value - array[j].value; sprintf(temp[number - 2].expression, "(%s - %s)", array[i].expression, array[j].expression); } else { temp[number - 2].value = array[j].value - array[i].value; sprintf(temp[number - 2].expression, "(%s - %s)", array[j].expression, array[i].expression); } if(game(temp, number - 1)) return TRUE; temp[number - 2].value = array[i].value * array[j].value; sprintf(temp[number - 2].expression, "%s * %s", array[i].expression, array[j].expression); if(game(temp, number - 1)) return TRUE; if(array[i].value != 0.0) { temp[number - 2].value = array[j].value / array[i].value; sprintf(temp[number - 2].expression, "%s / %s", array[j].expression, array[i].expression); if(game(temp, number - 1)) return TRUE; } if(array[j].value != 0.0) { temp[number - 2].value = array[i].value / array[j].value; sprintf(temp[number - 2].expression, "%s / %s", array[i].expression, array[j].expression); if(game(temp, number - 1)) return TRUE; } } } return FALSE; }
void CyclopsEntity::animate(float delay) { if (age <= 0.0f) { age += delay; return; } if (isAgonising) { if (h < -0.01f) { isDying = true; game().addCorpse(x, y, deathFrame); if (dyingSound != SOUND_NONE) SoundManager::getInstance().playSound(dyingSound); } else { frame = dyingFrame; hVelocity -= 700.0f * delay; h += hVelocity * delay; } return; } // special states if (specialState[SpecialStateIce].active) delay *= specialState[SpecialStateIce].param1; // IA computeStates(delay); // collisions if (canCollide()) testSpriteCollisions(); BaseCreatureEntity::animate(delay); // old frame (for sound) int oldFrame = frame; // current frame if (state == 0) { int r = ((int)(age * 5.0f)) % 4; if (r == 2) frame = 0; else if (r == 3) frame = 2; else frame = r; if (oldFrame == 1 && frame == 0) SoundManager::getInstance().playSound(SOUND_HEAVY_STEP_00); else if (oldFrame == 2 && frame == 0) SoundManager::getInstance().playSound(SOUND_HEAVY_STEP_01); } else if (state == 1) { isMirroring = game().getPlayer()->getX() > x; frame = timer > 0.5f ? 4 : 3; } else if (state == 2) { frame = 4; } else if (state == 3) { frame = 6; } else if (state == 4) { frame = 7; } // frame's mirroring if (velocity.x > 1.0f) isMirroring = true; else if (velocity.x < -1.0f) isMirroring = false; z = y + 36; }
int main() { Game game("level1.txt"); game.playGame(); return 0; }
void sandbox(SDL_Surface *s, int width, int height){ form sand(0,0,1000,600); cout<<sand.children.size()<<"\n"; XAutomataEngine game(&sand,200,100,750,400,width,height); //configure key events to pass preview to sand. sand.tag = &game; sand.addHandler(event_keydown,sandKey); //pan controls Button panUp(&sand,70,190,45,45); panUp.text = "Up"; Button panDown(&sand,70,290,45,45); panDown.text = "Down"; Button panLeft(&sand,20,240,45,45); panLeft.text = "Left"; Button panRight(&sand,120,240,45,45); panRight.text = "Right"; Button home(&sand,70,240,45,45); home.text = (width==-1&&height==-1?"Home":"Fit"); panUp.tag = panDown.tag = panLeft.tag = panRight.tag = home.tag = (void*)(&game); panUp.addHandler(event_Lclick,sandUpHandler); panDown.addHandler(event_Lclick,sandDownHandler); panLeft.addHandler(event_Lclick,sandLeftHandler); panRight.addHandler(event_Lclick,sandRightHandler); home.addHandler(event_Lclick,sandHomeHandler); //zoom controls Button zoomIn(&sand,55,375,75,45); zoomIn.text = "Zoom in"; Button zoomOut(&sand,55,445,75,45); zoomOut.text = "Zoom out"; zoomIn.tag = zoomOut.tag = (void*)(&game); zoomIn.addHandler(event_Lclick,sandZoomInHandler); zoomOut.addHandler(event_Lclick,sandZoomOutHandler); //speed controls label speedLabel(&sand,200,530,130,30); speedLabel.text = "Speed: Paused"; HScroll speedScroll(&sand,350,530,200,30,1,10,5); Button pause(&sand,600,530,70,30); pause.text = "Pause"; Button step(&sand,700,530,70,30); step.text = "Step"; speedLabel.tag = speedScroll.tag = pause.tag = step.tag = (void*)(&game); speedScroll.addHandler(event_scroll,sandScrollHandler); pause.addHandler(event_Lclick,sandPause); step.addHandler(event_Lclick,sandStep); //colour controls radioButton white(&sand,300,35,80,20,NULL); white.setTextColour(255,255,255); white.setText("Master"); radioButton red(&sand,400,35,80,20,&white); red.setTextColour(255,100,100); red.setText("Red"); radioButton green(&sand,500,35,80,20,&red); green.setTextColour(0,255,100); green.setText("Green"); radioButton blue(&sand,600,35,80,20,&green); blue.setTextColour(100,100,255); blue.setText("Blue"); radioButton yellow(&sand,700,35,80,20,&green); yellow.setTextColour(255,255,0); yellow.setText("Yellow"); checkBox bind(&sand,300,70,150,30); bind.setText("Enforce rules"); bind.tag = (void*)&game; bind.addHandler(event_checkchanged,changeRestrict); teamRadioStruct params[5]; radioButton *colours[5] = {&white,&red,&green,&blue,&yellow}; for(int i = 0; i < 5; i++){ params[i] = teamRadioStruct(i,&game); colours[i]->tag = ¶ms[i]; colours[i]->addHandler(event_checkchanged,changeTeam); } white.select(); game.fit(); //adding a save feature. No open yet... Button save(&sand,900,10,80,40); save.text = "Save"; //exit controls Button back(&sand,50,50,100,50); back.text = "Back"; back.addHandler(event_Lclick,sandBack); sand.addHandler(event_quit,sandBack); //keep that label and pause button updated pause.addHandler(event_frameTick,sandPauseButtonText); speedLabel.addHandler(event_frameTick,sandLabelText); sand.startFramerate(20,s); running = true; while(running){ sand.wait(); SDL_Flip(s); } cout<<"Ended"; }
void WitchEntity::animate(float delay) { if (age > 0.0f && !isAgonising) { if (escapeTimer > 0.0f) escapeTimer -= delay; timer -= delay; if (timer <= 0.0f) { if (state == 0) { state = 1; velocity = Vector2D(0.0f, 0.0f); timer = 0.6f; SoundManager::getInstance().playSound(SOUND_WITCH_00 + rand() % 3); if (rand() % 7 == 0) { // invoke int x0 = ((x - OFFSET_X) / TILE_WIDTH); if (x0 < 1) x0 = 1; else if(x0 > MAP_WIDTH - 2) x0 = MAP_WIDTH - 2; x0 = x0 * TILE_WIDTH + TILE_WIDTH / 2; int y0 = ((y - OFFSET_Y) / TILE_HEIGHT); if (y0 < 1) y0 = 1; else if(y0 > MAP_HEIGHT - 2) y0 = MAP_HEIGHT - 2; y0 = y0 * TILE_HEIGHT + TILE_HEIGHT / 2; if (witchType == WitchTypeNormal) new RatEntity(x0, y0, RatEntity::RatTypeNormal, true); else new BatEntity(x0, y0, true); SoundManager::getInstance().playSound(SOUND_INVOKE); for(int i=0; i < 6; i++) { generateStar(sf::Color(200, 50, 200, 255)); generateStar(sf::Color(255, 255, 255, 255)); } } else { // fire fire(); if (witchType == WitchTypeNormal) fire(); } } else if (state == 1) { timer = 3.5f + (rand() % 25) * 0.1f; velocity = Vector2D(creatureSpeed); state = 0; } } if (state == 0) { if (escapeTimer < 0.0f && Vector2D(x, y).distance2(game().getPlayerPosition()) <= 36000) { velocity = game().getPlayerPosition().vectorTo(Vector2D(x, y), creatureSpeed); escapeTimer = 2.5f; } frame = ((int)(age * 5.0f)) % 4; if (frame == 2) frame = 0; else if (frame == 3) frame = 2; if (velocity.x > 1.0f) isMirroring = true; else if (velocity.x < -1.0f) isMirroring = false; } else if (state == 1) { frame = 3; isMirroring = game().getPlayer()->getX() > x; } if (witchType == WitchTypeRed) frame += 8; } EnemyEntity::animate(delay); z = y + 20; }
void combat (emplacement) { //variables FILE* fichier = NULL; char path[50]; long int nombre = 0; long int choix = 1; char nom[35]; long int alea = 1; long min = 1; long max = 0; float degat = 0; float nbaleatoire = 0; long int i = 0; //caracs monstre & joueurs long int monstre_attaque, monstre_endu, monstre_pv, monstre_exp; long int joueur_force, joueur_intelligence, joueur_endurance, joueur_pv, joueur_pv_total; long int joueur_classe = 0; long int joueur_attaque = 0; long int joueur_niv; long int new_niveau = 1; long int niv_actuel = 1; fichier = fopen("monstres/liste.ars", "r+"); fscanf(fichier, "%ld", &nombre); max = nombre; alea = (rand() % (max - min + 1)) + min; //Alea indique le numero du monstre ! // printf("Nombre : %ld\n", alea); sprintf(path, "monstres/monstre%ld.ars", alea); fichier = fopen(path, "r+"); fgets(nom, 35, fichier); printf("Il s\'agit d\'un %s", nom); //Maintenant qu'on a le nom du monstre, on prend ses caracs monstre_attaque = appel_carac_monstre (alea, 2); //INVOCATIOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNN !!!!!! monstre_endu = appel_carac_monstre(alea, 3); //INVOCATION 2222222222222222222222222222222222 !!!!!!!!!!!!!! monstre_pv = appel_carac_monstre(alea, 4); //KAMAHAMEHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!!!!!! monstre_exp = appel_carac_monstre(alea, 5); // printf("Attaque : %ld\nEndu: %ld\npv:%ld\nexp : %ld\n", monstre_attaque, monstre_endu, monstre_pv, monstre_exp); // printf("Attaque : %ld\n", monstre_attaque); //On prend les caracs du persos joueur_force = appel_carac_joueur(emplacement, 5); joueur_intelligence = appel_carac_joueur(emplacement, 6); joueur_endurance = appel_carac_joueur(emplacement, 7); joueur_pv = appel_carac_joueur(emplacement, 8); joueur_pv_total = appel_carac_joueur(emplacement, 9); joueur_niv = appel_carac_joueur(emplacement, 10); joueur_classe = appel_carac_joueur(emplacement, 4); // printf("Attaque : %ld\n", joueur_niv); fclose(fichier); if (joueur_classe == 1) { joueur_attaque = joueur_force ; } else { joueur_attaque = joueur_intelligence ; } printf("\n%s vous attaque !\n",nom); while ((monstre_pv > 0) && (joueur_pv > 0)) { nbaleatoire = floor(((rand() % ((joueur_attaque*5) - 1 + 1)) + 1)/50); degat = (joueur_attaque + nbaleatoire) - monstre_endu; if(degat < 0) degat = 0; printf("Vous attaquez %s et lui infligez %0.0f points de dégats\n", nom, degat); monstre_pv = monstre_pv - degat; nbaleatoire = floor(((rand() % ((monstre_attaque*5) - 1 + 1)) + 1) / 50); degat = (monstre_attaque + nbaleatoire) - joueur_endurance; if(degat < 0) degat = 0; printf("%s vous attaque et vous inflige %0.0f points de dégats\n", nom, degat); joueur_pv = joueur_pv - degat; } if ((monstre_pv <= 0) && (joueur_pv > 0)) { printf("\nVous avez vaincu %s !!! \n", nom); monstre_exp *= 4; printf("\nVous gagnez %ld points d'experience !\n\n", monstre_exp); niv_actuel = joueur_niv; //sauvegarde des xp du joueur // printf("niv_actuel : %ld", niv_actuel); niv_actuel = conversion_xp(niv_actuel); //conversion des xp en niveau avant nouveaux xp joueur_niv = joueur_niv + monstre_exp; //gain de xp du monstre sauvegarde_carac(emplacement, 10, joueur_niv); //On sauvegarde le nombre de xp sauvegarde_carac(emplacement, 8, joueur_pv); // new_niveau = conversion_xp(joueur_niv); //On genere le lvl du perso avec ses nouveaux xp if(niv_actuel < new_niveau) lvl_up(emplacement, new_niveau); } else if((joueur_pv <= 0) && (monstre_pv > 0)) { printf("\nVous avez été vaincu par %s ...\n\n",nom); mort(emplacement); } else { printf("\n Dans une lutte sanglante, vous et %s vous êtes entretués, . \n\n", nom); mort(emplacement); } printf("\nVoulez-vous continuer à jouer (1), ou arrêter (2) ?\n"); scanf("%ld", &choix); if(choix == 1) game(emplacement); else { quitter(); } }
int rien(long emplacement) { printf("Il n\'y a rien ici !\n"); game(emplacement); }
void BrainGameOver::textInput(SDLKey k) { if( k == SDLK_RETURN ) { string s; game()->text().read(BrainText::CENTER,&s,4); if( !s.size() ) { game()->playSample(Brainblast::WARNING); return; } // We are always working on the lowest key // and maps are sorted by key. int id = m_text_queue.begin()->first; m_text_queue.erase(id); for_each(m_text_listeners.begin(),m_text_listeners.end(),text_ready(s,id)); game()->text().clear(BrainText::CENTER); nextTextInput(); return; } // For now only letters and numbers else if( (k >= SDLK_0 && k <= SDLK_9) || (k >= SDLK_a && k <= SDLK_z) ) { string s; game()->text().read(BrainText::CENTER,&s,4); if( s.size() == 8 ) { game()->playSample(Brainblast::WARNING); return; } s += k; game()->text().write(BrainText::CENTER,s,4); game()->playSample(Brainblast::CLICK); } else if( k == SDLK_BACKSPACE ) { string s; game()->text().read(BrainText::CENTER,&s,4); if( s.size() ) { s.resize(s.size()-1); game()->text().write(BrainText::CENTER,s,4); game()->playSample(Brainblast::CLICK); } else game()->playSample(Brainblast::WARNING); } }
void BrainMenu::cleanup() { game()->text().clear(BrainText::CENTER); }
bool BrainTimeBonus::handleEvent(SDL_Event& event) { switch(event.type) { case SDL_KEYDOWN: { if( game()->playerManager().computerPlayers() ) { for(unsigned int i=0; i<game()->playerManager().playerCount(); ++i) { BrainPlayer* p = game()->playerManager().getPlayer(i); if( (p->isComputerPlayer() || p == m_player) && game()->playerManager().isKeyForAction(event.key.keysym.sym, BrainPlayer::SELECT) ) speedyTimeBonus(); } } else if( event.key.keysym.sym == m_player->keyForAction(BrainPlayer::SELECT) ) speedyTimeBonus(); break; } case SDL_TIME_BONUS_EVENT: { int* current = static_cast<int*>(event.user.data2); assert(*current < 1000); if( *current <= 0 ) { // Delete event and stop timer SDL_RemoveTimer(m_time_bonus_timer); m_time_bonus_timer = 0; delete current; if( !game()->changeLevel(game()->getCurrentLevel()+1) ) { changeState(BrainGameOver::instance()); } else { game()->text().write(BrainText::CENTER,"",1); changeState(BrainPlayWait::instance(false)); } } else { ostringstream str; str << "Time Bonus: " << *current; (*current)--; game()->text().write(BrainText::CENTER,str.str(),1); game()->playSample(Brainblast::BOUNCE); BrainPlayer* player = static_cast<BrainPlayer*>(event.user.data1); if( player ) player->addScore(player->getLevel()->brickScore()/10); writeScoreAndTime(0); } } break; } return false; }
void BrainGameOver::init() { game()->text().write(BrainText::CENTER,"Game Over",0); game()->playerManager().gameOver(); game()->clearFloor(); }
void BrainPlaying::cleanup() { game()->forbidNavigation(); SDL_RemoveTimer(m_add_sprite_timer); }
void BrainMenu::titleScreenUpdateText() { game()->text().clear(BrainText::CENTER); game()->text().clear(BrainText::HIGH_SCORE); // Should not be needed, that mode should clear it game()->text().write(BrainText::CENTER,"BRAINBLAST 0.3",0); game()->text().write(BrainText::CENTER,"",1); ostringstream str; str << "F1: Human Players - " << game()->getHumanPlayers(); game()->text().write(BrainText::CENTER,str.str(),2); str.str(""); str << "F2: Computer Players - " << game()->getComputerPlayers(); game()->text().write(BrainText::CENTER,str.str(),3); str.str(""); string set = levelSetToString(game()->getLevelSet()); str << "F3: Level set - " << set; game()->text().write(BrainText::CENTER,str.str(),4); str.str(""); string difficulty = game()->playerManager().difficultyString(); str << "F4: Difficulty - " << difficulty; game()->text().write(BrainText::CENTER,str.str(),5); game()->text().write(BrainText::CENTER,"F5: Highscores",6); game()->text().write(BrainText::CENTER,"",7); game()->text().write(BrainText::CENTER,"SPACE: Start game",8); game()->text().write(BrainText::CENTER,"",9); game()->text().write(BrainText::TOP_CENTER,"",0); }
int main() { srand(time(0)); ResourceHolder<sf::Font, Fonts::ID> fonts; ResourceHolder<sf::Texture, Textures::ID> textures; //ResourceHolder<sf::SoundBuffer, Sounds::ID> sounds; try { fonts.load(Fonts::WhiteRabbit, "Assets/whiterabbit.ttf"); textures.load(Textures::Buttons, "Assets/buttons.png"); textures.load(Textures::Timtam, "Assets/cmcquiz.png"); } catch(std::runtime_error &e) { //would be better off using a log file for release code. return 1; } Window mainWindow(sf::Vector2f(800, 600), "Soft Eng Game"); Button mainPlayButton(textures.get(Textures::Buttons), sf::Vector2f(250, 75), sf::Vector2f(25, 500), sf::IntRect(0, 0, 250, 75), sf::IntRect(0, 75, 250, 75)); Button mainQuitButton(textures.get(Textures::Buttons), sf::Vector2f(250, 75), sf::Vector2f(525, 500), sf::IntRect(0, 150, 250, 75), sf::IntRect(0, 225, 250, 75)); //QuizSelect stuff Button quizMenuContinue(textures.get(Textures::Buttons), sf::Vector2f(250, 75), sf::Vector2f(250, 500), sf::IntRect(0, 300, 250, 75), sf::IntRect(0, 375, 250, 75)); sf::Text selectQuiz("Select Quiz", fonts.get(Fonts::WhiteRabbit), 24); selectQuiz.setPosition(150, 150); sf::Text selectTime("Select Time", fonts.get(Fonts::WhiteRabbit), 24); selectTime.setPosition(500, 150); std::vector<QuestionButton> quizButtons; std::vector<std::string> quizFilenames; Util::getFilenamesInDir(quizFilenames, "Quizes"); for(int i = 0; i < quizFilenames.size(); i++) { quizButtons.push_back(QuestionButton(quizFilenames[i], fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(200, 100), sf::Vector2f(100, 200 +( i * 100)), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); } std::vector<QuestionButton> timerButtons; timerButtons.push_back(QuestionButton("15", fonts.get(Fonts::WhiteRabbit), 48, sf::Vector2f(200, 100), sf::Vector2f(500, 200), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); timerButtons.push_back(QuestionButton("25", fonts.get(Fonts::WhiteRabbit), 48, sf::Vector2f(200, 100), sf::Vector2f(500, 300), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); timerButtons.push_back(QuestionButton("35", fonts.get(Fonts::WhiteRabbit), 48, sf::Vector2f(200, 100), sf::Vector2f(500, 400), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); //EndMenu Stuff Button endRetry(textures.get(Textures::Buttons), sf::Vector2f(250, 75), sf::Vector2f(25, 500), sf::IntRect(0, 450, 250, 75), sf::IntRect(0, 525, 250, 75)); Button endQuit(textures.get(Textures::Buttons), sf::Vector2f(250, 75), sf::Vector2f(525, 500), sf::IntRect(0, 150, 250, 75), sf::IntRect(0, 225, 250, 75)); sf::Vector2f endLogoPos(100, 0); std::vector<QuestionButton> endAnswers; endAnswers.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(640, 120), sf::Vector2f(80, 120), sf::Color(116, 40, 148, 255), sf::Color(116, 40, 148, 255))); endAnswers.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(640, 120), sf::Vector2f(80, 250), sf::Color::Green, sf::Color::Green)); endAnswers.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(640, 120), sf::Vector2f(80, 380), sf::Color::Red, sf::Color::Red)); //MAIN MENU Menu startMenu(mainWindow.getWindow(), mainPlayButton, mainQuitButton, 10, 20, 15, 45, textures.get(Textures::Timtam), sf::Vector2f(75, 200)); bool play = startMenu.run(); while(play) { play = false; //quiz reader, gets a list of quizes from a dir and displays them. //pick one and return with that number. //pick a filename / quiz file. std::string quizFile; //QUIZ CHOICE AND TIMER MENU QuizMenu quizMenu(mainWindow.getWindow(), quizMenuContinue, selectQuiz, selectTime, quizButtons, timerButtons, textures.get(Textures::Timtam), sf::Vector2f(100, 0)); int timeToAns = 0; timeToAns = quizMenu.run(quizFile); //use the quiz at that index. if(timeToAns == 15 || timeToAns == 25 || timeToAns == 35) { //get the list of Q's Quiz quiz = Util::getQuiz("Quizes/" + quizFile, timeToAns); std::vector<QuestionButton> questionButtons; questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(640, 120), sf::Vector2f(80, 210), sf::Color(116, 40, 148, 255), sf::Color(116, 40, 148, 255))); questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(80, 340), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(80, 470), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(420, 340), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(420, 470), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255))); std::vector<AnswerCombo> answers; Game game(&mainWindow.getWindow(), quiz, questionButtons, sf::Sprite(textures.get(Textures::Timtam), sf::IntRect(0, 0, textures.get(Textures::Timtam).getSize().x, textures.get(Textures::Timtam).getSize().y)), fonts.get(Fonts::WhiteRabbit), 32, sf::Color::Black); answers = game.run(); if(answers.size() > 0) { //takes in answers. EndMenu endMenu(&mainWindow.getWindow(), endRetry, endQuit, textures.get(Textures::Timtam), endLogoPos, answers, endAnswers); play = endMenu.run(); } } } return 0; }
Game play_game(const Options& options, Rng& rng) { static const boost::regex re_url("^(?:http://)?([^/]+)(/.*)$"); HTTPConnection connection(options.server_name); connection.proxy = options.proxy; const PTree& initial_json = connection.get_initial_state_json(options); //std::cout << initial_json; boost::match_results<std::string::const_iterator> what; if (!regex_search(initial_json.get<std::string>("playUrl"), what, re_url)) throw std::runtime_error("can't parse play url"); const std::string play_server_name(what[1].first, what[1].second); const std::string play_end_point(what[2].first, what[2].second); const std::string& view_url = initial_json.get<std::string>("viewUrl"); std::cout << "view game at " << view_url << std::endl; double start_time = get_double_time(); if (options.collect_map) { // collect maps const Tiles tiles = get_tiles(initial_json.get_child("game.board")); const HashedPair<Tiles> hashed_tiles(tiles); std::stringstream ss; ss << "map_" << std::hex << hashed_tiles.hash << std::dec << ".txt"; std::cout << "saving " << ss.str() << std::endl; std::ofstream handle(ss.str().c_str()); handle << hashed_tiles.value; handle.close(); } Game game(initial_json); #if defined(BOTUCT) || defined(BOTMULTI) Bot bot(game, options.uct_constant, options.max_mc_depth, rng); #elif defined(BOTRANDOM) Bot bot(game, rng); #else Bot bot(game); #endif #if defined(REPORTING) Reports reports; #endif while (!game.is_finished()) { OmpFlag continue_flag(true); std::cout << std::endl; std::cout << "======================================== " << clock_it(get_double_time() - start_time) << std::endl; game.status(std::cout); std::cout << "++++++++++++++++++++++++++++++++++++++++ " << clock_it(get_double_time() - start_time) << std::endl; #if defined(REPORTING) Report report_aa = bot.crunch_it_baby(game, continue_flag, start_time, TURN_DURATION); report_aa.type = 1; reports.push_back(report_aa); #else bot.crunch_it_baby(game, continue_flag, start_time, TURN_DURATION); #endif const Direction direction = bot.get_move(game); std::cout << "bot direction " << direction << std::endl; bot.advance_game(game, direction); //game.status(std::cout); std::cout << "---------------------------------------- " << clock_it(get_double_time() - start_time) << std::endl; std::cout << "view game at " << view_url << std::endl; PTree new_json; double request_start_time; double request_end_time; #if defined(OPENMP_FOUND) #pragma omp parallel sections default(shared) shared(new_json, request_end_time, request_start_time, continue_flag, play_end_point, play_server_name, start_time, bot, game) { #pragma omp section #endif { request_start_time = get_double_time(); new_json = connection.get_new_state_json(play_end_point, direction); request_end_time = get_double_time(); continue_flag.reset(); } #if defined(OPENMP_FOUND) #pragma omp section { #if defined(REPORTING) Report report_bb = bot.crunch_it_baby(game, continue_flag, start_time, 4); report_bb.type = 2; reports.push_back(report_bb); #else bot.crunch_it_baby(game, continue_flag, start_time, 4); #endif } } #endif game.state.update(new_json); game.update(new_json); std::cout << "request took " << clock_it(request_end_time-request_start_time) << std::endl; //game.status(std::cout); std::cout << "======================================== " << clock_it(get_double_time() - start_time) << std::endl; start_time = get_double_time(); } assert( game.is_finished() ); #if defined(REPORTING) save_report_file(reports, "report.txt"); #endif return game; }
bool BrainMenu::handleEvent(SDL_Event& event) { switch( event.type ) { case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_SPACE: case SDLK_RETURN: changeState(BrainPlayWait::instance(true)); return true; case SDLK_F1: game()->playSample(Brainblast::CLICK); game()->addHumanPlayer(); titleScreenUpdateText(); return true; case SDLK_F2: game()->playSample(Brainblast::CLICK); game()->addComputerPlayer(); titleScreenUpdateText(); return true; case SDLK_F3: game()->playSample(Brainblast::CLICK); switch( game()->getLevelSet() ) { case NORMAL: game()->setLevelSet(RANDOM); break; case RANDOM: game()->setLevelSet(NORMAL); break; default: game()->setLevelSet(NORMAL); break; } titleScreenUpdateText(); return true; case SDLK_F4: game()->playerManager().toggleDifficulty(); titleScreenUpdateText(); return true; case SDLK_F5: changeState(BrainHighScore::instance()); return true; case SDLK_ESCAPE: SDL_Event tb; tb.type = SDL_QUIT; SDL_PushEvent( &tb ); return true; default: // Just skip other keys return true; } } return false; }
int main(int argc, char** argv) { Blackguard::Game game(argc, argv); return game.run(); }
void ChestEntity::open() { isOpen = true; SoundManager::getInstance().playSound(SOUND_CHEST_OPENING); if (chestType == CHEST_BASIC) { int r = 2 + rand() % 6; for (int i = 0; i < r; i++) { ItemEntity* newItem = new ItemEntity(ItemCopperCoin, x, y); newItem->setVelocity(Vector2D(50.0f + rand()% 150)); newItem->setViscosity(0.96f); } // trap ! if (game().getLevel() >= 4) { if (rand() % 6 == 0) timer = 0.5f; } } else if (chestType >= CHEST_FAIRY) { enumItemType itemType = ItemFairy; switch (chestType - CHEST_FAIRY) { case FamiliarFairy: itemType = ItemFairy; break; case FamiliarFairyIce: itemType = ItemFairyIce; break; case FamiliarFairyFire: itemType = ItemFairyFire; break; case FamiliarFairyTarget: itemType = ItemFairyTarget; break; } ItemEntity* newItem = new ItemEntity(itemType, x, y); newItem->setVelocity(Vector2D(50.0f + rand()% 150)); newItem->setViscosity(0.96f); } else if (chestType == CHEST_EXIT) { int r = rand() % 3; if (r == 0) { for (int i = 0; i < 5; i++) { ItemEntity* newItem = new ItemEntity(ItemSilverCoin, x, y); newItem->setVelocity(Vector2D(90.0f + rand()% 150)); newItem->setViscosity(0.96f); } } else if (r == 1) { for (int i = 0; i < 3; i++) { ItemEntity* newItem = new ItemEntity(ItemSilverCoin, x, y); newItem->setVelocity(Vector2D(90.0f + rand()% 150)); newItem->setViscosity(0.96f); } ItemEntity* newItem = new ItemEntity(ItemHealth, x, y); newItem->setVelocity(Vector2D(90.0f + rand()% 150)); newItem->setViscosity(0.96f); } else { int bonusType = game().getRandomEquipItem(false, true); ItemEntity* newItem; if (game().getPlayer()->isEquiped(bonusType)) newItem = new ItemEntity( (enumItemType)(ItemBonusHealth), x ,y); else newItem = new ItemEntity( (enumItemType)(FirstEquipItem + bonusType), x ,y); newItem->setVelocity(Vector2D(90.0f + rand()% 150)); newItem->setViscosity(0.96f); } } }
void piege(emplacement) { FILE* fichier = NULL; long int nbaleatoire = 0; long int nbaleatoire2 = 0; long int i,j, choix = 0; long int evite, degat = 0; char nom[50]; char path[50]; long int taille_max = 50; long int pv = 1; long int nombre = 0; fichier = fopen("pieges/liste.ars", "r+"); fscanf(fichier, "%ld", &nombre); fclose(fichier); nbaleatoire = (rand() % (nombre - 1 + 1)) +1 ; sprintf(path, "pieges/piege%ld.ars", nbaleatoire); fichier = fopen(path, "r+"); fscanf(fichier, "%s\n%ld, %ld", nom, &evite, °at); printf("Il s\'agit d\'un piège mortel nommé %s\n", nom); fclose(fichier); nbaleatoire2 = (rand() % (100 - 1 +1)) +1; if (nbaleatoire2 <= evite) { printf("\nVous avez évité le piège\n"); } else { printf("\nVous n'avez pas réussi à éviter le piège et vous subissez %ld dégats.\n", degat); pv = appel_carac_joueur(emplacement,8); pv = pv - degat; if (pv <= 0) { mort(emplacement); pv = 0; } sauvegarde_carac(emplacement,8,pv); } printf("\nVoulez-vous continuer à jouer (1), ou arrêter (2) ?\n"); scanf("%ld", &choix); if(choix == 1) game(emplacement); else { quitter(); } }
void display() { /* If we are using DGR, send or receive data to keep multiple * processes/computers synchronized. */ dgr_update(); /* Syncronize the DGR objects */ dgr_setget("paddleA", &paddleA, sizeof(Paddle)); dgr_setget("paddleB", &paddleB, sizeof(Paddle)); dgr_setget("ball", &ball, sizeof(Ball)); dgr_setget("planet", planet, sizeof(float)*3); dgr_setget("state", &gameState, sizeof(int)); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); glEnable(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glColor3f(1,1,1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); float frustum[6]; projmat_get_frustum(frustum, -1, -1); glOrtho(frustum[0], frustum[1], frustum[2], frustum[3], frustum[4], frustum[5]); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Pick a depth that is between the near and far planes. float depth = -(frustum[4] + frustum[5])/2.0; // Move the light source GLfloat position[] = { 1.0f, -1.0f, depth+5.5f, 1.0f }; glLightfv(GL_LIGHT0, GL_POSITION, position); // Draw the background stars float masterfrust[6]; projmat_get_master_frustum(masterfrust); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindTexture(GL_TEXTURE_2D, texIdStars); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Draw the background quad with the scrolling star texture float tickmod = ticks / 200.0f; glBegin(GL_QUADS); glTexCoord2f(tickmod+1.0f, -tickmod); glVertex3f(masterfrust[1], masterfrust[3], depth-3.0); glTexCoord2f(tickmod, -tickmod); glVertex3f(masterfrust[0], masterfrust[3], depth-3.0); glTexCoord2f(tickmod, 1.0f-tickmod); glVertex3f(masterfrust[0], masterfrust[2], depth-3.0); glTexCoord2f(tickmod+1.0f, 1.0f-tickmod); glVertex3f(masterfrust[1], masterfrust[2], depth-3.0); glEnd(); //Draw the earth glMatrixMode(GL_MODELVIEW); glPushMatrix(); glBindTexture(GL_TEXTURE_2D, texIdEarth); glTranslatef(planet[0], planet[1], depth-3.0); glRotatef(25.0f, 0.0f, 0.0f, 1.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glRotatef(ticks, 0.0f, 0.0f, 1.0f); ticks += .005; if(ticks > 360.0f)ticks = 0.0f; gluSphere(earth, planet[2]*1.65f, 200, 200); glPopMatrix(); //Draw the clouds glEnable(GL_BLEND); glBlendFunc(GL_SRC_COLOR, GL_DST_COLOR); glPushMatrix(); glBindTexture(GL_TEXTURE_2D, texIdClouds); glLoadIdentity(); glTranslatef(planet[0], planet[1], depth-3.0); glRotatef(25.0f, 0.0f, 0.0f, 1.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glRotatef(ticks, 1.0f, 0.0f, 1.0f); gluSphere(clouds, planet[2]*1.652f, 200, 200); glPopMatrix(); // Reset somethings for the rest of the scene glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // top player (player 1) paddle drawPaddle(paddleA, depth+5.0f); // bottom player (player 2) paddle drawPaddle(paddleB, depth+5.0f); glDisable(GL_BLEND); // ball glEnable(GL_LIGHTING); glColor3fv(ball.color); glPushMatrix(); glTranslatef(ball.xpos, ball.ypos, depth+4.0f); glutSolidSphere(ball.radius, 100, 100); glPopMatrix(); /* If DGR is enabled, only do this in the master*/ if(dgr_is_enabled() == 0 || dgr_is_master()) { // Run the game code game(); } glFlush(); glutSwapBuffers(); glutPostRedisplay(); // call display() repeatedly }
int main(int argc, char** argv) { bool hasFocus = true; srand(time(NULL)); printf("build time %s\n",__TIME__); path = argv[0]; path = path.substr(0,path.rfind("/")); path = path.substr(0,path.rfind("/")); path += "/Resources/"; appConf = new INIReader(path+"settings.ini"); sf::RenderWindow window(sf::VideoMode(window_width, window_height), "Asteroid",sf::Style::Titlebar | sf::Style::Close); main_window = &window; window.setVerticalSyncEnabled(true); window.setKeyRepeatEnabled(false); sf::Clock clock; AsteroidGame game(800,600); currentScreen = &game; int elapsedTimeMS = 0; while (window.isOpen() && currentScreen != 0) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } else if(event.type == sf::Event::GainedFocus) { hasFocus = true; } else if(event.type == sf::Event::LostFocus) { hasFocus = false; } else { if(hasFocus) { currentScreen->handleEvent(event); } } } if(elapsedTimeMS >0) { if(hasFocus) { currentScreen->update(elapsedTimeMS); } } window.setActive(true); window.clear(sf::Color::Black); currentScreen->display(&window); window.display(); elapsedTimeMS = clock.restart().asMilliseconds(); if(currentScreen->isScreenFinished()) { currentScreen = currentScreen->getNextScreen(); } } return 0; }
int main() { game game(0); }
int main(void) { int state = SPLASH; int response = 1; while(1) { switch(state) { case SPLASH: lives = 3; response = splash(); if(response == 1) { state = SPLASH; } else state = GAME; break; case GAME: response = game(); if(response ==1) state = SPLASH; else if(response == 2) //restart game { state = GAME; lives--; } else if (response == 3) //nextLevel { state = NEXT; } if(lives == 0) { state = LOSE; } break; case NEXT: response = next(); if(response == 1) state = SPLASH; else if (response == 2) { state = NEXT; lives--; } else if(response ==3) { state = WIN; } if(lives ==0) { state = LOSE; } break; case WIN: response = win(); if(response == 1) state = SPLASH; break; case LOSE: response = lose(); if(response == 1) state = SPLASH; default: break; } } }
/*======================================================================* TestA *======================================================================*/ void TestA() { int fd; int i, n; char tty_name[] = "/dev_tty0"; char rdbuf[128]; int fd_stdin = open(tty_name, O_RDWR); assert(fd_stdin == 0); int fd_stdout = open(tty_name, O_RDWR); assert(fd_stdout == 1); // char filename[MAX_FILENAME_LEN+1] = "zsp01"; const char bufw[80] = {0}; // const int rd_bytes = 3; // char bufr[rd_bytes]; clear(); long int ii = 9999; printf(" \n");while(ii-->0);ii=9999; printf(" ## D## ### .## \n"); printf(" ## D## W## :## \n"); printf(" ## G## ### .## \n"); printf(" ## G## ### .## \n"); printf(" ## G## ### .## \n"); printf(" ## G## ### .## \n"); printf(" ## D## L###K ### .## ##W# . \n"); printf(" ## G## j#######i ### .## .######## \n"); printf(" ########### ##t .W## W## .## ### W##D \n"); printf(" ########### ##D ### W## .## D## ## \n"); printf(" ## G## .## ### W## .## ##E ##. \n"); printf(" ## G## .########### W## .## ## ##E \n"); printf(" ## D## :## W## .## ## ##E \n"); printf(" ## G## .## W## .## ## ##G \n"); printf(" ## G## ##. f## W## .## ##K ## \n"); printf(" ## G## ###. ### W## .## i#W ;## \n"); printf(" ## G## ###, ###. W## .## #### .###: \n"); printf(" ## D## #######: W## :## #######: \n"); printf(" K## . . . i## . \n\n"); startAnimate(); clear(); disp_color_str(" \n\n ==================================\n",5); disp_color_str(" Kernel on Orange's \n\n",3); disp_color_str(" Welcome !\n",4); disp_color_str(" ====================================",5); while (1) { printf("\n\n\n\n\n\n command:"); int r = read(fd_stdin, rdbuf, 70); rdbuf[r] = 0; //show(); if (strcmp(rdbuf, "process") == 0) { ProcessManage(); } else if (strcmp(rdbuf, "filemng") == 0) { printf("File Manager is already running on CONSOLE-1 ! \n"); continue; }else if (strcmp(rdbuf, "help") == 0) { help(); } else if (strcmp(rdbuf, "timer") == 0) { timer(fd_stdin, fd_stdout); } else if(strcmp(rdbuf, "game") == 0){ clear(); game(fd_stdin, fd_stdout); } else if (strcmp(rdbuf, "clear") == 0) { clear(); printf(" ==================================\n"); printf(" Kernel on Orange's \n\n"); printf(" Welcome !\n"); printf(" ==================================\n"); } else printf("Command not found, please check!\n"); } }
void CyclopsEntity::computeStates(float delay) { timer -= delay; if (timer <= 0.0f) { if (state == 0) // walking { if (counter > 0) { counter--; timer = 0.5f; creatureSpeed = CYCLOP_SPEED[getHealthLevel()]; setVelocity(Vector2D(x, y).vectorTo(game().getPlayerPosition(), creatureSpeed )); } else { velocity.x = 0.0f; velocity.y = 0.0f; if (destroyLevel < getHealthLevel()) { state = 3; // charge to destroy destroyLevel++; counter = destroyLevel + 1; timer = 0.9f; SoundManager::getInstance().playSound(SOUND_CYCLOP_00); initFallingGrid(); } else { state = 1; // charge to fire timer = 0.9f; counter = CYCLOP_NUMBER_ROCKS[getHealthLevel()]; SoundManager::getInstance().playSound(SOUND_CYCLOP_00); computeNextRockMissile(); } } } else if (state == 1) // fire { state = 2; fire(); timer = CYCLOP_FIRE_DELAY[getHealthLevel()]; } else if (state == 2) // fire end { if (counter <= 1) { state = 0; timer = 0.2f; counter = 10; } else { counter--; state = 1; timer = 0.2f; computeNextRockMissile(); } } else if (state == 3) { state = 4; // destroy timer = 0.2; game().makeShake(0.4f); SoundManager::getInstance().playSound(SOUND_CYCLOPS_IMPACT); for (int i = 0; i < 10 ; i++) fallRock(); } else if (state == 4) { if (counter <= 1) { state = 0; timer = 0.2f; counter = 10; } else { counter--; state = 3; timer = 0.3f; } } } }
main() { int game(int cm1, int cm2); setlocale (LC_ALL,"Russian"); int i=0, j=0, cm1, cm2, tomenu, flag=0, qw=0; FILE *f; char fn[15]; f=fopen("albase.txt","r"); for(i=0;i<n;i++) { fscanf(f,"%d%s%d",&base[i].ID, &base[i].name, &base[i].type); base[i].UID=0; } fclose(f); f=fopen("typebase.txt","r"); for(i=0;i<lo;i++) { fscanf(f,"%s",&types[i]); } fclose(f); /*for(i=0;i<n;i++) { printf("%2d %2d %15s ",base[i].ID, base[i].UID, base[i].name); printf("\n"); }*/ int menu1, exit1=0; char buf[2]; setlocale(LC_ALL, "Russian"); while(exit1==0) { system("cls"); puts(""); puts(" ~~..++НЕДОАЛХИМИЯ++..~~"); puts(" _____________________"); puts(" | ++Главное Меню++ |"); puts(" |_____________________|"); puts(" |1|Новая Игра |"); puts(" |_____________________|"); puts(" |2|Загрузить |"); puts(" |_____________________|"); puts(" |3|Сохранить |"); puts(" |_____________________|"); puts(" |4|Прогресс и |"); puts(" | АЧИВКИ :D |"); puts(" |_____________________|"); puts(" |5|Продолжить игру |"); puts(" |_____________________|"); puts(" |6|Выход |"); puts(" |_____________________|"); do { scanf("%s",&buf); menu1=atoi(buf); }while(!menu1); switch(menu1) { case 1: { tomenu=0, kol=0; f=fopen("combase.txt","r"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { fscanf(f,"%d",&combase[i][j]); } } fclose(f); id=1; for(i=0;i<4;i++) { usbase[i]=base[i]; usbase[i].UID=id; kol++; id++; } system("cls"); puts("У вас есть 4 элемента, комбинируйте их и получайте новые"); qsort((void *)usbase, kol, sizeof(alch), elem_cmp); outp(kol); while(tomenu==0) { puts("Введите номера комбинируемых элементов или два раза -1 для выхода в главное меню"); scanf("%d%d",&cm1,&cm2); tomenu=game(cm1,cm2); } } break; case 2: system("cls"); puts("Введите имя файла, который загрузить"); fflush(stdin); gets(fn); f=fopen(fn,"r"); qw=0; if(f) qw=1; else { puts("Файл не найден"); getch(); system("cls"); } if(qw==1) { fscanf(f,"%d",&kol); printf("SYSYEM: kol=%d\n",kol); for(i=0;i<kol;i++) { fscanf(f,"%d %d %s",&usbase[i].ID, &usbase[i].UID, &usbase[i].name); } for(i=0;i<n;i++) { for(j=0;j<n;j++) { fscanf(f,"%d",&combase[i][j]); } } tomenu=0; system("cls"); puts("Игра успешно загружена."); qsort((void *)usbase, kol, sizeof(alch), elem_cmp); outp(kol); while(tomenu==0) { id=kol+1; puts("Введите номера комбинируемых элементов или два раза -1 для выхода в главное меню"); scanf("%d%d",&cm1,&cm2); tomenu=game(cm1,cm2); } } break; case 3: system("cls"); puts("Введите имя файла, в который сохранить"); fflush(stdin); gets(fn); f=fopen(fn,"w"); fprintf(f,"%d\n",kol); for(i=0;i<kol;i++) { fprintf(f,"%d %d %s",usbase[i].ID, usbase[i].UID, usbase[i].name); fprintf(f,"\n"); } for(i=0;i<n;i++) { for(j=0;j<n;j++) { fprintf(f,"%2d",combase[i][j]); if(j!=n-1); fprintf(f," "); } if(i!=n-1) fprintf(f,"\n"); } break; case 4: { float m=n; progr=(kol/m)*100; system("cls"); puts("Прогресс и достижения"); printf("|"); for(i=0;i<progr/2;i++) { printf("|"); } for(i=0;i<50-progr;i++) { printf(" "); } printf("|\n"); printf(" %.1f %% (%d/%.0f)",progr, kol, m); getch(); } break; case 5: { system("cls"); qsort((void *)usbase, kol, sizeof(alch), elem_cmp); outp(kol); tomenu=0; while(tomenu==0) { id=kol+1; puts("Введите номера комбинируемых элементов или два раза -1 для выхода в главное меню"); scanf("%d%d",&cm1,&cm2); tomenu=game(cm1,cm2); } } break; case 6: exit1=1; break; /*case 7: f=fopen("mmm.txt","w"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { fprintf(f,"%4d",combase[i][j]); if(j!=n-1); fprintf(f," "); } if(i!=n-1) fprintf(f,"\n"); } fclose(f); break;*/ } } return(0); }
int main(int argc, char ** argv) { // Checking args if(argc > 1) return FAILURE; std::cout << "\nRunning program : " << argv[0] << "\n" << std::endl; // Starting load of heavy resources // Launching thread ResourceLoader rLoader(DEBUG); rLoader.start(); // Creating window sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), WINDOW_NAME, sf::Style::Titlebar); // Window framerate - Default : 120 fps window.setFramerateLimit(WINDOW_FPS); // Starting some videos while loading res SplashScreen splash(DEBUG); //splash.start(&window); // Getting loaded resources // Wait if not finished while(!rLoader.getLoadState()) sf::sleep(sf::milliseconds(WAIT_TIME)); ManagerGroup * managerGroup = rLoader.getManager(); // Creating menu LoginMenu loginMenu(DEBUG, managerGroup); //Creating lobby Lobby lobby(DEBUG, managerGroup); //Creating warmUp WarmUp warmUp(DEBUG, managerGroup); //Creating Game Game game(DEBUG, managerGroup); // Setting main target managerGroup->ptr_targetManager->isOnLoginMenu(); sf::Clock clock; while (window.isOpen()) { // Exiting program if(!managerGroup->ptr_targetManager->isExit()) { managerGroup->ptr_musicManager->stopPlaylist(); window.close(); continue; } double elapsedTime = clock.getElapsedTime().asSeconds(); clock.restart().asMilliseconds(); window.clear(); sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } // Updating game logic loginMenu.update(&window, &event, elapsedTime); lobby.update(&window, &event, elapsedTime); warmUp.update(&window, &event, elapsedTime); game.update(&window, &event, elapsedTime); managerGroup->ptr_musicManager->update(); window.display(); } return SUCCESS; }
int main(int argc, char** argv){ srand( (unsigned)time( NULL ) ); initializeGame(); game(); return 0; }
// Export connection-related stuff. void export_connect() { enum_<LOGMODE>("LOGMODE") .value("NONE", NONE) .value("SCREEN", SCREEN) .value("DISK", DISK) .value("SYSLOG", SYSLOG); // class_<Common, boost::noncopyable> common("Common", no_init); { // common.def("logError", &simplify_log_function<Common::logError>); // common.def("logInfo", &simplify_log_function<Common::logInfo>); // common.def("logDebug", &simplify_log_function<Common::logDebug>); // common.def("logWarning", &simplify_log_function<Common::logWarning>); // common.def("log", &Common::log); // common.def("setLogMode", &Common::setLogMode); // common.def("setLogFilename", &Common::setLogFilename); } class_<FXClient> client("FXClient"); { client.add_property("version", &FXClient::version); client.def("login", &FXClient::login); client.def("logout", &FXClient::logout); client.def("isLoggedIn", &FXClient::isLoggedIn); client.def("setTimeout", &FXClient::setTimeout); // client.add_property("timeout", &FXClient::timeout); // (Removed because redundant and confusing.) client.def("setLogfile", &FXClient::setLogfile); client.def("getWithRateThread", &FXClient::getWithRateThread); client.def("setWithRateThread", &FXClient::setWithRateThread); client.add_property("withRateThread", &FXClient::getWithRateThread, &FXClient::setWithRateThread); client.def("getWithKeepAliveThread", &FXClient::getWithKeepAliveThread); client.def("setWithKeepAliveThread", &FXClient::setWithKeepAliveThread); client.add_property("withKeepAliveThread", &FXClient::getWithKeepAliveThread, &FXClient::setWithKeepAliveThread); client.def("getWithLoadableKey", &FXClient::getWithLoadableKey); client.def("setWithLoadableKey", &FXClient::setWithLoadableKey); client.add_property("withLoadableKey", &FXClient::getWithLoadableKey, &FXClient::setWithLoadableKey); client.def("getServerTime", &FXClient::getServerTime); // Note: I'm assuming that we don't have to manage the lifespan of the // returned user object here. client.def("getUser", &FXClient::getUser, return_value_policy<reference_existing_object>()); client.def("getRateTable", &FXClient::getRateTable, return_value_policy<reference_existing_object>()); // We don't need to export this, there are several substitute elsewhere. // static DateString timestampToString(time_t stamp) } class_<FXGame, bases<FXClient> > game("FXGame"); class_<FXTrade, bases<FXClient> > trade("FXTrade"); class_<User> user("User", no_init); { user.add_property("userId", &User::userId); user.add_property("createDate", &User::createDate); user.add_property("name", &User::name); user.add_property("email", &User::email); user.add_property("address", &User::address); user.add_property("telephone", &User::telephone); const char*(User::*user_getprofile)() const = &User::profile; void(User::*user_setprofile)(char*) = &User::profile; user.add_property("profile", user_getprofile, user_setprofile); user.def("getAccounts", User__getAccounts); user.def("getAccountWithId", &User::getAccountWithId, return_value_policy<reference_existing_object>()); } class_<Account> account("Account", no_init); { account.def("__str__", &Account__str__); account.add_property("accountId", &Account::accountId); account.add_property("accountName", &Account::accountName); account.add_property("createDate", &Account::createDate); account.add_property("homeCurrency", &Account::homeCurrency); account.add_property("marginRate", &Account::marginRate); account.add_property("balance", &Account::balance); account.def("realizedPL", &Account::realizedPL); account.def("unrealizedPL", &Account::unrealizedPL); account.def("marginUsed", &Account::marginUsed); account.def("marginAvailable", &Account::marginAvailable); account.add_property("profile", Account__profile); account.def("eventManager", &OanPy::Account__eventManager); // return_value_policy<manage_new_object>()); // Order execution. void (Account::*execute_limit)(LimitOrder& anorder) = &Account::execute; account.def("execute", Account__execute_market); account.def("execute", execute_limit); // Order close. MarketOrder (Account::*close_market)(const MarketOrder&) = &Account::close; void (Account::*close_limit)(const LimitOrder&) = &Account::close; void (Account::*close_position)(const char*) = &Account::close; account.def("close", close_market); account.def("close", close_limit); account.def("close", close_position); // Order modify. void (Account::*modify_market)(const MarketOrder&) = &Account::modify; void (Account::*modify_limit)(const LimitOrder&) = &Account::modify; account.def("modify", modify_market); account.def("modify", modify_limit); // Access to orders and positions. account.def("getTrades", Account__getTrades); account.def("getTradeWithId", &Account::getTradeWithId); account.def("getOrders", Account__getOrders); account.def("getOrderWithId", &Account::getOrderWithId); account.def("getPositions", Account__getPositions); account.def("getPosition", &Account::getPosition); account.def("getTransactions", Account__getTransactions); account.def("getTransactionWithId", &Account::getTransactionWithId); } }
int main(int argc, char *argv[]) { Game game(argc, argv); return game.exec(); }