Example #1
0
	void GameScene::onKeyDown(EventKeyboard::KeyCode keyCode, cocos2d::Event* e)
	{
		if(keyCode == EventKeyboard::KeyCode::KEY_ESCAPE)
		{
			gameEnd();
			return;
		}

		if(mKeyMap.find(keyCode) != mKeyMap.end())
		{
			Key::MappedKey key = mKeyMap[keyCode];
			if(mKeyState[key] == Key::KEY_UP)
			{
				mKeyState[key] = Key::KEY_DOWN;

				// TODO calculate position
				Event::KeyEvent event(key, Key::KEY_DOWN, 0);
				Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(Event::KeyEvent::DOWN, &event);
			}

			if(key == Key::SpeedDown)
			{
				setSpeed(mSpeed - 0.5f);
			}
			else if(key == Key::SpeedUp)
			{
				setSpeed(mSpeed + 0.5f);
			}
		}
	}
Example #2
0
void Game::combat(Hero& newHero,Monster& newMonster)
{
	int playerDamage,monsterDamage;
	while(true)
	{
		playerDamage=newMonster.getDamage()-newHero.getBlock();
		cout<<endl<<newMonster.getName()<<" damages you for "<<playerDamage<<" HP...\n";
		newHero.takeDamage(playerDamage);
		if(newHero.getCurHP()<=0)
			gameEnd();
		cout<<newMonster.getName()<<" HP: "<<newMonster.getHP()<<"\t\t"<<newHero.getName()<<" HP: "<<newHero.getCurHP();
		_getch();
		monsterDamage=newHero.getMeleeDamage();
		newMonster.takeDamage(monsterDamage);
		if(newMonster.getHP()<=0)
		{
			cout<<endl<<"You deliver the killing blow to "<<newMonster.getName()<<"\n";
			newHero.updateXP(newMonster.getLevel());
			return;
		}
		cout<<endl<<"You damage "<<newMonster.getName()<<" for "<<monsterDamage<<" HP...\n";
		cout<<newMonster.getName()<<" HP: "<<newMonster.getHP()<<"\t\t"<<newHero.getName()<<" HP: "<<newHero.getCurHP();
		_getch();
	}
}
Example #3
0
void Game::gameSetup()
{
	cout<<CLRSCR<<"New Game Started...\nPress Any Key...";
	_getch();
	initStory();
	gameEnd();
}
Example #4
0
void gpLoadGame(char *name, featom *atom)
{
    char filename[PATH_MAX] = "";
    sdword verifysavename;

    if (gpNumberGames > 0)
    {
        gpDonePicking(name, atom);

        dbgAssertOrIgnore(gpCurrentSelected < gpNumberGames);
        if (gpLoadTutorial)
        {
            strcpy(filename,TutorialSavedGamesPath);
        }
        else
        {
            strcpy(filename,SavedGamesPath);
        }
        strcat(filename,gpGames[gpCurrentSelected].title);

        if ((verifysavename = VerifySaveFile(filename)) != VERIFYSAVEFILE_OK)
        {
            if (verifysavename == VERIFYSAVEFILE_BADVERSION)
                GeneralMessageBox(strGetString(strErrorInvalidSaveGameFileVersion),NULL);
            else
                GeneralMessageBox(strGetString(strErrorInvalidSaveGameFile),NULL);
            return;
        }

        feScreenDisappear(NULL, NULL);

        soundEventStopTrack(SOUND_EVENT_DEFAULT, 1.0f);
        soundEventPause(TRUE);
        gameEnd();
        if (gpLoadSinglePlayerGame)
        {
            if (gpLoadTutorial)
            {
                tutorial = 1;
            }
            else
            {
                //for single player games, tutorial == 2 to use certain tutorial functions
                tutorial = 2;
            }
            utyLoadSinglePlayerGameGivenFilename(filename);
        }
        else
        {
            utyLoadMultiPlayerGameGivenFilename(filename);
        }
        if (!multiPlayerGame)
        {
            universePause = FALSE;      // unpause game
        }
        soundEventPause(FALSE);
    }
}
Example #5
0
MainWindow::MainWindow(QWidget *parent):KXmlGuiWindow(parent)
{  
	//To the random number generator
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
	
	//ScoreNumber
	scoreNumberLabel = new QLabel( i18n( "Scores:" ), this );
	scoreNumber = new QLCDNumber( this );
	
	//Removed lines
	removedLinesLabel = new QLabel( i18n( "Removed lines:" ), this );
	removedLinesNumber = new QLCDNumber( this );
	
	//Level
	levelLabel = new QLabel( i18n( "Level:" ), this );
	levelNumber = new QLCDNumber( this );
	
	//CentralTable
	centralTable = new CentralTable(this);
	
	//NextShape
	nextShapeLabel = new QLabel( i18n( "Next shape:" ), this );
	nextShapeTable = new NextShapeTable( this );

	//Set connects
	connect( centralTable, SIGNAL( newNextShape( Shape* ) ), nextShapeTable, SLOT( setNewShapeSlot( Shape* ) ) );
	connect( centralTable, SIGNAL( removedLine() ), this, SLOT( removedLineSlot() ));
	connect( centralTable, SIGNAL( newScore( int ) ), this, SLOT( newScoreSlot( int ) ) );
	connect( centralTable, SIGNAL( newLevel( int ) ), this, SLOT( newLevelSlot( int ) ) );
	connect( centralTable, SIGNAL( gameEnd() ), this, SLOT( gameEndSlot() ) );
	
    createActions();
	
	setMinimumWidth( MAIN_WINDOW_MINIMUM_WIDTH );
	setMinimumHeight( MAIN_WINDOW_MINIMUM_HEIGHT );
	
	statusBar()->showMessage( i18n( "Welcome to Ketris!" ) );
	
    //setupGUI();
	
	setupGUI( QSize( MAIN_WINDOW_DEFAULT_WIDTH, MAIN_WINDOW_DEFAULT_HEIGHT ) );
	
	setFocusPolicy( Qt::StrongFocus );
	
	//
	windowResized = false;
	statusBarVisible = false;
}
Example #6
0
void gpLoadGivenGame(char* gamename)
{
    sdword verifysavename;

    if (!fileExists(gamename, FF_UserSettingsPath))
    {
        return;
    }

    if ((verifysavename = VerifySaveFile(gamename)) != VERIFYSAVEFILE_OK)
    {
        if (verifysavename == VERIFYSAVEFILE_BADVERSION)
            GeneralMessageBox(strGetString(strErrorInvalidSaveGameFileVersion),NULL);
        else
            GeneralMessageBox(strGetString(strErrorInvalidSaveGameFile),NULL);
        return;
    }

    gameEnd();

    if (gpLoadSinglePlayerGame)
    {
        if (gpLoadTutorial)
        {
            tutorial = 1;
        }
        else
        {
            tutorial = 2;
        }
        utyLoadSinglePlayerGameGivenFilename(gamename);
    }
    else
    {
        utyLoadMultiPlayerGameGivenFilename(gamename);
    }
    if (!multiPlayerGame)
    {
        universePause = FALSE;
    }
}
Example #7
0
	void GameScene::update(float dt)
	{
		float playTime = currentTime() - mStartTime; // - origTime ??
		float position = mLastBpmMeter + calculateMeter(mCurrentBpm, currentTime() - mLastBpmTime);
		if( checkGameEnd() )
		{
			gameEnd();
			return;
		}

		for(auto it = mChannelPlayers.begin(); it != mChannelPlayers.end(); it++)
		{
			if (it->second)
			{
				// invisible note
				if (it->first[0] == '3' || it->first[0] == '4')
					continue;

				it->second->autoplay(position);
			}
		}
	}
