Score *Match::play( Player *p ) { MatchScore *matchScore = new MatchScore( player1(), player2() ); while ( !matchScore->haveAWinner() ) { Set *set = new Set( player1(), player2() ); Score *setScore = set->play( player1() ); matchScore -> addScore(setScore); delete set; p = p -> otherPlayer(p); } return matchScore; }
Score *TieBreaker::play( Player *p ) { //switches player if necessary bool switchPlayer = false; //create a tiebreaker instance TieBreakerScore *s = new TieBreakerScore(player1(),player2()); // serve a point get the winner of the point s->addScore(reinterpret_cast<PointScore *>(p->serveAPoint())->getWinner()); // switch players p = p->otherPlayer(p); // check for a winner while (!s->haveAWinner()) { // if no winner, proceed with the game s->addScore(reinterpret_cast<PointScore *>(p->serveAPoint())->getWinner()); // and switch when necessary if (switchPlayer) p = p->otherPlayer(p); switchPlayer = !switchPlayer; } return s; }
int main(int argc, const char * argv[]) { Board board; board[3][3] = WHITE; board[3][4] = BLACK; board[4][3] = BLACK; board[4][4] = WHITE; printBoard(board); pair<int, int> move; for (int i = 0; i < 32; i++) { TeamNULL player1(BLACK); TeamNULL player2(WHITE); player1.move(board, move); // board = moveObj.board; // printBoard(board); player2.move(board, move); // board = moveObj.board; // printBoard(board); } return 0; }
int main(int argc, char** argv) { if(argc <= 1){ std::cout << "Please input filename" << std::endl; return -1; } try{ SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO); SDLVideoFairy videoFairy("Cycloa"); SDLAudioFairy audioFairy; SDLGamepadInfo info; SDLGamepadFairy player1(info); VirtualMachine vm(videoFairy, audioFairy, &player1, 0); vm.loadCartridge(argv[1]); vm.sendHardReset(); while(true){ vm.run(); } SDL_Quit(); }catch(EmulatorException& e){ std::cerr << "Error: " << e.getMessage(); std::cerr << std::endl; std::cerr.flush(); return -1; } catch (...) { std::cerr << "Unknown Error..."; std::cerr << std::endl; std::cerr.flush(); return -2; } return 0; }
void Hud::display(int PlayerTurn) { Text text("Heroes tsy", hudFont); text.setPosition(view->getCenter().x - 290, view->getCenter().y - 300); text.setCharacterSize(15); text.setColor(Color::White); window->draw(text); window->draw(text1); window->draw(text2); if (PlayerTurn == 0) { Text player1("Player1", hudFont); player1.setPosition(view->getCenter().x - 290, view->getCenter().y - 250); player1.setCharacterSize(15); player1.setColor(Color::White); window->draw(player1); } if (PlayerTurn == 1) { Text player2("Player2", hudFont); player2.setPosition(view->getCenter().x + 150, view->getCenter().y - 250); player2.setCharacterSize(15); player2.setColor(Color::White); window->draw(player2); } }
int main () { std::cout << "New game:\n"; Player player1 ("Bob", "builder", 1, 1, 1); player1.create_new(); std::cout << "Test spells:\n"; player1.cast_spell(); return 0; }
void game::handle_events() {player player1(IMG_Load("megaman.gif")); SDL_Event event; while(SDL_PollEvent (&event)) { switch(event.type) { case SDL_QUIT: run=false; break; case SDL_KEYDOWN: switch(event.key.keysym.sym) {case SDLK_LEFT: direction[0]=1; break; case SDLK_RIGHT: direction[1]=1; break; case SDLK_SPACE: direction[2]=1; break; case SDLK_e: gun=1; break; } break; case SDL_KEYUP: switch(event.key.keysym.sym) {case SDLK_LEFT: direction[0]=0; break; case SDLK_RIGHT: direction[1]=0; break; case SDLK_SPACE: direction[2]=0; break; case SDLK_e: gun=0; break; } break; } } }
// Implemented by David Wells Score *Set::play( Player *p ) { // Create a score object for this SET SetScore *setScore = new SetScore(player1(), player2()); // While we don't have a winner of the Set, continue playing games. while( !setScore -> haveAWinner() ) { // Create a new game and score object Game *game = new Game( player1(), player2() ); // Start playing the game Score *gameScore = game->play(p); // Get the winner from the game and add the points from the game setScore -> addScore( gameScore -> getWinner() ); // Delete the game, and free up memory because the game is over delete game; // After the game switch servers p = p->otherPlayer(p); // If we have a TIE, play a tiebreaker! if( setScore->shouldPlayATieBreaker() ) { // create a new tiebreaker object with player 1 and player 2 TieBreaker *tiebreaker = new TieBreaker (player1(), player2() ); // We'll add the tiebreaker score to score, but we'll need to cast the result of playing a tiebreaker to the same type. setScore -> addTieScore( reinterpret_cast<TieBreakerScore *>(tiebreaker -> play(p))); // Now that we've settled the tie, we can return out of the set return setScore; } } return setScore; }
int main(){ FragTrap player1("the virgine"); FragTrap player2(player1); player2 = player1; player1.vaulthunter_dot_exe("mouton"); player2.takeDamage(25); return 0; };
void game::start() {int i=0; player player1(IMG_Load("megaman.gif")); Uint32 start; while(run) {start=SDL_GetTicks(); handle_events(); if(direction[2]) { player1.setjump(); } if(direction[0]) {if(player1.getrect()->x>0) player1.setxvel(-1); else { camera.x--; base::coord.x--; } if(camera.x<=0) {camera.x++;base::coord.x++;} } else if(direction[1]) { {if(player1.getrect()->x<60) player1.setxvel(1); else { player1.setxvel(0); camera.x++; base::coord.x++; } if(camera.x>1280-640) camera.x=0; } } else player1.setxvel(0); SDL_BlitSurface(back,&camera,screen,NULL); player1.move(); if(gun) bullets=(new bullet(fire,player1.getrect()->x+player1.getrect()->w-11,player1.getrect()->y+15,10,0)); bullets->move(); player1.showplayer(); showmap(); bullets->show(); SDL_Flip(screen); if(1000/30>(SDL_GetTicks()-start)) SDL_Delay(1000/30-(SDL_GetTicks()-start)); } }
Score *Game::play( Player *p ) { Score *score = new GameScore( player1(), player2() ); while( !score->haveAWinner() ) { PointScore *pointScore = reinterpret_cast<PointScore *>( p->serveAPoint() ); score->addScore( pointScore->getWinner() ); delete pointScore; } return score; }
int main(void) { // EXERCISE 2 Player player1(10); player1.set_name("John"); Player player2(15); player2.set_name("Fred"); cout << player1.get_name() << " has " << player1.get_hit_points() << " health" << endl; cout << player2.get_name() << " has " << player2.get_hit_points() << " health" << endl << endl; // EXERCISE 3 BST* bst = new BST(); bst->insertInteger(18); bst->insertInteger(8); bst->insertInteger(3); bst->insertInteger(23); bst->insertInteger(11); bst->printTree(); cout << "Is 11 in BST? " << bst->searchTree(11) << endl; cout << "Is 5 in BST? " << bst->searchTree(5) << endl << endl; bst->deleteValue(18); bst->printTree(); // EXERCISE 4 Battleship* battleship = new Battleship(); battleship->play(); // TUTORIAL CODE Enemy e1(2); cout << "hit points = " << e1.get_hit_points() << "\n"; Enemy* e2 = new Enemy(2); e2->set_hit_points(3); cout << "hit points = " << e2->get_hit_points() << "\n"; e2->set_score(2); cout << "score = " << e2->get_score() << "\n"; delete e2; e2 = NULL; cout << endl << "Enter a number to exit..." << endl; int exit; cin >> exit; return 0; }
int memoize(int a,int b,vector<int> &v,int **M,vector<int> &sum,int player){ if(M[a][b]>0) return M[a][b]; int oppprofit=0; if(player==1) oppprofit=player2(a,b,v,M,sum); else oppprofit=player1(a,b,v,M,sum); if(a==0) M[a][b]=sum[b]-oppprofit; else M[a][b]=sum[b]-sum[a-1]-oppprofit; return M[a][b]; }
int main() { int turn = 1; int health; srand(time(NULL)); std::cout << "\nFANTASY COMBAT TEST GAME\n" << std::endl; std::cout << "\nList of Creatures\n" << std::endl; std::cout << "1) Goblin" << std::endl; std::cout << "2) Barbarian" << std::endl; std::cout << "3) Reptile People" << std::endl; std::cout << "4) Blue Men" << std::endl; std::cout << "5) The Shadow\n" << std::endl; Goblin player1(); Goblin player2(); while ((player1.getHealth() > 0) && (player2.getHealth() > 0)) { if (turn == 1) { health = player2.defense(player1.attack()); turn = 2; if (health < 1) { std::cout << "Player 2 is DEAD" << std::endl; exit (EXIT_SUCCESS); } else std::cout << "Player 2 has " << health << " health points left." << std::endl; } else { health = player1.defense(player2.attack()); turn = 1; if (health < 1) { std::cout << "Player 1 is DEAD" << std::endl; exit (EXIT_SUCCESS); } else std::cout << "Player 1 has " << health << " health points left." << std::endl; } } return 0; }
int Solution::maxcoin(vector<int> &A) { int n=A.size(),i,j; int **M=new int *[n]; for(i=0;i<n;i++) M[i]=new int[n]; for(i=0;i<n;i++) for(j=0;j<n;j++) M[i][j]=-1; vector<int> sum; sum.push_back(A[0]); for(i=1;i<n;i++) sum.push_back(A[i]+sum[i-1]); return player1(0,n-1,A,M,sum); }
int main(int argc, char *argv[]) { Game game; ConsoleBoard board(&game); ConsoleNotification notification; ConsolePlayer player1(&game, "First"); ComputerPlayer player2(&game, "Second"); game.setBoard(&board); game.setNotification(¬ification); game.setPlayer1(&player1); game.setPlayer2(&player2); game.startNewGame(); return 0; }
game::game() { SDL_Init(SDL_INIT_EVERYTHING); screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE|SDL_DOUBLEBUF); block=load("brick_f.png"); back=load("level.png"); fire=load("bullet.png"); base::coord.x=camera.x=0; base::coord.y=camera.y=0; base::coord.h=camera.h=480; base::coord.w=camera.w=640; frame1=6; frame2=0; player player1(IMG_Load("megaman.gif")); direction[2]=direction[0]=direction[1]=0; gun=0; run=true; }
int main(){ Player player1(0, 410); sf::RenderWindow window(sf::VideoMode(800, 600), "New Game"); sf::Texture stage1; stage1.loadFromFile("background.png"); sf::Sprite background; background.setTexture(stage1); sf::Music music; music.openFromFile("music.wav"); music.play(); while(window.isOpen()){ sf::Event event; while(window.pollEvent(event)){ if(event.type == sf::Event::Closed) window.close(); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){ if(sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)){ player1.moveRight(12); } else{ player1.moveRight(7); } } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){ if(sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)){ player1.moveLeft(12); } else{ player1.moveLeft(7); } } } window.clear(); window.draw(background); window.draw(player1.getPlayerSprite()); window.display(); } return 0; }
Score *Game::play( Player *p ) { /**** Derived function of play from base Competition class. Driver for a match between the two players. ****/ //creates new instance of score (0-0 game) Score *score = new GameScore( player1(), player2() ); int i = 0; while( !score->haveAWinner() ) { /**** Checks to see if either of the players has won yet. If not, it creates a new PointScore object and has a player server, which will result in a point. ****/ PointScore *pointScore; pointScore = reinterpret_cast<PointScore *>( p->serveAPoint() ); score->addScore( pointScore->getWinner() ); delete pointScore; //delete the player point } //returns the score of a game between two players return score; }
void WagonSelect::setup_player1_mactchdata() { rapidjson::Document doc; doc.SetObject(); rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); doc.AddMember("turn", 1, allocator); rapidjson::Value player1(rapidjson::kObjectType); player1.AddMember("name", g_gameConfig.player1Name.c_str(), allocator); player1.AddMember("wagon", _wagon, allocator); player1.AddMember("male", _isBoy, allocator); player1.AddMember("hp", g_wagonConfig[_wagon].hp, allocator); player1.AddMember("posx", 229, allocator); player1.AddMember("posy", 513, allocator); player1.AddMember("rot", 0, allocator); player1.AddMember("shootangle", "", allocator); player1.AddMember("facing", "right", allocator); doc.AddMember("player1", player1, allocator); srand((unsigned)time(NULL)); srand(rand()); doc.AddMember("windx", CCRANDOM_MINUS1_1()*0.025, allocator); srand(rand()); doc.AddMember("windy", CCRANDOM_MINUS1_1()*0.025, allocator); rapidjson::Value array(rapidjson::kArrayType); doc.AddMember("explosions", array, allocator); rapidjson::Value actions(rapidjson::kArrayType); doc.AddMember("actions", actions, allocator); rapidjson::StringBuffer strbuf; rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); doc.Accept(writer); g_gameConfig.match_string = strbuf.GetString(); }
int main(int argc,char *argv[]) { Init(); std::vector<cBullet> bullets; //all the bullets std::vector<SDL_Rect> objects; //add enemy rects (or rects, which should stop a bullet) at the end of this vector //if you later create a class for the enemies, you should make the type that (but change in the bullet update function too //you can make different for enemies and tiles, which the bullet cannot go through cTile map; cTile colmap; Uint32 color = SDL_MapRGB(screen->format,45,39,12); SDL_Rect playerRect; Camera cam; cPlayer player1(50,50,60,60,&playerRect); player = SDL_LoadBMP("Images/player.bmp"); SDL_Surface* tiles[2]; SDL_Rect bulletRect[2]; bulletRect[0].x = playerRect.x; bulletRect[0].y = playerRect.y; bulletRect[0].w = 10; bulletRect[0].h = 10; tiles[0] = SDL_LoadBMP("Images/tile2.bmp"); tiles[1] = SDL_LoadBMP("Images/tile1.bmp"); SDL_Surface* bulletimage=SDL_LoadBMP("Images/bullet.bmp"); SDL_SetColorKey(bulletimage,SDL_SRCCOLORKEY,SDL_MapRGB(bulletimage->format,255,0,255)); map.LoadMap("Maps/map.txt"); colmap.LoadMap("Maps/colmap.txt"); bool direction[4]= {0,0,0,1}; //top,right,bottom,left, this is where the player looks int spx=0; int spy=0; while(running) { SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: running = false; break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: return 0; break; case SDLK_SPACE: //determine the speed (depending, where the player looks) if(direction[0]) //up { spx=0; spy=-10; } else if(direction[1]) //left { spx=10; spy=0; } else if(direction[2]) //down { spx=0; spy=10; } else //right { spx=-10; spy=0; } bullets.push_back(cBullet(spx,spy,playerRect.x,playerRect.y,10,bulletimage)); break; case SDLK_UP: move[0] = 1; direction[0]=1; direction[1]=direction[2]=direction[3]=false; break; case SDLK_RIGHT: move[3] = 1; direction[1]=1; direction[0]=direction[2]=direction[3]=false; Shoot[0] = 1; break; case SDLK_DOWN: move[2] = 1; direction[2]=1; direction[0]=direction[1]=direction[3]=false; break; case SDLK_LEFT: direction[3]=1; direction[1]=direction[2]=direction[0]=false; move[1] = 1; break; } break; case SDL_KEYUP: switch(event.key.keysym.sym) { case SDLK_UP: move[0] = 0; break; case SDLK_RIGHT: move[3] = 0; break; case SDLK_DOWN: move[2] = 0; break; case SDLK_LEFT: move[1] = 0; break; } break; } } cam.x = playerRect.x - screen->w/2; cam.y = playerRect.y - screen->h/2; map.RenderMap(screen,tiles); player1.Movement(&playerRect,1); colmap.SetCollisionMap(&playerRect,move,1); //BlitSurface(player,screen,playerRect.x - cam.x,playerRect.y - cam.y); player1.Show(player,&playerRect); SDL_FillRect(screen,&bulletRect[1],color); for(int i=0; i<bullets.size(); i++) { int j=bullets[i].update(objects); if(j==-2) { //out of the screen bullets.erase(bullets.begin()+i); } else if(j>=0) { //bullet hit the ith object, here you could decrease the enemy's health bullets.erase(bullets.begin()+i); } bullets[i].show(); } SDL_Flip(screen); } }
void main() { //************************************ Create team 1 ********************************* //Create players for team 1 Person person1("Eran Zahavi", 21); StaffMember staff1(person1, 20000, 3); Player player1(staff1, Player::STRICKER, 8); Person person2("Yoav Ziv", 26); StaffMember staff2(person2, 10000, 1); Player player2(staff2, Player::GOALKEEPER, 12); //Create coaches for team 1 Person person3("Slavisa Jokanovic", 58); StaffMember staff3(person3, 70000, 30); Coach caoch1(staff3, Coach::HEAD); Person person4("Domingo Marin", 47); StaffMember staff4(person4, 33000, 15); Coach caoch2(staff4, Coach::ASSISTANT); //Create stadium for team 1 Stadium stadium1("Blumfild", 40000, "Tel Aviv"); //Crete team 1 Team team1(stadium1, 13, "Maccabi"); //Add the players and the coaches to the team team1 += player1; team1 += player2; team1 += caoch1; team1 += caoch2; //************************************ Create team 2 ********************************* //Create players for team 2 Person person11("Altman Omri", 21); StaffMember staff11(person11, 20000, 3); Player player11(staff11, Player::STRICKER, 8); Person person22("Danin Eyal", 26); StaffMember staff22(person22, 10000, 1); Player player22(staff22, Player::GOALKEEPER, 12); //Create coaches for team 2 Person person33("Badir Walid", 58); StaffMember staff33(person33, 70000, 30); Coach caoch11(staff33, Coach::HEAD); Person person44("burstein gabriel", 47); StaffMember staff44(person44, 33000, 15); Coach caoch22(staff44, Coach::ASSISTANT); //Create stadium for team 2 Stadium stadium2("Hapoel Stadium", 30000, "Tel Aviv"); //Crete team 2 Team team2(stadium2, 13, "Hapoel Tel Aviv"); //Add the players and the coaches to the team team2 += player11; team2 += player22; team2 += caoch11; team2 += caoch22; //********************************************************************************* //Create referees for the entire association Person refereePerson1("Ben Zion Salman", 37); Referee referee1(refereePerson1, Referee::CENTER); Person refereePerson2("Naftali Eitan", 46); Referee referee2(refereePerson2, Referee::SIDELINE); Person refereePerson3("Ozi Itzhaki", 32); Referee referee3(refereePerson3, Referee::SIDELINE); Person refereePerson4("Ilan Barom", 24); Referee referee4(refereePerson4, Referee::ASISSTANT); //Create the league League league1("Ligat ha al", 2, 1);//two teams one game //Add both teams to the league league1 += team1; league1 += team2; //Create a game between the two teams Game theGame(stadium1, team1, team2); theGame.AddReferee(referee1); theGame.AddReferee(referee2); theGame.AddReferee(referee3); theGame.AddReferee(referee4); //Add the game to the league league1 += theGame; //Create the football association Association association1(1, 4); //Add the league to the association association1.addLeague(league1); //Add the referees to the association association1.addReferee(referee1); association1.addReferee(referee2); association1.addReferee(referee3); association1.addReferee(referee4); //Start the association - start the league - start the game association1.start(); //other unused operators team1 -= player2;//Remove player from team league1 -= team1;//remove team from league //return 0; }
int main(int argc, char *argv[]) { // Initializing and loading variables SDL_Window *window = nullptr; SDL_Renderer *renderTarget = nullptr; int currentTime = 0; int prevTime = 0; float delta = 0.0f; const Uint8 *keyState; SDL_Rect camerRect = { 0, 0, 640, 480 }; int levelWidth, levelHeight; SDL_Init(SDL_INIT_VIDEO); if(IMG_Init(imgFlags) != imgFlags) std::cout << "Error: " << IMG_GetError() << std::endl; int data = 10; window = SDL_CreateWindow("SDL CodingMadeEasy Series", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN); renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); Player player1(renderTarget, "image.png", 0, 0, 3, 4); Player player2(renderTarget, "image.png", 500, 300, 3, 4); SDL_Texture *texture = LoadTexture("rect.png", renderTarget); SDL_QueryTexture(texture, NULL, NULL, &levelWidth, &levelHeight); bool isRunning = true; SDL_Event ev; while(isRunning) { prevTime = currentTime; currentTime = SDL_GetTicks(); delta = (currentTime - prevTime) / 1000.0f; while(SDL_PollEvent(&ev) != 0) { // Getting the events if(ev.type == SDL_QUIT) isRunning = false; } keyState = SDL_GetKeyboardState(NULL); player1.Update(delta, keyState); player2.Update(delta, keyState); camerRect.x = player1.GetOriginX() - 320; camerRect.y = player1.GetOriginY() - 240; if(camerRect.x < 0) camerRect.x = 0; if(camerRect.y < 0) camerRect.y = 0; if(camerRect.x + camerRect.w >= levelWidth) camerRect.x = levelWidth - 640; if(camerRect.y + camerRect.h >= levelHeight) camerRect.y = levelHeight - 480; player1.IntersectsWith(player2); SDL_RenderClear(renderTarget); SDL_RenderCopy(renderTarget, texture, &camerRect, NULL); player1.Draw(renderTarget, camerRect); player2.Draw(renderTarget, camerRect); SDL_RenderPresent(renderTarget); } SDL_DestroyWindow(window); SDL_DestroyRenderer(renderTarget); SDL_DestroyTexture(texture); texture = nullptr; window = nullptr; renderTarget = nullptr; IMG_Quit(); SDL_Quit(); return 0; }
int main(int argc,char* args[]){ //the screen where everything else is drawn on SDL_Surface* screen; //eventcontainer used to handle inputs SDL_Event event; //if the user requested to quit the program bool quit=false; //initialize SDL, if it fails, quit if(SDL_Init(SDL_INIT_EVERYTHING) == -1){ return 1; } //initialize TTF if(TTF_Init() == -1){ return 1; } //set up the screen, parameter are defined in basic.h screen = SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP, SDL_SWSURFACE); //set window caption SDL_WM_SetCaption("Move that dot!",NULL); //fill the screen white SDL_FillRect(screen,&screen->clip_rect,SDL_MapRGB(screen->format,0xFF, 0xFF,0xFF)); //game is not started bool game = false; //load font TTF_Font* font = NULL; font = TTF_OpenFont("./adkfont.ttf",20); if(font == NULL){ printf("Error:main.cpp:could not load font.\n"); return 1; } //startscreen basic setup SDL_Surface* background = NULL; background = load_image("./background.png"); if(background == NULL){ printf("Error:main.cpp:could not load background image.\n"); } //this vector holds all players (in the future ;) ) // std::vector<Player> player; Player player1("red"); player1.id=1; Player player2("green"); player2.id=2; //rect that defines the playing field SDL_Rect field; field.x=0; field.y=0; field.h=SCREEN_HEIGHT; field.w=SCREEN_HEIGHT; //seperates field from the other part SDL_Rect sep; sep.x=field.w; sep.y=0; sep.w=8; sep.h=SCREEN_HEIGHT; //display of statistics and stuff SDL_Rect stat; stat.x=field.w+sep.w; stat.y=0; stat.w=SCREEN_WIDTH-field.w-sep.w; stat.h=SCREEN_HEIGHT; //to pause the game press space bool pause = false; //whether to cap the framerate bool cap = true; //these timers are used to measure/fix framerate Timer fps; Timer update; int frame; //start them both upon starting the program //the update timer isnt used at the moment //used with collision detection int i; //update.start(); //loop this until the user requests to quit the program while(quit == false){ if(game == true){ fps.start(); //loop through captured events while(SDL_PollEvent(&event)){ //let dotclass handle the events /*if(pause == false){ player1.dot.handle_input(event); player2.dot.handle_input(event); }*/ //if the user wants to exit, set quit to true, such that the loop ends if(event.type == SDL_QUIT){ quit = true; } if(event.type == SDL_KEYDOWN){ if(event.key.keysym.sym == SDLK_ESCAPE){ game = false; } if(event.key.keysym.sym == SDLK_SPACE){ if(pause == false){ print_message("PAUSED",screen,150,240,100); pause = true; } else{ pause = false; } } } } if(pause == false){ if(player1.is_set() == true){ player1.handleinput(); } if(player2.is_set() == true){ player2.handleinput(); } //store path for collision detection player1.dot.store_path(i); player2.dot.store_path(i); //move the dot to new positions depending on old postition and velocity player1.dot.move(); player2.dot.move(); //check whether a collision happened //player1.dot.check_collision(&player1.dot.path_array[0][0], // &player2.dot.path_array[0][0],i); //draw the whole screen white otherwise the dot image leaves a trail //since its old positions dont get deleted //(which is kind off what we want in the end!) SDL_FillRect(screen,&field,SDL_MapRGB(screen->format,0xFF, 0xFF,0xFF)); SDL_FillRect(screen,&sep,SDL_MapRGB(screen->format,0x00, 0x00,0x00)); SDL_FillRect(screen,&stat,SDL_MapRGB(screen->format,0xFF,0xFF,0x00)); //paint the dot at its new positions on the screen player1.dot.show(screen); player2.dot.show(screen); //#######next line is not used at the moment //frame++; } } else if (game == false){ while(SDL_PollEvent(&event)){ if(event.type == SDL_QUIT){ quit = true; } apply_surface(0,0,background,screen); print_message("Achtung die Kurve 3000",screen,30,30,60); print_message("Select player and keys",screen,50,100,40); print_message("Press 1 or 2 to select player, SPACE to start", screen,55,170,30); if(event.type == SDL_KEYDOWN){ if(event.key.keysym.sym == SDLK_1){ player1.setup(screen); } if(event.key.keysym.sym == SDLK_2){ player2.setup(screen); } if(event.key.keysym.sym == SDLK_SPACE){ game = true; } } //display settings for the players player1.displaysettings(screen); player2.displaysettings(screen); } } SDL_Flip(screen); //this caps the framerate to FRAMES_PER_SECOND so that it runs at the same //speed on every computer if((cap=true) && (fps.get_ticks() < 1000 / FRAMES_PER_SECOND)){ SDL_Delay((1000/FRAMES_PER_SECOND)-fps.get_ticks()); } //count cycles i++; } //before quitting call SDL_Quit() to let the SDL library exit and clean up //properly SDL_Quit(); //return without errorcode if the program made it until here return 0; }
int main(){ ////////////////////GAME PROPERTIES/////////////////////////////////// //window properties sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "Tungu"); pong.setMouseCursorVisible(false); pong.setFramerateLimit(60); //music sf::Music bgm; bgm.openFromFile("multimedia/audio/background.wav"); bgm.setPitch(1.5); bgm.setLoop(true); bgm.play(); //sound sf::SoundBuffer buffer1; buffer1.loadFromFile("multimedia/audio/bounce.wav"); sf::Sound bounce; bounce.setBuffer(buffer1); sf::SoundBuffer buffer2; buffer2.loadFromFile("multimedia/audio/point.wav"); sf::Sound point; point.setBuffer(buffer2); //ncp properties sf::RectangleShape ncp(sf::Vector2f(5, RENDERHEIGHT / 1.6)); ncp.setFillColor(sf::Color(50, 50, 50)); ncp.setPosition(RENDERWIDTH / 2, RENDERHEIGHT / 2 - (RENDERHEIGHT / 1.6) / 2 ); //player 1 properties int p1Len = 100; sf::RectangleShape player1(sf::Vector2f(15, p1Len)); player1.setFillColor(sf::Color(0, 0, 255)); player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2); int player1Score = 0; //player 2 properties int p2Len = 100; sf::RectangleShape player2(sf::Vector2f(15, p2Len)); player2.setFillColor(sf::Color(0, 255, 0)); player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2); int player2Score = 0; //ball properties sf::CircleShape ball(10, 25); ball.setFillColor(sf::Color(255, 255, 255)); ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius()); float BALLSPEED = 15; float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED; float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius(); float ballDiameter = ball.getRadius() * 2; //score-timer text sf::Font font; font.loadFromFile("fonts/LiberationSerif-Regular.ttf"); sf::Text score1("0", font, 80); score1.setPosition(RENDERWIDTH / 4, 0); sf::Text score2("0", font, 80); score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0); sf::Text timer1("", font, 50); timer1.setPosition(0 , 5 * RENDERHEIGHT / 6); sf::Text timer2("", font, 50); timer2.setPosition(RENDERWIDTH / 2 - timer2.getLocalBounds().width, 5 * RENDERHEIGHT / 6); int time1 = 0; int time2 = 0; //gameover sf::Text gameover("GAME OVER", font, 120); gameover.setColor(sf::Color::Red); gameover.setPosition(0, RENDERHEIGHT / 3); ///////////////CAMERA FUNTIONS////////////////////// CvCapture* capture =0; capture = cvCaptureFromCAM(0); if(!capture){ printf("Capture failure\n"); return -1; } IplImage* frame=0; frame = cvQueryFrame(capture); if(!frame) return -1; //create a blank image and assigned to 'imgTracking' which has the same size of original video imgTracking=cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U, 3); cvZero(imgTracking); //covert the image, 'imgTracking' to black //cvNamedWindow("Player1"); ///cvNamedWindow("Player2"); //iterate through each frames of the video while(player1Score + player2Score != 7){ frame = cvQueryFrame(capture); if(!frame) break; frame=cvCloneImage(frame); cvSmooth(frame, frame, CV_GAUSSIAN,3,3); //smooth the original image using Gaussian kernel /////////////////// Player 1 //////////////////// IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV IplImage* imgThresh = GetThresholdedImage(imgHSV, 85, 143, 40, 116, 256, 159); //guante cyan cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel player100 = trackObject(imgThresh, 255, 0, 0, 1); /////////////////// Player 2 //////////////////// IplImage* imgHSV2 = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); cvCvtColor(frame, imgHSV2, CV_BGR2HSV);//Change the color format from BGR to HSV IplImage* imgThresh2 = GetThresholdedImage(imgHSV2, 26, 145, 31, 73, 256, 111); //guante verde cvSmooth(imgThresh2, imgThresh2, CV_GAUSSIAN,3,3); //smooth the binary image using Gaussian kernel player200 = trackObject(imgThresh2, 0, 255, 0, 2); // Add the tracking image and the frame cvAdd(frame, imgTracking, frame); //cvShowImage("Player1", imgThresh); //cvShowImage("Player2", imgThresh2); cvMoveWindow("Video", 1800, 0); cvResizeWindow("Video", 100, 240); cvShowImage("Video", frame); //Clean up used images cvReleaseImage(&imgHSV); cvReleaseImage(&imgHSV2); cvReleaseImage(&imgThresh); cvReleaseImage(&imgThresh2); cvReleaseImage(&frame); //Wait 10mS int c = cvWaitKey(10); //If 'ESC' is pressed, break the loop if((char)c==27 ) break; /////////////////////////////Scores/////////////////////////////////// //score for player one winning if(player1Score == player2Score + 1) { timer1.setString(convertInt(time1 += 2)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 2) { timer1.setString(convertInt(time1 += 4)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 3) { timer1.setString(convertInt(time1 += 8)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 4) { timer1.setString(convertInt(time1 += 16)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 5) { timer1.setString(convertInt(time1 += 32)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 6) { timer1.setString(convertInt(time1 += 64)); timer2.setString(convertInt(time2 += 1)); } //score on equals if(player1Score == player2Score) { timer1.setString(convertInt(time1 += 1)); timer2.setString(convertInt(time2 += 1)); } //score for player two winning if(player2Score == player1Score + 1) { timer2.setString(convertInt(time2 += 2)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 2) { timer2.setString(convertInt(time2 += 4)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 3) { timer2.setString(convertInt(time2 += 8)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 4) { timer2.setString(convertInt(time2 += 16)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 5) { timer2.setString(convertInt(time2 += 32)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 6) { timer2.setString(convertInt(time2 += 64)); timer1.setString(convertInt(time1 += 1)); } //////////////////////////////Game//////////////////////////////////// //player 1 movement muy lento if(player100==6) player1.move(0, -(vel-3)); else if(player100==-6) player1.move(0, vel-3); //player 1 movement LENTO if(player100==1) player1.move(0, -vel); else if(player100==-1) player1.move(0, vel); //player 1 movement MEDIO if(player100==2) player1.move(0, -(vel+10)); else if(player100==-2) player1.move(0, vel+10); //player 1 movement RAPIDO if(player100==3) player1.move(0, -(vel+20)); else if(player100==-3) player1.move(0, vel+20); //player 1 movement muy rapido if(player100==4) player1.move(0, -(vel+25)); else if(player100==-4) player1.move(0, vel+25); //player 1 movement Extreme if(player100==5) player1.move(0, -(vel+30)); else if(player100==-5) player1.move(0, vel+30); //MOVIMIENTO GOLPE PLAYER1 if(player100==0) player1.move(0,0); if (player1.getPosition().x <= 10){ if(player100==22) player1.move(10, 0); } //player 2 movement muy LENTO if(player200==6) player2.move(0, -(vel-3)); else if(player200==-6) player2.move(0, vel-3); //player 2 movement LENTO if(player200==1) player2.move(0, -vel); else if(player200==-1) player2.move(0, vel); //player 2 movement MEDIO if(player200==2) player2.move(0, -(vel+10)); else if(player200==-2) player2.move(0, vel+10); //player 2 movement RAPIDO if(player200==3) player2.move(0, -(vel+20)); else if(player200==-3) player2.move(0, vel+20); //player 2 movement muy rapido if(player200==4) player2.move(0, -(vel+25)); else if(player200==-4) player2.move(0, vel+25); //player 2 movement Extreme if(player200==5) player2.move(0, -(vel+30)); else if(player200==-5) player2.move(0, vel+30); if(player200==0) player2.move(0,0); //MOVIMIENTO GOLPE PLAYER2 if (player2.getPosition().x >= RENDERWIDTH-player2.getSize().x-10){ if(player200==-22) player2.move(-10, 0); } //player 1 and wall collision if(player1.getPosition().y <= 0) player1.setPosition(0, 0); if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y) player1.setPosition(0, RENDERHEIGHT - player1.getSize().y); //PLAYER1 AND WALL BACK COLLISION if(player1.getPosition().x != 0) player1.move(-1,0); //PLAYER2 AND WALL BACK COLLISION if(player2.getPosition().x != RENDERWIDTH-player2.getSize().x) player2.move(1,0); //player 2 and wall collision if(player2.getPosition().y <= 0) player2.setPosition(RENDERWIDTH - player2.getSize().x, 0); if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y) player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y); //ball and wall collision if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter){ ballVelY *= -1; bounce.play(); } //ball and player 1 collision if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x){ if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y) || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y && ball.getPosition().y >= player1.getPosition().y){ if (player1.getPosition().x > 14){ ballVelX = (ballVelX - 5) * -1; ball.setFillColor(sf::Color(255,0,0)); } else if (player1.getPosition().x <= 14){ ballVelX = (ballVelX - 3) * -1; ball.setFillColor(sf::Color(0,0,255)); bounce.play(); } } else{ ball.setFillColor(sf::Color(255,255,255)); point.play(); player2Score += 1; ballX = RENDERWIDTH / 2 - ball.getRadius(); if (BALLSPEED < 8) BALLSPEED += 0.2; ballVelX = BALLSPEED; score2.setString(convertInt(player2Score)); score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0); if (p2Len > 40) p2Len -= 10; player2.setSize(sf::Vector2f(15, p2Len)); if (p1Len < 100) p1Len += 10; player1.setSize(sf::Vector2f(15, p1Len)); } } //ball and player 2 collision if (ball.getPosition().x + ballDiameter >= player2.getPosition().x){ if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y) || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y && ball.getPosition().y >= player2.getPosition().y){ if (player2.getPosition().x < (RENDERWIDTH-9-player2.getSize().x)){ ballVelX = (ballVelX + 5) * -1; ball.setFillColor(sf::Color(255,0,0)); } else if (player2.getPosition().x >= (RENDERWIDTH-9-player2.getSize().x)){ ballVelX = (ballVelX + 3) * -1; ball.setFillColor(sf::Color(0,255,0)); bounce.play(); } } else{ ball.setFillColor(sf::Color(255,255,255)); point.play(); player1Score += 1; ballX = RENDERWIDTH / 2 - ball.getRadius(); if (BALLSPEED < 8) BALLSPEED += 0.5; ballVelX = -BALLSPEED; score1.setString(convertInt(player1Score)); if (p1Len > 40) p1Len -= 10; player1.setSize(sf::Vector2f(15, p1Len)); if (p2Len < 100) p2Len += 10; player2.setSize(sf::Vector2f(15, p2Len)); } } //ball position update ballX += ballVelX; ballY += ballVelY; ball.setPosition(ballX, ballY); //render updates pong.clear(); pong.draw(score1); pong.draw(timer1); pong.draw(timer2); pong.draw(score2); pong.draw(player1); pong.draw(player2); pong.draw(ball); pong.draw(ncp); pong.display(); while(player1Score + player2Score == 7){ if(player1Score > player2Score) timer1.setString(convertInt(time1 += 500)); if(player1Score < player2Score) timer2.setString(convertInt(time2 += 500)); pong.clear(sf::Color::Black); pong.draw(score1); pong.draw(timer1); pong.draw(timer2); pong.draw(score2); pong.draw(gameover); pong.display(); counter(3); break; } /////////////////////Finish Game///////////////////////////////// } std::stringstream ss; ss.str (timer1.getString()); std::string scorePlayer1 = ss.str(); ss.str (timer2.getString()); std::string scorePlayer2 = ss.str(); std::cout << "Final Score:" << '\n'; std::cout << "Player1: " + scorePlayer1 << '\n'; std::cout << "Player2: " + scorePlayer2 << '\n'; std::ofstream myfile ("highscores.txt", std::ofstream::in | std::ofstream::out | std::ofstream::app); if (myfile.is_open()) { myfile << scorePlayer1 << std::endl; myfile << scorePlayer2 << std::endl; myfile.close(); } else std::cout << "Unable to open file"; cvDestroyAllWindows() ; cvReleaseImage(&imgTracking); cvReleaseCapture(&capture); return 0; }
int main(int argc, char* args[]) { init(); //Stage objects Tileset tileset("src/assets/img/tileset.png", 6, 3); Map map1("map1"); // Get level dimensions levelWidth = tileset.getTileWidth() * map1.getMapWidth(); levelHeight = tileset.getTileHeight() * map1.getMapHeight(); Player player1(gRenderer, "src/assets/img/player1_sheet.png", 5, 5, 3, 4); //Wall wall(192, 96, 96, 576); // General event handler stuff bool quit = false; bool paused = false; SDL_Event e; // Game Loop while (!quit) { //framerate control stabilizeFramerate(); // Poll Events while (SDL_PollEvent(&e) != 0) { switch (e.type) { // check for quit case SDL_QUIT: quit = true; break; case SDL_KEYDOWN: switch(e.key.keysym.sym) { // check for pause case SDLK_ESCAPE: if (!paused) { paused = true; } else { paused = false; } break; } break; // checking for window focus case SDL_WINDOWEVENT: switch(e.window.event) { case SDL_WINDOWEVENT_FOCUS_LOST: paused = true; break; } break; } } if (!paused) { keystate = SDL_GetKeyboardState(NULL); player1.update(delta, keystate, map1); cameraRect.x = player1.getOriginX() - SCREEN_WIDTH/2; cameraRect.y = player1.getOriginY() - SCREEN_HEIGHT/2; if (cameraRect.x < 0) { cameraRect.x = 0; } if (cameraRect.y < 0) { cameraRect.y = 0; } if (cameraRect.x + cameraRect.w >= levelWidth) { cameraRect.x = levelWidth - SCREEN_WIDTH; } if (cameraRect.y + cameraRect.h >= levelHeight) { cameraRect.y = levelHeight - SCREEN_HEIGHT; } // Clear stage SDL_RenderClear(gRenderer); // Make stuff happen! map1.drawTiles(tileset); map1.drawWalls(); player1.draw(gRenderer, cameraRect); // Update stage SDL_RenderPresent(gRenderer); } } done(); return 0; }
void Visual::paintplayer(map &mapp,int k) { QPen pen(Qt::NoPen); QBrush bonus100(QColor(255, 255, 255), QPixmap(":resource/images/player11.png")); QBrush bonus200(QColor(255, 255, 255), QPixmap(":resource/images/player22.png")); QBrush bonus300(QColor(255, 255, 255), QPixmap(":resource/images/palyer33.png")); QBrush money100(QColor(255, 255, 255), QPixmap(":resource/images/Money100.png")); QBrush money500(QColor(255, 255, 255), QPixmap(":resource/images/Money500.png")); QBrush player1 (QColor(255, 255, 255), QPixmap(":resource/images/player1.png")); QBrush player2 (QColor(255, 255, 255), QPixmap(":resource/images/player2.png")); for (int i = 0; i < mapp.len; i++) { for (int j = 0; j < mapp.wid; j++) { //QGraphicsItem * item = QGraphicsScene.items(i*10,j*10,10,10); QList <QGraphicsItem*>item; item=items(QRectF(i*10, j*10, 10, 10)); if (item.size()>0 && item[0]->data(0) != map::WALL && item[0]->data(0) != map::LIFT_UP && item[0]->data(0) != map::LIFT_DOWN) removeItem(item[0]); if (mapp.floor[i][j][k] == map::BONUS100) { QGraphicsItem * item = addRect(QRectF(i*10, j*10, 10, 10), pen, bonus100); item->setData(0, map::BONUS100); } if (mapp.floor[i][j][k] == map::BONUS200) { QGraphicsItem * item = addRect(QRectF(i*10, j*10, 10, 10), pen, bonus200); item->setData(0, map::BONUS200); } if (mapp.floor[i][j][k] == map::BONUS300) { QGraphicsItem * item = addRect(QRectF(i*10, j*10, 10, 10), pen, bonus300); item->setData(0, map::BONUS300); } if (mapp.floor[i][j][k] == map::MONEY100) { QGraphicsItem * item = addRect(QRectF(i*10, j*10, 10, 10), pen, money100); item->setData(0, map::MONEY100); } if (mapp.floor[i][j][k] == map::MONEY500) { QGraphicsItem * item = addRect(QRectF(i*10, j*10, 10, 10), pen, money500); item->setData(0, map::MONEY500); } if (mapp.floor[i][j][k] == map::PLAYER1) { QGraphicsItem * item = addRect(QRectF(i*10, j*10, 10, 10), pen, player1); item->setData(0, map::PLAYER1); } if (mapp.floor[i][j][k] == map::PLAYER2) { QGraphicsItem * item = addRect(QRectF(i*10, j*10, 10, 10), pen, player2); item->setData(0, map::PLAYER2); } } } }
int screen_3::Run(sf::RenderWindow &App) { Cursor mouse_cursor(App,resources->textures.get("MouseCursor")); sf::Sprite mock_cursor; mock_cursor.setTexture(resources->textures.get("MockCursor")); sf::Sprite background; background.setTexture(resources->textures.get("GameBackground")); bool Running = true; int starting_index = resources->start_index; Sidebar sidebar(App, resources); sf::Clock clock; Board board(starting_index,App, resources); board.move(0,50); board.animateMovement(sf::Vector2f(200,50),3); Replay replay(App, resources); Player* player1 (new Player(board.getBoardGrid(),'X')); Player* player2 (new Player(board.getBoardGrid(),'O')); Player* curr_player; player1->setTexture(&resources->textures.get("Player1Mark")); player2->setTexture(&resources->textures.get("Player2Mark")); Button waiting(App); waiting.load(resources->textures.get("WaitingBase"),resources->textures.get("WaitingHover")); //waiting.setScale(0.7); waiting.setPosition((App.getSize().x-waiting.getGlobalBounds().x)/2+40,App.getSize().y-waiting.getGlobalBounds().y+5); VictoryBanner victory_banner(App,player1,player2,replay, resources); Messenger messenger(App, resources); PauseOverlay pause_screen(App, resources, true); while (Running) { sf::Event event; while (App.pollEvent(event)) { if(messageSocket->receive(packet) == sf::Socket::Disconnected) { sidebar.stopMusic(); pause_screen.setString(" DISCONNECTED"); pause_screen.isDisconnected(true); pause_screen.setPaused(true); } else { board.handleEvents(event); //if not disconnected if(sidebar.updateEvents(event)) pause_screen.setPaused(true); } if(pause_screen.updateEvent(event)) { return pause_screen.getActionKeyCode(); } messenger.updateEvents(event); if (event.type == sf::Event::Closed) { return (-1); } if(victory_banner.handleEvents(event)) { return victory_banner.getActionKeyCode(); } } board.updateAnimation(); messenger.update(messageSocket); if((is_host&&player_turn) || (!is_host && !player_turn)) { curr_player = player1; } else { curr_player = player2; } mouse_cursor.update(); replay.record(player_turn , replaySocket); mock_cursor.setPosition(replay.getCurrPosition()); if(!board.game_done) { if(sidebar.checkTimer(resources->isTimerActivated,resources->turn_timer)) { if(player_turn) { is_waiting = false; board.update(curr_player,is_host,socket); } else{ is_waiting = true; board.update(curr_player,socket); //receiver } if(board.round_done) { sidebar.restartClock(); player_turn = !player_turn; board.round_done = false; } } else { player_turn = !player_turn; sidebar.restartClock(); } } else { replay.save(); sidebar.stopMusic(); victory_banner. displayBanner(is_host); } App.clear(); App.draw(background); App.draw(board); if(!player_turn) App.draw(mock_cursor); if(is_waiting) App.draw(waiting); App.draw(sidebar); if(board.game_done) { App.draw(victory_banner); } if(pause_screen.isPaused()) { App.draw(pause_screen); } App.draw(messenger); App.draw(mouse_cursor); App.display(); } return (-1); }
int main() { sf::RenderWindow window(sf::VideoMode(640, 480, 32), "Pickin' Gems"); window.SetFramerateLimit(30); window.SetIcon(gem_icon.width, gem_icon.height, gem_icon.pixel_data); sf::Image grassImage; grassImage.LoadFromFile("grass.png"); grassImage.SetSmooth(false); sf::Sprite grass; grass.SetImage(grassImage); sf::Image gemImage; gemImage.LoadFromFile("gem.png"); gemImage.CreateMaskFromColor(sf::Color(255, 0, 255)); gemImage.SetSmooth(false); sf::Sprite gem; gem.SetImage(gemImage); sf::Image player1Image; player1Image.LoadFromFile("ayne.png"); player1Image.CreateMaskFromColor(sf::Color(255, 0, 255)); player1Image.SetSmooth(false); sf::Sprite player1(player1Image); sf::Image player2Image; player2Image.LoadFromFile("elliot.png"); player2Image.CreateMaskFromColor(sf::Color(255, 0, 255)); player2Image.SetSmooth(false); sf::Sprite player2(player2Image); sf::Image pressEnterToStartImage; pressEnterToStartImage.LoadFromFile("pressEnterToStart.png"); pressEnterToStartImage.SetSmooth(false); sf::Sprite pressEnterToStart(pressEnterToStartImage); sf::Image humanSelectedImage; humanSelectedImage.LoadFromFile("humanSelected.png"); humanSelectedImage.SetSmooth(false); sf::Sprite humanSelectedSprite(humanSelectedImage); sf::Image computerSelectedImage; computerSelectedImage.LoadFromFile("computerSelected.png"); computerSelectedImage.SetSmooth(false); sf::Sprite computerSelectedSprite(computerSelectedImage); sf::Image gameOverScreenImage; gameOverScreenImage.LoadFromFile("gameOverScreen.png"); gameOverScreenImage.SetSmooth(false); sf::Sprite gameOverScreen(gameOverScreenImage); sf::Music backgroundMusic; backgroundMusic.OpenFromFile("background.ogg"); backgroundMusic.SetLoop(true); sf::SoundBuffer gemPickupBuffer; gemPickupBuffer.LoadFromFile("gemCollect.wav"); sf::Sound gemPickup; gemPickup.SetBuffer(gemPickupBuffer); sf::Font font; font.LoadFromFile("Halo11.ttf"); sf::String player1ScoreToPrint; sf::String player2ScoreToPrint; sf::String timerPrint; sf::String gameOverPrint; player1ScoreToPrint.SetFont(font); player1ScoreToPrint.SetSize(24); player2ScoreToPrint.SetFont(font); player2ScoreToPrint.SetSize(24); timerPrint.SetFont(font); timerPrint.SetSize(24); gameOverPrint.SetFont(font); gameOverPrint.SetSize(24); float player1Frame = 1; float player2Frame = 1; int player1Score = 0; int player2Score = 0; char buffer1[256]; char buffer2[256]; char buffer3[256]; char buffer4[256]; sf::Vector2f player1Pos; sf::Vector2f player2Pos; enum Direction {DOWN = 0, UP = 1, LEFT = 2, RIGHT = 3}; enum State {MAIN_MENU = 0, PLAYER_SELECT = 1, GAME = 2, GAME_OVER = 3}; State gameState = MAIN_MENU; bool humanSelected = true; bool computerSelected = false; bool enterPressed = false; bool downPressed = false; bool upPressed = false; bool backgroundMusicPlaying = true; Direction player1Direction = DOWN; Direction player2Direction = DOWN; bool player1Moving = false; bool player2Moving = false; bool player1Animating = false; bool player2Animating = false; sf::Vector2f gemPos; srand(time(NULL)); gemPos.x = (int)rand() % (640 - 32); gemPos.y = (int)rand() % (480 - 32); int time = 1800; bool gameOver = false; bool fullscreen = false; while (window.IsOpened()) { sf::Event event; while (window.GetEvent(event)) { if (event.Type == sf::Event::Closed) { window.Close(); } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Escape)) { window.Close(); } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Return)) { enterPressed = true; } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Up)) { upPressed = true; } if ((event.Type == sf::Event::KeyPressed) && (event.Key.Code == sf::Key::Down)) { downPressed = true; } } switch (gameState) { case MAIN_MENU: window.Draw(pressEnterToStart); if (enterPressed) { enterPressed = false; gameState = PLAYER_SELECT; } break; case PLAYER_SELECT: if (humanSelected) { window.Draw(humanSelectedSprite); } else if (computerSelected) { window.Draw(computerSelectedSprite); } if (upPressed) { if (computerSelected) { computerSelected = false; humanSelected = true; } else if (humanSelected) { humanSelected = false; computerSelected = true; } upPressed = false; } else if (downPressed) { if (humanSelected) { humanSelected = false; computerSelected = true; } else if (computerSelected) { computerSelected = false; humanSelected = true; } downPressed = false; } if (enterPressed) { enterPressed = false; gameState = GAME; } break; case GAME: { --time; if (backgroundMusicPlaying) { backgroundMusicPlaying = false; backgroundMusic.Play(); } for (int i = 0; i < 640 / 32; i++) { for (int j = 0; j < 480 / 32; j++) { grass.SetPosition(i * 32, j * 32); window.Draw(grass); } } gem.SetPosition(gemPos); if (window.GetInput().IsKeyDown(sf::Key::Left)) { player1Direction = LEFT; player1Animating = true; player1.Move(-3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::Right)) { player1Direction = RIGHT; player1Animating = true; player1.Move(3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::Up)) { player1Direction = UP; player1Animating = true; player1.Move(0, -3); } else if (window.GetInput().IsKeyDown(sf::Key::Down)) { player1Direction = DOWN; player1Animating = true; player1.Move(0, 3); } if (humanSelected) { if (window.GetInput().IsKeyDown(sf::Key::A)) { player2Direction = LEFT; player2Animating = true; player2.Move(-3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::D)) { player2Direction = RIGHT; player2Animating = true; player2.Move(3, 0); } else if (window.GetInput().IsKeyDown(sf::Key::W)) { player2Direction = UP; player2Animating = true; player2.Move(0, -3); } else if (window.GetInput().IsKeyDown(sf::Key::S)) { player2Direction = DOWN; player2Animating = true; player2.Move(0, 3); } } else if (computerSelected) { if ((int)player2Pos.x < (int)gemPos.x) { if (gemPos.x - player2Pos.x < 2) { player2.Move(1, 0); } else { player2.Move(2, 0); } player2Direction = RIGHT; player2Animating = true; } else if ((int)player2Pos.y > (int)gemPos.y) { if (player2Pos.y - gemPos.y < 2) { player2.Move(0, -1); } else { player2.Move(0, -2); } player2Direction = UP; player2Animating = true; } else if ((int)player2Pos.x > (int)gemPos.x) { if (player2Pos.x - gemPos.x < 2) { player2.Move(-1, 0); } else { player2.Move(-2, 0); } player2Direction = LEFT; player2Animating = true; } else if ((int)player2Pos.y < (int)gemPos.y) { if (gemPos.y - player2Pos.y < 2) { player2.Move(0, 1); } else { player2.Move(0, 2); } player2Direction = DOWN; player2Animating = true; } else if ((int)player2Pos.x > (int)gemPos.x) { if (player2Pos.x - gemPos.x < 2) { player2.Move(-1, 0); } else { player2.Move(-2, 0); } player2Direction = LEFT; player2Animating = true; } } if (player1Animating) { player1Frame += 0.25; if (player1Frame > 3) { player1Frame = 0; } player1Animating = false; } if (player2Animating) { player2Frame += 0.25; if (player2Frame > 3) { player2Frame = 0; } player2Animating = false; } player1Pos = player1.GetPosition(); player2Pos = player2.GetPosition(); if (player1Pos.x < 0) { player1.SetX(0); } else if (player1Pos.x + 32 > 640) { player1.SetX(640 - 32); } if (player1Pos.y < 0) { player1.SetY(0); } else if (player1Pos.y + 48 > 480) { player1.SetY(480 - 48); } if (player2Pos.x < 0) { player2.SetX(0); } else if (player2Pos.x + 32 > 640) { player2.SetX(640 - 32); } if (player2Pos.y < 0) { player2.SetY(0); } else if (player2Pos.y + 48 > 480) { player2.SetY(480 - 48); } if (isColliding(getRegionCoordinates(gemPos, 32, 32), getRegionCoordinates(player1Pos, 32, 48))) { gemPos.x = (int)rand() % (640 - 32); gemPos.y = (int)rand() % (480 - 32); gemPickup.Play(); player1Score += 10; } if (isColliding(getRegionCoordinates(gemPos, 32 + 3, 32 + 3), getRegionCoordinates(player2Pos, 32, 48))) { gemPos.x = (int)rand() % (640 - 32); gemPos.y = (int)rand() % (480 - 32); gemPickup.Play(); player2Score += 10; } sprintf(buffer1, "Player 1's Score: %d", player1Score); sprintf(buffer2, "Player 2's Score: %d", player2Score); sprintf(buffer3, "Time left: %d", time / 30); player1ScoreToPrint.SetText(buffer1); player2ScoreToPrint.SetText(buffer2); timerPrint.SetText(buffer3); player1ScoreToPrint.SetColor(sf::Color(0, 0, 0)); player2ScoreToPrint.SetColor(sf::Color(0, 0, 0)); timerPrint.SetColor(sf::Color(0, 0, 0)); player1ScoreToPrint.SetX(0); player1ScoreToPrint.SetY(0); player2ScoreToPrint.SetX(0); player2ScoreToPrint.SetY(24); timerPrint.SetX(0); timerPrint.SetY(48); int player1SpritesheetX = (int)player1Frame * 32; int player1SpritesheetY = player1Direction * 48; int player2SpritesheetX = (int)player2Frame * 32; int player2SpritesheetY = player2Direction * 48; player1.SetSubRect(sf::IntRect(player1SpritesheetX, player1SpritesheetY, player1SpritesheetX + 32, player1SpritesheetY + 48)); player2.SetSubRect(sf::IntRect(player2SpritesheetX, player2SpritesheetY, player2SpritesheetX + 32, player2SpritesheetY + 48)); window.Draw(gem); window.Draw(player2); window.Draw(player1); window.Draw(player1ScoreToPrint); window.Draw(player2ScoreToPrint); window.Draw(timerPrint); if (time / 30 == 0) { gameState = GAME_OVER; } break; } case GAME_OVER: { if (player1Score < player2Score) { sprintf(buffer4, "Congratulations, Player 2! You win!"); } else if (player1Score > player2Score) { sprintf(buffer4, "Congratulations, Player 1! You win!"); } else { sprintf(buffer4, "It's a tie!"); } gameOverPrint.SetText(buffer4); gameOverPrint.SetColor(sf::Color(0, 0, 0)); sf::FloatRect rect(gameOverPrint.GetRect()); sf::Vector2f pos(window.GetWidth() / 2 - rect.GetWidth() / 2, window.GetHeight() / 2 - rect.GetHeight() / 2); gameOverPrint.SetPosition(pos); window.Draw(gameOverScreen); window.Draw(gameOverPrint); if (enterPressed) { enterPressed = false; gameState = MAIN_MENU; time = 1800; player1Score = 0; player2Score = 0; player1Frame = 1; player2Frame = 1; player1.SetPosition(0, 0); player2.SetPosition(0, 0); player1Direction = DOWN; player2Direction = DOWN; upPressed = false; downPressed = false; humanSelected = true; } break; } } window.Display(); window.Clear(); } return 0; }
int main() { srand(time(0)); //variables const int width = 700; const int height = 600; int points = 0; float velEnemy = 0.2; //font sf::Font font; if (!font.loadFromFile("Data/avaria.ttf")) return 0; //sound sf::SoundBuffer exploImage; if (!exploImage.loadFromFile("Data/explosion.wav")) return 0; sf::Sound destroy; destroy.setBuffer(exploImage); //enemy image sf::Texture alienImage; if (!alienImage.loadFromFile("Data/alien.png")) return 0; //enemy dead sf::Texture alienDead; if (!alienDead.loadFromFile("Data/alienExplo.png")) return EXIT_FAILURE; //ship image sf::Texture texture; if (!texture.loadFromFile("Data/ship.png")) return EXIT_FAILURE; sf::RectangleShape alien; alien.setTexture(&alienImage); alien.setSize(sf::Vector2f(50, 50)); alien.setPosition(150, 100); //bullet image sf::Texture bulletImage; if (!bulletImage.loadFromFile("Data/bullet.png")) return EXIT_FAILURE; //score sf::Text score; score.setFont(font); score.setPosition(10, height - 50); score.setString("Points : 0"); //end score sf::RenderWindow window(sf::VideoMode(width, height), "X1"); Player player1(width/2, height-50, texture); shoot shooter(bulletImage); shoot alienShoot(bulletImage); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { srand(time(nullptr)); if (event.type == sf::Event::Closed) window.close(); if (event.key.code == sf::Keyboard::Escape) window.close(); } //logic alien move if (alien.getPosition().x > width - 50) velEnemy = -0.2; if (alien.getPosition().x < 50) velEnemy = 0.2; //end logic window.clear(sf::Color::Black); std::stringstream text; bool go = false; text << "Player : " << points; score.setString(text.str()); window.draw(score); //logic for alien alien.setTexture(&alienImage); if (alien.getGlobalBounds().intersects(shooter.bullet.getGlobalBounds())) { alien.setPosition(1 + rand() % width, 100); points++; destroy.play(); alien.setTexture(&alienDead); Sleep(20); } //set player limits if (player1.rect.getPosition().x < 0) player1.rect.setPosition(0, player1.rect.getPosition().y); if (player1.rect.getPosition().x > width - 50) player1.rect.setPosition(width - 50, player1.rect.getPosition().y); alien.move(velEnemy, 0); window.draw(alien); if (player1.update()) { shooter.update(player1.rect.getPosition().x, player1.rect.getPosition().y, -3); window.draw(shooter.bullet); } window.draw(player1.rect); window.display(); } return 0; }