Example #8
0
GameView::GameView()
{
    scene = new QGraphicsScene;
    snake = new Snake;
    addItems();
    setScene(scene);
    score = 0;

    connect(this,SIGNAL(keyPress(QKeyEvent*)),
            snake,SLOT(keyPressEvent(QKeyEvent*)));
    connect(snake,SIGNAL(addandDelBox(OneBox*,OneBox*)),
            this,SLOT(changedItem(OneBox*,OneBox*)));
    connect(snake,SIGNAL(needNewBox()),this,SLOT(needNewBox()));
    connect(snake,SIGNAL(gameEnd()),this,SLOT(endGame()));

    //添加边界线,进行碰撞检测
    QGraphicsLineItem *topLineItem =new QGraphicsLineItem(-20,-20,820,-20);
    QGraphicsLineItem *leftLineItem = new QGraphicsLineItem(-20,-20,-20,620);
    QGraphicsLineItem *buttonLineItem = new QGraphicsLineItem(-20,620,820,620);
    QGraphicsLineItem *rightLineItem = new QGraphicsLineItem(820,-20,820,620);
    scene->addItem(topLineItem);
    scene->addItem(leftLineItem);
    scene->addItem(buttonLineItem);
    scene->addItem(rightLineItem);

//设置窗口大小,不可改变
    setMinimumSize(802, 602);
    setMaximumSize(802, 602);

    scene->setSceneRect(0,0,800,600);
//    setSceneRect(0,0,800,600);
//    setSceneRect(0,0,800,600);

    setBackgroundBrush(Qt::black);
    needNewBox();
}
Example #9
0
void Client::handleData(boost::system::error_code ec)
{
    if (!ec)
    {
        std::istream is(&data);
        std::string str;
        std::getline(is, str);

        boost::erase_all(str,"\r");

        std::vector<std::string> tokens;


        boost::split(tokens, str, boost::is_any_of(" "));

        if (!tokens.empty())
        {
            if ((tokens[0] == "<12>")&&(tokens[27]!="none"))
            {
                int row1;
                int col1;
                int row2;
                int col2;

                if (tokens[27]=="o-o")
                {
                    if (tokens[9]=="W")
                    {
                        row1 = 7;
                        col1 = 4;
                        row2 = 7;
                        col2 = 6;
                    }else{
                        row1 = 0;
                        col1 = 4;
                        row2 = 0;
                        col2 = 6;
                    }
                }else if (tokens[27]=="o-o-o"){
                    if (tokens[9]=="W")
                    {
                        row1 = 7;
                        col1 = 4;
                        row2 = 7;
                        col2 = 2;
                    }else{
                        row1 = 0;
                        col1 = 4;
                        row2 = 0;
                        col2 = 2;
                    }

                }else{
                    row1 = std::stoi(tokens[27].substr(3,1)) - 1;
                    col1 = stringToCol(tokens[27].substr(2,1));
                    row2 = std::stoi(tokens[27].substr(6,1)) - 1;
                    col2 = stringToCol(tokens[27].substr(5,1));
                }

                int whiteTime = std::stoi(tokens[24]);
                int blackTime = std::stoi(tokens[25]);

                Piece promotionPiece;

                if (tokens[27].size()==9){ //means promotion
                    promotionPiece = symbolToPiece(tokens[27].substr(8,1));
                }else promotionPiece = Piece::None;


                positionReady({{row1,col1},{row2,col2}}, whiteTime, blackTime, promotionPiece);
            }else if (tokens[0] == "Creating:"){
                int time = 60*std::stoi(tokens[7]);
                if (tokens[1] == nickname) startGame(Color::White, time, tokens[1], tokens[3]);
                else startGame(Color::Black, time, tokens[1], tokens[3]);
            }else if (tokens[0] == "{Game"){
                std::string toCheck = tokens.back();
                if (toCheck == "1-0") gameEnd(Color::White);
                else if (toCheck == "0-1") gameEnd(Color::Black);
                else if (toCheck == "1/2-1/2") gameEnd(Color::Both);
            }else if ((tokens[0]=="****")&&(tokens[1]=="Starting")&&(tokens[2]=="FICS")){
                //succesfully logged in
                boost::erase_all(tokens[5],"(U)");
                boost::erase_all(tokens[5],"(R)");
                nickname = tokens[5];
                toClient("set style 12");
            }else if (tokens[0] != "fics%"){
                //not processed, so let's print it
                textReady(str);
            }
        }

        boost::asio::async_read_until(socket, data, "\n\r",
                boost::bind(&Client::handleData, this, _1));

    }
}
Example #10
0
File: gui.c Project: MrYawe/snake
/**
 * \fn guiPlay(BoardSize size)
 * \brief This function is the main game loop
 * \details Function that create a new game, perform the game loop and display the game with SDL
 * \param size Variable representing the size of the Board (Small, Medium or Large)
 */
int guiPlay(BoardSize size)
{
      /*******************/
     /**   VARIABLES   **/
    /*******************/

    /***** SDL Variables *****/
    SDL_Event event;    //Variable to capture mouse/keyboard events
    SDL_Surface* screen;//Buffer that will contain the pixels to render on the screen

    /***** General Variables *****/
    Assets assets;  //Variable that will contain all the assets used in the game
    Timer timer;    //Variable used to control the actions based on the time

    /***** Structure Variables *****/
    bool continueGameMove1, continueGameMove2;	//Variable used to check if the snake x is dead
    bool snake1InDebuff, snake2InDebuff;

    Game game;		//Variable to access the game
    Board board;	//Variable to access the board
    Snake snake1;	//Variable to access the first snake
    Snake snake2;	//Variable to access the first snake


	  /************************/
	 /**   INITIALIZATION   **/
	/************************/

	/***** SDL Initialization *****/
    SDL_Init(SDL_INIT_VIDEO);				//Initialization of the SDL Library
    TTF_Init();
    SDL_WM_SetCaption("Larasnake", NULL);	//Set the title and icon name of the displayed window
    screen = guiCreateScreen(size);

    /***** General Variables *****/
    srand(time(NULL));  //Initialization of the random function
    timer = guiCreateTimer();
    assets = guiLoadAssets(size);

    /***** Structure Variables *****/
    continueGameMove1 = true;
    continueGameMove2 = true;
    snake1InDebuff = false;
    snake2InDebuff = false;

    game = gameCreate(size);
    board = gameGetBoard(game);

    guiSetFieldType(game, assets, size);


    snake1 = gameGetSnake(game, 1);
    snake2 = gameGetSnake(game, 2);

    //music of the game
    Mix_Music *musiqueGame = Mix_LoadMUS("./sound/musiqueGame.mp3"); //music of the game
    Mix_PlayMusic(musiqueGame, -1); //loop  --PLAY HERE
    Mix_VolumeMusic(MIX_MAX_VOLUME / 6); //half of the maximum sound


      /************************/
     /**      GAME LOOP     **/
    /************************/
    gameFeed(game, true); //first ham appeared
    while (gameGetIsPlaying(game)) {
        timer->start = SDL_GetTicks(); // Start of the current frame

        guiEvent(&event, snake1, game); // catch player event and set the direction of snake1
        if(!gameGetIsPaused(game)) {
            if(gameGetPauseTimer(game)==0) //know if we don't leave the pause
            {
                if(boardGetType(board)) //if we have to change the background
                {
                    boardSetType(board, false); //disable change flag
                    guiChangeBackground(screen, assets,size);
                    guiSetFieldType(game, assets, size);
                    printf("MAP CHANGED\n"); //the map is now changed
                }
              ////// Move of snake 1 (player) //////
              timer->snake1MoveTimer += SDL_GetTicks() - timer->snake1LastMove;
              if (timer->snake1MoveTimer >= snakeGetSpeed(snake1)) {  // test if we wait enough time to move the snake 1
                  continueGameMove1 = gameMoveSnake(game, snake1);   // move th snake1. if snake1 is dead continueGameMove1=false
                  timer->snake1MoveTimer = 0;                         // set the move timer to 0 when the snake move
              }
              timer->snake1LastMove = SDL_GetTicks();
              /////////////////////////////////////

              ////// Move of snake 2 (AI) //////
              timer->snake2MoveTimer += SDL_GetTicks() - timer->snake2LastMove;
              if (timer->snake2MoveTimer >= snakeGetSpeed(snake2)) {  // test if we wait enough time to move the snake 2
                  snakeSetDirection(snake2, iaSurviveDepth(board, snake2, snake1));  // let ia choose the best direction of snake2
                  continueGameMove2 = gameMoveSnake(game, snake2);   // move the snake2. if snake2 is dead continueGameMove2=false
                  timer->snake2MoveTimer = 0;                        // set the move timer to 0 when the snake move
              }
              timer->snake2LastMove = SDL_GetTicks();
              /////////////////////////////////

              ///////////////// Debuff snake1 /////////////////
              if (!itemListIsEmpty(snakeGetItemList(snake1))) {
                  if (!snake1InDebuff) {
                      snake1InDebuff = true;
                      timer->snake1LastDebuff = SDL_GetTicks();
                  } else {
                      timer->snake1DebuffTimer += SDL_GetTicks() - timer->snake1LastDebuff;
                      if(timer->snake1DebuffTimer >= ITEM_DEBUFF_INTERVAL) {
                          gameItemDebuff(snakeGetItemList(snake1)->next, snake1);
                          snake1InDebuff = false;
                          timer->snake1DebuffTimer = 0;
                      }
                      timer->snake1LastDebuff = SDL_GetTicks();
                  }
              }
              ////////////////////////////////////////////////

              ///////////////// Debuff snake2 /////////////////
              if (!itemListIsEmpty(snakeGetItemList(snake2))) {
                  if (!snake2InDebuff) {
                      snake2InDebuff = true;
                      timer->snake2LastDebuff = SDL_GetTicks();
                  } else {
                      timer->snake2DebuffTimer += SDL_GetTicks() - timer->snake2LastDebuff;
                      if(timer->snake2DebuffTimer >= ITEM_DEBUFF_INTERVAL) {
                          gameItemDebuff(snakeGetItemList(snake2)->next, snake2);
                          snake2InDebuff = false;
                          timer->snake2DebuffTimer = 0;
                      }
                      timer->snake2LastDebuff = SDL_GetTicks();
                  }
              }
              ////////////////////////////////////////////////


              ///////// Item pop /////////
              timer->itemPopTimer += SDL_GetTicks() - timer->itemLastPop;
              if(timer->itemPopTimer >= ITEM_POP_INTERVAL) {
                  gameFeed(game, false); //Function called to put some food on the board
                  timer->itemPopTimer = 0;
              }
              timer->itemLastPop = SDL_GetTicks();
              ///////// Item pop /////////

//>>>>>>> 43afef4547198632093d7b891941aa8c99643d24
            }


        }

        /////// Draw ///////
        guiDrawGame(screen, game, assets, size);  // draw the board on screen with surfaces stored in the Assets struct
        guiReloadScreen(screen);            // reload all the screen
        //boardDisplay(board);
        ///////////////////

        if(!continueGameMove1 || !continueGameMove2) // if one snake die the game is over
            gameEnd(game);

        ////// Framerate management //////
        timer->end = SDL_GetTicks();                           // Get the time after the calculations
        timer->delay = FRAME_MS - (timer->end - timer->start); // Calculate how long to delay should be

        if(timer->delay > 0) {
            SDL_Delay(timer->delay);                           // Delay processing
        }
    }

    int idWinner;
    if(continueGameMove1) {
        if(snakeGetId(snake1) == 1)
            idWinner = 1;
        else
            idWinner = 2;
    } else {
        if(snakeGetId(snake1) == 1)
            idWinner = 2;
        else
            idWinner = 1;
    }

    ////// Free //////
    gameFree(game);
    guiFreeAssets(assets);
    Mix_FreeMusic(musiqueGame); //free the music

    //TTF_Quit();
    //SDL_Quit();
    return idWinner;
}
Example #11
0
int main() {

	setupInterrupts();
    setupSounds();

    playSoundA(titleSong, TITLESONGLEN, TITLESONGFREQ, 1);

	// Start game with splash screen
	splash();


	// Main Game Loop
	while (1) {

		oldButtons = buttons;
		buttons = BUTTONS;

		// Update player row and column
		player.bigRow = player.row + vOff;
		player.bigCol = player.col + hOff;


		switch(state) {

			case SPLASH:

				// Displays splash screen
				splash();

			break;

			case INSTRUCTIONS:

				instructions();

			break;

			case GAME:

				// Game Function holds all game logic
				game();

			break;

			case SEASONCHANGE:
				
				// Warp-like animation as player changes between seasons
				warpAnimation();

				// Change game to correct season, based on prevSeason and return to gameplay
				if (vBlankCount < 1) {
					seasonChange();
					state = GAME;
				}

			break;

			case PAUSE:

				pause();

			break;

			case LOSE:

				lose();

			break;

			case WINLEVEL:

				winLevel();

			break;

			case GAMEEND:

				gameEnd();

			break;

		}

		
		// Shadow OAM Handling
		// Player Sprite
		shadowOAM[0].attr0 = (ROWMASK & player.row) | ATTR0_SQUARE;
		shadowOAM[0].attr1 = (COLMASK & player.col) | ATTR1_SIZE16 | (ATTR1_HFLIP & (player.facing << 12));
		shadowOAM[0].attr2 = (SPRITEOFFSET16(season * 2, player.currentFrame * 2)) | ATTR2_PRIORITY2;	

		// Season Icon Sprite
		shadowOAM[1].attr0 = (ROWMASK & icon.row) | ATTR0_SQUARE;
		shadowOAM[1].attr1 = (COLMASK & icon.col) | ATTR1_SIZE16;
		shadowOAM[1].attr2 = (SPRITEOFFSET16(season * 2, 6)) | (1 << 10); // Priority 1

		REG_BG2HOFS = hOff;
        REG_BG2VOFS = vOff;

       	// Set BG1 offsets - used for snow and falling leaves
		REG_BG1HOFS = bg1HOff;
		REG_BG1VOFS = bg1VOff;
        
        //Copy the shadowOAM into the OAM
        DMANow(3, &shadowOAM, OAM, 512);

		waitForVblank();

	}

	return 0;
}
Example #12
0
int main(int argc, char * argv) {
	if (argc > 1) {
		printf("\n\tTicTacToe by scruff3y, 2016.\n\n");
		printf("How to play:\n");
		printf("The rules are the same as regular tic-tac-toe, fill a row, column or diagonal\n");
		printf("with your tile, and you win!\n\n");
		printf("To make a move, enter the row and column number of the tile you'd like to play on.\n\n");
		printf("If you really want to get a party going, try playing on a size 10 board\n");
		printf("with 10 players!\n\n");
		printf("Or, for the masochists, play a game against the computer. Hint: you will lose.\n");
		printf("(This is only availiable on a board size of 2 or 3\n");
		exit(0);
	}

	// This is just used to clear stdin between inputs.
	int c;

	// Welcome.
	printf("\n\tWelcome to TicTacToe!\n\n");
	printf("What size game would you like to play?: ");
	scanf("%i", &NUMBER_OF_GAME_SQUARES);

	while ((NUMBER_OF_GAME_SQUARES < 2) || (NUMBER_OF_GAME_SQUARES > 10)) {
		while ((c = getc(stdin)) != '\n');

		printf("Sorry, the game size must be between 2 and 10 squares.\n");
		printf("Please enter another value: ");
		scanf("%i", &NUMBER_OF_GAME_SQUARES);
	}

	while ((c = getc(stdin)) != '\n');

	// Init game board.
	GameBoard game = {0};

	char numberOfPlayers = 0;
	printf("How many players?: ");
	scanf("%i", &numberOfPlayers);

	while ((numberOfPlayers < 2) || (numberOfPlayers > 26)) {
		while ((c = getc(stdin)) != '\n');

		printf("Please specify a number between 2 and 26: ");
		scanf("%i", &numberOfPlayers);
	}

	// init playerlist.
	PlayerList playerList = InitPlayerList(numberOfPlayers);

	if ((numberOfPlayers == 2) && (NUMBER_OF_GAME_SQUARES <= 3)) {
		while ((c = getc(stdin)) != '\n');
		printf("Human or computer opponent (Y/N)?: ");
		char input;
		scanf("%c", &input);

		while ((input != 'Y') && (input != 'N') && (input != 'y') && (input != 'n')) {
			while ((c = getc(stdin)) != '\n');

			printf("Please try again: ");
			scanf("%c", &input);
		}

		if ((input == 'Y') || (input == 'y')) playerList.players[0].human = FALSE;
	}

	/*
	Main game loop:

	1. Check if game is over.
	2. If it isn't, do the next turn (data on whos turn it is stored in PlayerList)
	3. Otherwise, exit.
	*/
	while (TRUE) {
		printBoard(game);
		int gamestate = IsWon(game);
		if (gamestate != TRUE) {
			gameEnd(gamestate);
			exit(0);
		}
		else {
			nextTurn(&game, &playerList);
		}
	}
	return 0;
}
Example #13
0
void AtlantikNetwork::processNode(QDomNode n)
{
	QDomAttr a;

	for ( ; !n.isNull() ; n = n.nextSibling() )
	{
		QDomElement e = n.toElement();
		if(!e.isNull())
		{
			if (e.tagName() == "server")
			{
				a = e.attributeNode( QString("version") );
				if ( !a.isNull() )
					m_serverVersion = a.value();

				emit receivedHandshake();
			}
			else if (e.tagName() == "msg")
			{
				a = e.attributeNode(QString("type"));
				if (!a.isNull())
				{
					if (a.value() == "error")
						emit msgError(e.attributeNode(QString("value")).value());
					else if (a.value() == "info")
						emit msgInfo(e.attributeNode(QString("value")).value());
					else if (a.value() == "chat")
						emit msgChat(e.attributeNode(QString("author")).value(), e.attributeNode(QString("value")).value());
				}
			}
			else if (e.tagName() == "display")
			{
				int estateId = -1;

				a = e.attributeNode(QString("estateid"));
				if (!a.isNull())
				{
					estateId = a.value().toInt();
					Estate *estate;
					estate = m_atlanticCore->findEstate(a.value().toInt());

					emit displayDetails(e.attributeNode(QString("text")).value(), e.attributeNode(QString("cleartext")).value().toInt(), e.attributeNode(QString("clearbuttons")).value().toInt(), estate);

					bool hasButtons = false;
					for( QDomNode nButtons = n.firstChild() ; !nButtons.isNull() ; nButtons = nButtons.nextSibling() )
					{
						QDomElement eButton = nButtons.toElement();
						if (!eButton.isNull() && eButton.tagName() == "button")
						{
							emit addCommandButton(eButton.attributeNode(QString("command")).value(), eButton.attributeNode(QString("caption")).value(), eButton.attributeNode(QString("enabled")).value().toInt());
							hasButtons = true;
						}
					}

					if (!hasButtons)
						emit addCloseButton();
				}
			}
			else if (e.tagName() == "client")
			{
				a = e.attributeNode(QString("playerid"));
				if (!a.isNull())
					m_playerId = a.value().toInt();

				a = e.attributeNode(QString("cookie"));
				if (!a.isNull())
					emit clientCookie(a.value());
			}
			else if (e.tagName() == "configupdate")
			{
				int configId = -1;
				a = e.attributeNode(QString("configid"));
				if (!a.isNull())
				{
					configId = a.value().toInt();
					ConfigOption *configOption;
					if (!(configOption = m_atlanticCore->findConfigOption(configId)))
						configOption = m_atlanticCore->newConfigOption( configId );

					a = e.attributeNode(QString("name"));
					if (configOption && !a.isNull())
						configOption->setName(a.value());

					a = e.attributeNode(QString("description"));
					if (configOption && !a.isNull())
						configOption->setDescription(a.value());

					a = e.attributeNode(QString("edit"));
					if (configOption && !a.isNull())
						configOption->setEdit(a.value().toInt());

					a = e.attributeNode(QString("value"));
					if (configOption && !a.isNull())
						configOption->setValue(a.value());

					if (configOption)
						configOption->update();
				}

				int gameId = -1;
				a = e.attributeNode(QString("gameid"));
				if (!a.isNull())
				{
					gameId = a.value().toInt();
					for( QDomNode nOptions = n.firstChild() ; !nOptions.isNull() ; nOptions = nOptions.nextSibling() )
					{
						QDomElement eOption = nOptions.toElement();
						if (!eOption.isNull() && eOption.tagName() == "option")
							emit gameOption(eOption.attributeNode(QString("title")).value(), eOption.attributeNode(QString("type")).value(), eOption.attributeNode(QString("value")).value(), eOption.attributeNode(QString("edit")).value(), eOption.attributeNode(QString("command")).value());
					}
					emit endConfigUpdate();
				}
			}
			else if (e.tagName() == "deletegame")
			{
				a = e.attributeNode(QString("gameid"));
				if (!a.isNull())
				{
					int gameId = a.value().toInt();

					Game *game = m_atlanticCore->findGame(gameId);
					if (game)
						m_atlanticCore->removeGame(game);
				}
			}
			else if (e.tagName() == "gameupdate")
			{
				int gameId = -1;

				a = e.attributeNode(QString("gameid"));
				if (!a.isNull())
				{
					gameId = a.value().toInt();

					Player *playerSelf = m_atlanticCore->playerSelf();
					if ( playerSelf && playerSelf->game() )
						kdDebug() << "gameupdate for " << QString::number(gameId) << " with playerSelf in game " << QString::number(playerSelf->game()->id()) << endl;
					else
						kdDebug() << "gameupdate for " << QString::number(gameId) << endl;


					Game *game = 0;
					if (gameId == -1)
					{
						a = e.attributeNode(QString("gametype"));
						if ( !a.isNull() && !(game = m_atlanticCore->findGame(a.value())) )
							game = m_atlanticCore->newGame(gameId, a.value());
					}
					else if (!(game = m_atlanticCore->findGame(gameId)))
						game = m_atlanticCore->newGame(gameId);

					a = e.attributeNode(QString("canbejoined"));
					if (game && !a.isNull())
						game->setCanBeJoined(a.value().toInt());

					a = e.attributeNode(QString("description"));
					if (game && !a.isNull())
						game->setDescription(a.value());

					a = e.attributeNode(QString("name"));
					if (game && !a.isNull())
						game->setName(a.value());

					a = e.attributeNode(QString("players"));
					if (game && !a.isNull())
						game->setPlayers(a.value().toInt());

					a = e.attributeNode(QString("master"));
					if (game && !a.isNull())
					{
						// Ensure setMaster succeeds by creating player if necessary
						Player *player = m_atlanticCore->findPlayer( a.value().toInt() );
						if ( !player )
							player = m_atlanticCore->newPlayer( a.value().toInt() );
						game->setMaster( player );
					}

					QString status = e.attributeNode(QString("status")).value();
					if ( m_serverVersion.left(4) == "0.9." || (playerSelf && playerSelf->game() == game) )
					{
						if (status == "config")
							emit gameConfig();
						else if (status == "init")
							emit gameInit();
						else if (status == "run")
							emit gameRun();
						else if (status == "end")
							emit gameEnd();
					}

					if (game)
						game->update();
				}
			}
			else if (e.tagName() == "deleteplayer")
			{
				a = e.attributeNode(QString("playerid"));
				if (!a.isNull())
				{
					int playerId = a.value().toInt();

					Player *player = m_atlanticCore->findPlayer(playerId);
					if (player)
						m_atlanticCore->removePlayer(player);
				}
			}
			else if (e.tagName() == "playerupdate")
			{
				int playerId = -1;

				a = e.attributeNode(QString("playerid"));
				if (!a.isNull())
				{
					playerId = a.value().toInt();

					Player *player;
					if (!(player = m_atlanticCore->findPlayer(playerId)))
						player = m_atlanticCore->newPlayer( playerId, (m_playerId == playerId) );

					// Update player name
					a = e.attributeNode(QString("name"));
					if (player && !a.isNull())
						player->setName(a.value());

					// Update player game
					a = e.attributeNode(QString("game"));
					if (player && !a.isNull())
					{
						int gameId = a.value().toInt();
						if (gameId == -1)
							player->setGame( 0 );
						else
						{
							// Ensure setGame succeeds by creating game if necessary
							Game *game = m_atlanticCore->findGame(a.value().toInt());
							if (!game)
								game = m_atlanticCore->newGame(a.value().toInt()); // 
							player->setGame( game );
						}
					}

					// Update player host
					a = e.attributeNode(QString("host"));
					if (player && !a.isNull())
						player->setHost(a.value());

					// Update player image/token
					a = e.attributeNode(QString("image"));
					if (player && !a.isNull())
						player->setImage(a.value());

					// Update player money
					a = e.attributeNode(QString("money"));
					if (player && !a.isNull())
						player->setMoney(a.value().toInt());

					a = e.attributeNode(QString("bankrupt"));
					if (player && !a.isNull())
						player->setBankrupt(a.value().toInt());

					a = e.attributeNode(QString("hasdebt"));
					if (player && !a.isNull())
						player->setHasDebt(a.value().toInt());

					a = e.attributeNode(QString("hasturn"));
					if (player && !a.isNull())
						player->setHasTurn(a.value().toInt());

					// Update whether player can roll
					a = e.attributeNode(QString("can_roll"));
					if (player && !a.isNull())
						player->setCanRoll(a.value().toInt());

					// Update whether player can buy
					a = e.attributeNode(QString("can_buyestate"));
					if (player && !a.isNull())
						player->setCanBuy(a.value().toInt());

					// Update whether player can auction
					a = e.attributeNode(QString("canauction"));
					if (player && !a.isNull())
						player->setCanAuction(a.value().toInt());

					// Update whether player can use a card
					a = e.attributeNode(QString("canusecard"));
					if (player && !a.isNull())
						player->setCanUseCard(a.value().toInt());

					// Update whether player is jailed
					a = e.attributeNode(QString("jailed"));
					if (player && !a.isNull())
					{
						player->setInJail(a.value().toInt());
						// TODO: emit signal with player ptr so board can setText and display something
					}

					// Update player location
					a = e.attributeNode(QString("location"));
					if (!a.isNull())
					{
						m_playerLocationMap[player] = a.value().toInt();

						bool directMove = false;

						Estate *estate = m_atlanticCore->findEstate(a.value().toInt());

						a = e.attributeNode(QString("directmove"));
						if (!a.isNull())
							directMove = a.value().toInt();

						if (player && estate)
						{
							if (directMove)
								player->setLocation(estate);
							else
								player->setDestination(estate);
						}
					}

					if (player)
						player->update();
				}
			}
			else if (e.tagName() == "estategroupupdate")
			{
				a = e.attributeNode(QString("groupid"));
				if (!a.isNull())
				{
					int groupId = a.value().toInt();

					EstateGroup *estateGroup = 0;
					bool b_newEstateGroup = false;
					
					if (!(estateGroup = m_atlanticCore->findEstateGroup(groupId)))
					{
						// Create EstateGroup object
						estateGroup = m_atlanticCore->newEstateGroup(a.value().toInt());
						b_newEstateGroup = true;
					}

					a = e.attributeNode(QString("name"));
					if (estateGroup && !a.isNull())
						estateGroup->setName(a.value());

					// Emit signal so GUI implementations can create view(s)
					// TODO:  port to atlanticcore and create view there
					if (estateGroup)
					{
						if (b_newEstateGroup)
							emit newEstateGroup(estateGroup);
						estateGroup->update();
					}
				}
			}
			else if (e.tagName() == "estateupdate")
			{
				int estateId = -1;

				a = e.attributeNode(QString("estateid"));
				if (!a.isNull())
				{
					estateId = a.value().toInt();
					
					Estate *estate = 0;
					bool b_newEstate = false;

					// FIXME: allow any estateId, GUI should not use it to determin its geometry
					if (estateId >= 0 && estateId < 100 && !(estate = m_atlanticCore->findEstate(a.value().toInt())))
					{
						// Create estate object
						estate = m_atlanticCore->newEstate(estateId);
						b_newEstate = true;

						QObject::connect(estate, SIGNAL(estateToggleMortgage(Estate *)), this, SLOT(estateToggleMortgage(Estate *)));
						QObject::connect(estate, SIGNAL(estateHouseBuy(Estate *)), this, SLOT(estateHouseBuy(Estate *)));
						QObject::connect(estate, SIGNAL(estateHouseSell(Estate *)), this, SLOT(estateHouseSell(Estate *)));
						QObject::connect(estate, SIGNAL(newTrade(Player *)), this, SLOT(newTrade(Player *)));

						// Players without estate should get one
						Player *player = 0;
						QPtrList<Player> playerList = m_atlanticCore->players();
						for (QPtrListIterator<Player> it(playerList); (player = *it) ; ++it)
							if (m_playerLocationMap[player] == estate->id())
								player->setLocation(estate);
					}

					a = e.attributeNode(QString("name"));
					if (estate && !a.isNull())
						estate->setName(a.value());

					a = e.attributeNode(QString("color"));
					if (estate && !a.isNull() && !a.value().isEmpty())
						estate->setColor(a.value());

					a = e.attributeNode(QString("bgcolor"));
					if (estate && !a.isNull())
						estate->setBgColor(a.value());

					a = e.attributeNode(QString("owner"));
					Player *player = m_atlanticCore->findPlayer(a.value().toInt());
					if (estate && !a.isNull())
						estate->setOwner(player);

					a = e.attributeNode(QString("houses"));
					if (estate && !a.isNull())
						estate->setHouses(a.value().toInt());

					a = e.attributeNode(QString("mortgaged"));
					if (estate && !a.isNull())
						estate->setIsMortgaged(a.value().toInt());

					a = e.attributeNode(QString("group"));
					if (!a.isNull())
					{
						EstateGroup *estateGroup = m_atlanticCore->findEstateGroup(a.value().toInt());
						if (estate)
							estate->setEstateGroup(estateGroup);
					}

					a = e.attributeNode(QString("can_toggle_mortgage"));
					if (estate && !a.isNull())
						estate->setCanToggleMortgage(a.value().toInt());

					a = e.attributeNode(QString("can_be_owned"));
					if (estate && !a.isNull())
						estate->setCanBeOwned(a.value().toInt());

					a = e.attributeNode(QString("can_buy_houses"));
					if (estate && !a.isNull())
						estate->setCanBuyHouses(a.value().toInt());

					a = e.attributeNode(QString("can_sell_houses"));
					if (estate && !a.isNull())
						estate->setCanSellHouses(a.value().toInt());

					a = e.attributeNode(QString("price"));
					if (estate && !a.isNull())
						estate->setPrice(a.value().toInt());

					a = e.attributeNode(QString("houseprice"));
        				if (estate && !a.isNull())
                				estate->setHousePrice(a.value().toInt());

        				a = e.attributeNode(QString("sellhouseprice"));
        				if (estate && !a.isNull())
                				estate->setHouseSellPrice(a.value().toInt());
						
					a = e.attributeNode(QString("mortgageprice"));
        				if (estate && !a.isNull())
                				estate->setMortgagePrice(a.value().toInt());

        				a = e.attributeNode(QString("unmortgageprice"));
        				if (estate && !a.isNull())
                				estate->setUnmortgagePrice(a.value().toInt());
						
					a = e.attributeNode(QString("money"));
					if (estate && !a.isNull())
						estate->setMoney(a.value().toInt());

					// Emit signal so GUI implementations can create view(s)
					// TODO:  port to atlanticcore and create view there
					if (estate)
					{
						if (b_newEstate)
							emit newEstate(estate);
						estate->update();
					}
				}
			}
Example #14
0
void MainWindow::gameUpdate()
{
    //update jugador
    updateShip(this->player);

    //update bullets
    for(int i = 0; i < playerBullets->size(); i++)
    {
        bool remove = UpdatePlayerBeam(playerBullets->at(i));

        if(remove)
        {
            delete playerBullets->at(i)->myLabel;
            playerBullets->removeAt(i);
            i--;

        }
    }
    for(int i= 0; i < enemies->size(); i++)
    {
        enemyUpdate(enemies->at(i));
    }

    QRect Rectplayer = player->myLabel->geometry();
    //Checkeo Colisiones
    for(int i = 0; i < playerBullets->size(); i++)
    {
        PlayerBeam* bullet = playerBullets->at(i);
        QRect Rectbullet = bullet->myLabel->geometry();

        if(Rectbullet.intersects(Rectplayer))
        {
            player->lives--;
            delete bullet->myLabel;
            playerBullets->removeAt(i);
            i--;
        }

        for(int j = 0; j < enemies->size(); j++)
        {
             enemy_T* actEnemy = enemies->at(j);
             QRect RectActEnemy = actEnemy->image->geometry();
             if(Rectbullet.intersects(RectActEnemy))
             {
                 hit(actEnemy);
                 delete bullet->myLabel;
                 playerBullets->removeAt(i);
                 i--;
                 break;
             }
        }

    }
    //Colisiones con el jugador


    for(int i = 0; i < enemies->size(); i++)
    {

        QRect RectActEnemy = enemies->at(i)->image->geometry();
        if(Rectplayer.intersects(RectActEnemy))
        {
            playerHitted = true;
            player->lives--;
            qDebug() << player->lives;
            hit(enemies->at(i));
        }
    }



    //check gmae over
    if(player->lives <= 0)
    {
         emit gameEnd();
    }

    //Checkeo Muerte de Enemigos
    for(int i = 0; i < enemies->size(); i++)
    {
        if(enemies->at(i)->dead)
        {
            delete enemies->at(i)->image;
            player->score += checkEnemyValue(enemies->at(i)->type);
            enemies->removeAt(i);
            i--;
            this->enemyKilled = true;
        }
    }

    if(enemies->size() == 0)
    {
        this->level++;
        generateNextLevel();
    }

    refreshScore();
    refreshLives();

}