Ejemplo n.º 1
0
void Scene::timeup()
{
    if(mytime->time <= 0)
    {
        mybox = new QMessageBox;
        mybox->setIconPixmap(QPixmap(":/image/image/5_141211115056_17.gif"));
        mybox->setWindowTitle("Time up");
        mybox->setText(QString("Score: ")+QString::number(score1->score)+(QString("\n\nPlay again?")));
        mybox->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        mybox->setButtonText(QMessageBox::No,("Play Again"));
        mybox->setButtonText(QMessageBox::Yes,("Home"));
        mybox->show();
        end->play();

        dis = 1;
        gameInit();
        mytime->initialize();
        score1->initialize();

        bgm2->stop();

        //設定yes no按鈕事件
        //Play again
        if(mybox->exec() == QMessageBox::No)
        {
            for(int i=0;i<num_drum;i++)
            {
                removeItem(drum_list[i]);
            }
            drum_list.clear();
            rand_list.clear();
            num =0;
            num_drum = 0;
            mytime->startTime();
            dis = 0;
            gameInit();
            bgm2->play();

        }
        //Home
        else if(mybox->exec() == QMessageBox::Yes)
        {
            removeItem(A);
            removeItem(D);
            removeItem(score1);
            removeItem(mytime);
            bgRecover();
            gameInit();

            //Initialize
            drum_list.clear();
            rand_list.clear();
            num =0;
            num_drum = 0;
            screenMode = 0;
            bgm->play();

        }
    }
}
Ejemplo n.º 2
0
void gameSet(short level) { //Gets the game ready for a new level.
	//TODO: Can be updated to use addRock
	int i;
	gameInit();
	if(level < 5) {
		for(i = 0; i < level/2+3; i++) {
			gRocks[i].x = randRange(-8, 8);
			gRocks[i].y = randRange(-8, 8);
			gRocks[i].dx = randRange(-64, 64)/80.;
			gRocks[i].dy = randRange(-64, 64)/80.;
			gRocks[i].status = ALIVE;
			gRocks[i].rockType = randRange(0, ROCK_TYPES-1);
			gRocks[i].rockSize = 2;
			if(abs(gRocks[i].dx)-abs(gRocks[i].dy) < 1) {
				gRocks[i].dx = randRange(16, 64)/80.;
				gRocks[i].dy = randRange(16, 64)/80.;
			}
		}
	}
	else if(level < 10) {
		for(i = 0; i < level/2+3; i++) {
			gRocks[i].x = randRange(-10, 10);
			gRocks[i].y = randRange(-10, 10);
			gRocks[i].dx = randRange(-1, 1);
			gRocks[i].dy = randRange(abs(gRocks[i].dx)-1, 1-abs(gRocks[i].dx));
			gRocks[i].status = ALIVE;
			gRocks[i].rockType = randRange(0, ROCK_TYPES-1);
			gRocks[i].rockSize = randRange(2,3);
			if(randRange(0, level) > 5) {
				gRocks[i].rockSize = 3;
			}
		}
	}
}
Ejemplo n.º 3
0
void MainWindow::restartGame()
{
    if(gamepause == false)
    {
        deleteAll();
        gameInit();
        dataInit();
        setBtn();
    }
}
Ejemplo n.º 4
0
LJ_int main(LJ_int argc, LJ_char* argv[])
{
    LJ_engineEarlyInit( argc, argv );
	gameInit();
	LJ_engineLateInit();

	gameSingleLoop();

    return 0;
}
Ejemplo n.º 5
0
//
// Special Key like GLUT_KEY_F1, F2, F3,...
// Arrow Keys, GLUT_KEY_UP, GLUT_KEY_DOWN, GLUT_KEY_RIGHT, GLUT_KEY_RIGHT
//
void onSpecialKeyDown( int key, int x, int y )
{
	switch( key ) {
	case GLUT_KEY_UP: if( lastKey != DOWN ) lastKey = UP; break;
	case GLUT_KEY_DOWN: if( lastKey != UP )lastKey = DOWN; break ;
	case GLUT_KEY_LEFT: if( lastKey != RIGHT )lastKey = LEFT; break ;
	case GLUT_KEY_RIGHT: if( lastKey != LEFT )lastKey = RIGHT; break ;
	case GLUT_KEY_F1: gameState = RUN ; gameInit(); break ;
	}
}
Ejemplo n.º 6
0
/**
 * Menu principal du jeu
 */
void mainMenu(){
printf(
"_________ _______  _______ __________________ _______  _______ " "\n"
"\\__   __/(  ___  )(  ____ \\__   __/ \\__   __/(  ____ \\(  ____ \\ " "\n"
"   ) (   | (   ) || (    \\/   ) (      ) (   | (    \\/| (    \\/" "\n"
"   | |   | (___) || |         | |      | |   | |      | (_____ " "\n"
"   | |   |  ___  || |         | |      | |   | |      (_____  )" "\n"
"   | |   | (   ) || |         | |      | |   | |            ) |" "\n"
"   | |   | )   ( || (____/\\   | |   ___) (___| (____/\\/\\____) |" "\n"
"   )_(   |/     \\|(_______/   )_(   \\_______/(_______/\\_______)" "\n"
"                                                               " "\n"
" _______  _______  _______  _        _______ " "\n"
"(  ___  )(  ____ )(  ____ \\( (    /|(  ___  )" "\n"
"| (   ) || (    )|| (    \\/|  \\  ( || (   ) |" "\n"
"| (___) || (____)|| (__    |   \\ | || (___) |" "\n"
"|  ___  ||     __)|  __)   | (\\ \\) ||  ___  |" "\n"
"| (   ) || (\\ (   | (      | | \\   || (   ) |" "\n"
"| )   ( || ) \\ \\__| (____/\\| )  \\  || )   ( |" "\n"
"|/     \\||/   \\__/(_______/|/    )_)|/     \\|" "\n"
);



    int choix;
    color(red, "\nBienvenue sur le jeu Tactics arena SPI deluxe edition \n"); // Change la couleur des caractères suivants en rouge
    color(cyan, "Pour une meilleure immersion, veuillez mettre la console en fullscreen, svp\n");
    do{
        printf("\nMenu principal :\n");

        printf(" 1 - Nouvelle partie\n");
        printf(" 2 - Charger partie\n");
        printf(" 3 - Aide jeu \n");
        printf(" 4 - Quitter\n");
        printf("Votre choix : ");

        choix = readLong();	// Choix = 1 si chiffre est rentré, 0 sinon

        if(choix == 0) {
    		printf("Erreur : Veuillez rentrer un chiffre et non un caractère \n");
    	}

        switch(choix){
            case 1: gameInit(); break;
            case 2: load(); break;
            case 3: mainHelp(); break;
            case 4: clearScreen(); break;
            default: printf("Erreur: votre choix doit etre compris entre 1 et 4\n");
        }

    }while(choix != 4);
    printf("A bientôt ! Hope you enjoy this game ! \n");

    exit(1);
}
Ejemplo n.º 7
0
void gameMain(void)
{
	gameInit();
	do
	{
		gameMainOpen();

	}while(flgRun);

	gameClose();
}
Ejemplo n.º 8
0
// ////////////////////////////////////////////////////////////////////////////
//called when the game finally gets fired up.
bool multiGameInit(void)
{
	UDWORD player;

	for (player = 0; player < MAX_PLAYERS; player++)
	{
		openchannels[player] = true;								//open comms to this player.
	}

	gameInit();
	msgStackReset();	//for multiplayer msgs, reset message stack

	return true;
}
Ejemplo n.º 9
0
// JFL 30 Jul 06
int qeMain(int argc,chr *argv[])
{
   int fail = 0; // failure

   //
   // INIT
   //

   //qePrintf("%s / %s / %s\n",__FILE__,glGetString(GL_VERSION),qeVersion());

   if(gameInit() < 0) // initialize game
   {
      fail=1;
   } // if

   if(fail) // check for catastrophic failure in init
   {
      goto BAIL; // end
   } // if

   //
   // BODY
   //

   // add a function object to engine
   if(!qeObjAddFnc(gameMainLoop))
   {
      BRK(); // error
      goto BAIL; // end
   }

   gameSetup(); // setup game objects
 
   qeForever(); // turn over control to the engine until the program exits

BAIL:

   //
   // FINAL
   //

   gameFinal(); // cleanup and free game objects

   if(qefnCheckForCleanExit() <0 )
   {
      BRK(); // check qelog.txt for problem
   } // if

   return 0;
} // qeMain()
Ejemplo n.º 10
0
void gui_tetris_init(){
    draw_filled_rect(camera_screen.ts_button_border+0,0,camera_screen.width-camera_screen.ts_button_border,camera_screen.height, TETRIS_COLOR_BG);
    draw_rect(camera_screen.ts_button_border+BOARD_X-1,BOARD_Y-1,camera_screen.ts_button_border+BOARD_WIDTH*TILE_SIZE+10,BOARD_HEIGHT*TILE_SIZE+10, COLOR_BLACK);
    game = createGame();
    gameInit(game);
  
    long buf;
    FILE *f;    

    f=fopen("A/CHDK/GAMES/TETRIS.SCO","rb");
    if(!f) {
        game->stats.high = 0;
    } else {
    
    fread( &buf, 1, sizeof( buf ), f );
    game->stats.high = buf; 
    
    }

    fclose (f);
    startGame(game);
}
Ejemplo n.º 11
0
void Logic::gameRun()
{
    gameInit();
    printResult();

    while(1)
    {
        setMoveDirection(userInput());

        checkFinish();

        if(bFinished || bWin) break;

        if(bChanged) generateRandom();
        else cout<<"invalid move!"<<endl;

        bChanged = false;

        printResult();
    }
    printResult();
    goodGame();
}
Ejemplo n.º 12
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);   
    // Enable the event Filter
    qApp->installEventFilter(this);
    // background music
    bgm = new QMediaPlayer();
    bgm->setMedia(QUrl("qrc:/image/bgm.mp3"));
    //set scoreboard
    scoredisplay = new QLabel(this);
    scoredisplay->setStyleSheet("color:black; background-color: transparent; font: 32pt Comic Sans MS");
    scoredisplay->setText("Score :");
    scoredisplay->setGeometry(900, 10, 150, 50);
    scoredisplay->show();
    scoreboard = new QLabel(this);
    scoreboard->setStyleSheet("color:black; background-color: transparent; font: 32pt Comic Sans MS");
    scoreboard->setGeometry(1055, 10, 100, 50);
    scoreboard->show();
    //set number of birds
    numdisplay = new QLabel(this);
    numdisplay->setPixmap(QPixmap(":/image/numdisplay.png").scaled(80,51));
    numdisplay->setGeometry(700, 10, 80, 51);
    numdisplay->show();
    birdnum = new QLabel(this);
    birdnum->setStyleSheet("color:black; background-color: transparent; font: 32pt Comic Sans MS");
    birdnum->setGeometry(790, 12, 50, 50);
    birdnum->show();
    gameInit();
    dataInit();
    setBtn();
    // Timer
    connect(&timer,SIGNAL(timeout()),this,SLOT(tick()));
    connect(this,SIGNAL(quitGame()),this,SLOT(QUITSLOT()));
    timer.start(100/6);
}
Ejemplo n.º 13
0
int main() {
	*transmit_enable = 0;
	*sram_we = 1;
	*sram_oe = 1;
	gameInit();
	int playerNum = getPlayerNum();
	printBoard();

	while (sramRead(keepScore) < 11) {

		switch (playerNum) {
		case '1':
			playerOnePlay();
			break;
		case '2':
			playerTwoPlay();
			break;
		}
	}

	alt_putstr("You win!");

	return 0;
}
Ejemplo n.º 14
0
int main(int argc, char** argv) {
    glutInit(&argc, argv);
 	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
 	glutInitWindowSize(win_width, win_height);
 	//glutFullScreen();
 	glutInitWindowPosition(0,0);
 	glutCreateWindow("Snipa");
    gameInit();  //initialize the game, load textures and stuffs
    

	glutSetCursor(GLUT_CURSOR_NONE); // hide mouse
	glutPassiveMotionFunc(mouseMovement); //check for mouse movement
	glutMouseFunc(processMouse); //check for mouse clicks
	
    glutIgnoreKeyRepeat(1);
    glutKeyboardFunc(keyboardDown);
	glutKeyboardUpFunc(keyboardUp);  
	
   
    
    glutDisplayFunc(renderScene); //decide which display handlers to use
    

    glutIdleFunc(renderScene); 
 
     
    glutReshapeFunc(gameReshape);
        
    playTheme();
     
 
    glutTimerFunc (1, bulletAnimation, 0);
   

    glutMainLoop();
}
Ejemplo n.º 15
0
Archivo: main.c Proyecto: hk0i/annoi
int main(int argc, char **argv)
{
    int setting;    /* number of rings */
    if (argc > 1)
        setting = atoi(argv[1]);
    else
        setting = 3;
    if (setting > 10)
        setting = 10;
    else if (setting < 3)
        setting = 3;
    /* init display */
    init();
    /* init game variables */

    gameInit(setting);
    musicInit();
    atexit(freeMusic);

    while (1)
    {
        /* eventMainLoop handles all SDL events, when an SDL_QUIT is received,
         * the program will exit */
        eventMainLoop();
        drawScreen();
        if (SDL_Flip(screen) < 0)
        {
            fprintf(stderr, "SDL_Flip() failed to flip screen: %s\n",
                    SDL_GetError());
            return EXIT_FAILED_FLIP;
        }
    }

    return 0;

}
Ejemplo n.º 16
0
int main(int argc, char *argv[]){ 
  char esc,tmp,strInputs[8] = {'I','T','L','F','C','U','E','O'};
  int i,j,activeStructures[8];
  Init();
  while(1){
           char c,c2;
           if(MainMenu.buttons[0].clicked){//PLAY button
                                           gameInit();
                                           gameRun();
                                           MainMenu.buttons[0].clicked = 0;
                                           }
           else if(MainMenu.buttons[1].clicked){//BEST SCORE button
                printf("Name : %s   Best Score : %d",HighScore.name,HighScore.score);
                getch();
                MainMenu.buttons[1].clicked = 0;
                }
           else if(MainMenu.buttons[2].clicked){//SETTINGS button
                if(SettingsMenu.buttons[0].clicked){//MATRIXSIZE button
                     printf("Current Matrix Size : %d",Board.settings.matrixSize);
                     printf("\nPress Enter To Change...");
                     c2 = getch();
                     if(c2 == 13) {
                           printf("\nNew Size : ");
                           scanf("%d",&Board.settings.matrixSize);
						   if(Board.settings.matrixSize > BOARD_MAX_SIZE)Board.settings.matrixSize = BOARD_MAX_SIZE;
						   else if(Board.settings.matrixSize < 5)Board.settings.matrixSize = 5;
                           printf("Current Matrix Size : %d",Board.settings.matrixSize);
                           getch();
                     }
                     SettingsMenu.buttons[0].clicked = 0;
                     }
                else if(SettingsMenu.buttons[1].clicked){//RANGE button
                     printf("Number Range : %d , %d",Board.settings.range[0],Board.settings.range[1]);
                     printf("\n(Difference must be greater then 2 <2,10>)\nPress Enter To Change...");
                     c2 = getch();
                     if(c2 == 13) {
                           printf("\nRange Begin : ");
                           scanf("%d",&Board.settings.range[0]);
						   if(Board.settings.range[0] < 2)Board.settings.range[0] = 2;
                           printf("Range End : ");
                           scanf("%d",&Board.settings.range[1]);
						   if(Board.settings.range[1] > 10)Board.settings.range[1] = 10;
						   if(Board.settings.range[0] > Board.settings.range[1] - 2){
						   Board.settings.range[0] = 2;
						   Board.settings.range[1] = 10;
						   }
                           printf("\nNew Number Range : %d , %d",Board.settings.range[0],Board.settings.range[1]);
                           getch();
                      }
                     SettingsMenu.buttons[1].clicked = 0;
                     }
                else if(SettingsMenu.buttons[2].clicked){//STRUCTURE button

				     printf("Active Structures : ");
				     for(i = 0;i < Board.settings.numberOfStructures;i++)printf(" %c ",Board.settings.structures[i].name);
                     printf("\nAvaliable Structures : I T L C E F O U");
                     printf("\nPress Enter To Change...");
                     c2 = getch();
                     if(c2 == 13) {
					       printf("\n\nThe characters you used will be saved up till you use different ones\n\n");//ingilizceye çevir
					       i = 0;
						   esc = 0;
						   while(i < 8 && !esc){
								j = 0;
								printf("Enter Structure : ");
								scanf(" %c",&tmp);
								while(j < 8 && strInputs[j] != tmp && strInputs[j] != (tmp-'a'+'A') )j++;
								if(j < 8)activeStructures[i] = j;
								else esc = 1;
								i++;
						   }
						   if(i > 1){
								if(!esc)MYS_Settings_CreateStructures(&Board.settings,activeStructures,i);
								else MYS_Settings_CreateStructures(&Board.settings,activeStructures,i-1);
						   }
						   printf("Active Structures : ");
						   for(i = 0;i < Board.settings.numberOfStructures;i++)printf(" %c ",Board.settings.structures[i].name);
						   getch();
					 }
                     SettingsMenu.buttons[2].clicked = 0;
                     }
                else if(SettingsMenu.buttons[3].clicked){//PLAYER NAME button
					 char name[32];
					 printf("Current Name : %s",Board.settings.player.name);
                     printf("\n(Name Length must be greater then 2)\nPress Enter To Change...");
                     c2 = getch();
                     if(c2 == 13) {
                           printf("\nNew Name : ");
                           gets(name);
						   if(strlen(name) > 2)
                           strcpy(Board.settings.player.name,name);
						   printf("Current Name : %s",Board.settings.player.name);
						   SaveScore();
                           getch();
                     }
                     SettingsMenu.buttons[3].clicked = 0;
				
				}
				else if(SettingsMenu.buttons[4].clicked){//BACK button
                     SettingsMenu.buttons[4].clicked = 0;
                     MainMenu.buttons[2].clicked = 0;
                     MainMenu.focusedButtonIndex = 0;
                     }
                else{
                     drawMenu(&SettingsMenu);
                     c = getch();
                     if(c == 27){//BACK button
                          SettingsMenu.buttons[4].clicked = 0;
                          MainMenu.buttons[2].clicked = 0;
                          MainMenu.focusedButtonIndex = 0;
                          }
                     else menuInput(&SettingsMenu,c);
                     }
                }
           else if(MainMenu.buttons[3].clicked){//EXIT button
                printf("CODED BY EMRE KUL");
                getch();
                return;
                }
           else {//w s enter key
                drawMenu(&MainMenu);
                c = getch();
                menuInput(&MainMenu,c);
                } 
           system("cls");    
   }
  return 0;
}
Ejemplo n.º 17
0
void enterMenu(int menu){
	LoadPaletteBGData(0, menuBGPal, menuBGPalLen);
	
	bool active = true;
	int option = 0;
	int keyPressCoolDown = 30;
	if(menu == 0)ClearObjects();
	
	//MENU LOOP
	while(active){
		keyPressCoolDown--;
		if(keyPressCoolDown <= 0)keyPressCoolDown = 0;
		clearText();
		switch(menu){
			case 0://Main menu
			if((REG_KEYINPUT & KEY_UP) == 0){
				option = 0;
			}
			if((REG_KEYINPUT & KEY_DOWN) == 0){
				option = 1;
			}
			if((REG_KEYINPUT & KEY_A) == 0 && keyPressCoolDown == 0){
				if(option == 0){
					active = false;
					gameInit();
				}else{
					menu = 1;
					keyPressCoolDown = 30;
				}
			}
			drawText(60,20,"Super Crate Box");
			drawText(105,65,"PLAY");
			drawText(93,90,"CREDITS");
			
			if(option == 0)drawText(90, 65, ">      <");
			if(option == 1)drawText(78, 90, ">         <");
			break;
			
			case 1://Credits
			if((REG_KEYINPUT & KEY_A) == 0 && keyPressCoolDown == 0){
				menu = 0;
				keyPressCoolDown = 30;
			}
			if((REG_KEYINPUT & KEY_B) == 0 && keyPressCoolDown == 0){
				menu = 0;
				keyPressCoolDown = 30;
			}
			
			drawText(30, 20, "GBA - Super Crate Box");
			drawText(30,60, "Created by Peter Black");
			drawText(70,80, "for CGA 2014");
			drawText(8, 135, "Assets & Gameplay C Vlambeer");
			break;
			
			case 2://Game Over
			if((REG_KEYINPUT & KEY_A) == 0 && keyPressCoolDown == 0){
				active = false;
				gameInit();
			}
			if((REG_KEYINPUT & KEY_B) == 0 && keyPressCoolDown == 0){
				menu = 0;
				ClearObjects();
				keyPressCoolDown = 30;
			}
		
			drawText(82,60,"GAME OVER");
			drawText(85,80,"Score:");
			drawText(133,80,toString(score));
			drawText(77, 125,"A = Retry");
			drawText(65, 135,"B = Main Menu");
			
			
			break;
		}
		
		
		WaitVSync();
		UpdateObjects();
	}
	
	LoadPaletteBGData(0, backgroundPal, backgroundPalLen);
}
Ejemplo n.º 18
0
// JFL 22 Jul 09
// JS 21 Apr 12; Added court, paddles, and ball objects
// JS 22 Apr 12; Added many object and collision resolution
// JS 24 Apr 12; Implemented winning condition
int gameMainLoop()
{
   int errorCode = 0; // in case functions return errors

   // Game object pointers
   Camera *cam;
   HeadsUp *hud;
   InputController *inpCtrl;
   Court *court;
   Paddle *paddles[NUM_PLYRS];
   Ball *ball;
   CollisionController *collCtrl;

   //
   // UPDATE
   //

   // Get input from Keyboard and QE
   if(inpCtrl = Game.inpCtrl)
   {
      inpCtrl->update();
   } // if

   // Update state of the HUD
   if(hud = Game.hud)
   {
      hud->update();
   } // if

   // Only update game-playing state if currently in play
   if(Game.inPlay)
   {      
      // Check collisions
      if(collCtrl = Game.collCtrl)
      {
         collCtrl->update();
      } // if
      
      // Update and resolve paddles
      for(int i=0; i<NUM_PLYRS; i++)
      {
         if(paddles[i] = Game.paddles[i])
         {
            errorCode = paddles[i]->update();
            // Print error if any
            if (errorCode != 0)
            {
               qePrintf("**Error: Paddle%d's *inpCtrl invalid!", i);
            } // if
            // Resolve collision of the paddles
            if(collCtrl && errorCode == 0)
            {
               if(collCtrl->phw[i])
               {
                  errorCode = collCtrl->resolvePaddle(i);
                  // Print error if any
                  if (errorCode != 0)
                  {
                     qePrintf("**CollCtrl's *xyzPad%d invalid!", i);
                  } // if
               } // if
            } // if
         } // if
      } // for

      // Update and resolve ball
      if(ball = Game.ball)
      {
         ball->update();
         // Resolve collision of ball
         if(collCtrl)
         {
            if(collCtrl->bhp[IDNX_PLY_1] ||  // After hitting Player1
               collCtrl->bhp[IDNX_PLY_2] ||  // After hitting Player2
               collCtrl->bhhw ||             // After hitting horizontal walls
               collCtrl->bhbw)               // After hitting side walls
            {
               errorCode = collCtrl->resolveBall();
               // Print error if any
               if (errorCode != 0)
               {
                  qePrintf("**CollCtrl's *xyzBal invalid!");
               } // if
            } // if
         } // if
      } // if ball
   } // if inPlay

   //
   // WIN CONDITION CHECK
   //

   // Check to see if the game is over (If someone gets 3 points)
   if(Game.scores[IDNX_PLY_1] == 3 || Game.scores[IDNX_PLY_2] == 3)
   {
      // Not the first game anymore, regardless
      Game.firstGame = false;
      // Game is not in play anymore (until game is restarted)
      Game.inPlay = false;
      // Play game end sound
      Game.sndId = qeSndPlay(snd[SDR_INDX_STR_END_GAME].name);
      
      // Manage scores of each paddle
      for(int i=0; i<NUM_PLYRS; i++)
      {
         // Record last scores
         Game.lastScores[i] = Game.scores[i];

         // Clear scores, to prevent this routine from running concurrently
         Game.scores[i] = 0;
      } // for 
   } // if

   //
   // RESET CONDITONS
   //

   // Implement soft reset (spacebar)
   if(inpCtrl && inpCtrl->pressedSpace())
   {
      // Play game end sound
      Game.sndId = qeSndPlay(snd[SDR_INDX_STR_END_GAME].name);

      // Reposition ball's position
      if(ball = Game.ball)
      {
         ball->xyz.x = 0;
         ball->xyz.z = 0;
      } // if
      
      // Pause game very briefly
      qeSleep(0.5);

      // Manage scores of each paddle
      for(int i=0; i<NUM_PLYRS; i++)
      {
         // Record last scores
         Game.lastScores[i] = Game.scores[i];

         // Clear scores, to prevent this routine from running concurrently
         Game.scores[i] = 0;

         // Reset the z-position of each paddle
         if(paddles[i] = Game.paddles[i])
         {
            paddles[i]->xyz.z = PADDLE_INIT_Z;
         } // if
      } // for 

      // Skip rest of game loop
      goto END_RESET;

   } // if

   // Implement hard reset (pressing "1")
   if(inpCtrl && inpCtrl->pressedOne())
   {
      // Play game end sound
      Game.sndId = qeSndPlay(snd[SDR_INDX_STR_END_GAME].name);

      // Pause game
      qeSleep(1.5);

      // Reinitialize game
      gameFinal();
      gameInit();
      gameSetup();

      // Skip rest of game loop
      goto END_RESET;
   } // if

   //
   // DRAW
   //

   // DRAW 3D

   // set 3D camera
   if((cam=Game.cam) && !(qeInpButton(QEINPBUTTON_ZERO)&2))
   {
      cam->apply(); // set the camera
   } // if

   // DRAW COURT, PADDLES, BALL

   // Draw court
   if(court=Game.court)
   {
      court->draw();
   } // if

   // Draw paddles
   for(int i=0; i<NUM_PLYRS; i++)
   {
      if(paddles[i] = Game.paddles[i])
      {
         paddles[i]->draw();
      } // if
   } // for

   // Draw ball
   if(ball=Game.ball)
   {
      ball->draw();
   } // if

   // DRAW HUD

   qefnSysCamBitmap(); // set camera (also turns off depth testing)

   if((hud=Game.hud))
   {
      hud->draw();
   } // if

END_RESET:

    return 0;
} // gameMainLoop()
Ejemplo n.º 19
0
void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(screenMode == 0)
    {
        /*Beginning page*/
        //Start Game button
        if(event->scenePos().x() > btn_start->pos().x()+20 && event->scenePos().x() <= btn_start->pos().x()+80)
        {
           if(event->scenePos().y() > btn_start->pos().y()+20 && event->scenePos().y() <= btn_start->pos().y()+80)
           {
               if(x == 1)
               {
               cout<<"Start Game!"<<endl;
               bgChange();
               gameInit();
               screenMode = 1;
               /*start counting time*/
               mytime->startTime();

               //stop bgm
               bgm->stop();
               bgm2->play();
               }

           }
        }
        /*Beginning page*/
        //Exit button
        else if(event->scenePos().x() > btn_exit->pos().x()+20 && event->scenePos().x() <= btn_exit->pos().x()+100)
        {
            if(event->scenePos().y() > btn_exit->pos().y()+20 && event->scenePos().y() <= btn_exit->pos().y()+110)
            {
                if(x == 1)
                {
                    bgm->stop();
                    haha->play();
                    QTimer::singleShot(8000,this,SLOT(endofgame()));
                    //QApplication::exit();
                    x = 0;
                }
            }
        }
    }

    if(screenMode == 1)
    {

        /*Playing page*/
        //Back button setting
        if(event->scenePos().x() > btn_back->pos().x() && event->scenePos().x() <= btn_back->pos().x()+btn_back_w)
        {
            if(event->scenePos().y() > btn_back->pos().y() && event->scenePos().y() <= btn_back->pos().y()+btn_back_h)
            {
                bgRecover();
                gameInit();
                removeItem(score1);
                removeItem(mytime);

                //Initialize
                drum_list.clear();
                rand_list.clear();
                num =0;
                num_drum = 0;
                screenMode = 0;

                //add back sound
                bgm->play();
                bgm2->stop();
            }
        }
    }

}
Ejemplo n.º 20
0
/** @brief	The game loop function
  * @param  p_structCommon : Struct with all program informations
  */
void playGame(structProgramInfo* p_structCommon)
{
	unsigned char l_cKey;
    char* l_sTopText;
    unsigned int l_iWatchdog;
	unsigned int l_iCursorX;
	unsigned int l_iCursorY;
    unsigned int l_iMovement;	/* store the wanted move, if impossible this variable */
    unsigned int l_iCurrentSocketIndex;		/* allow the program to go back */
    int l_iNewCoordinates;
    char l_bForceRedraw;

    l_bForceRedraw = TRUE;
	l_cKey = 0;
    l_iNewCoordinates = -1;
	l_iMovement = 0;
	l_iCursorX = 1;
	l_iCursorY = 1;
    p_structCommon->iLastXUsed = l_iCursorX;
    p_structCommon->iLastYUsed = l_iCursorY;
    l_iCurrentSocketIndex = 0;
	p_structCommon->iOffsetX = (p_structCommon->iCol / 2) - (p_structCommon->iSizeX / 2);
	p_structCommon->iOffsetY = (p_structCommon->iRow / 2) - (p_structCommon->iSizeY / 2);
    l_sTopText = (char*)malloc((p_structCommon->iCol + 1) * sizeof(char));
    if(l_sTopText == NULL) exit(-ENOMEM);

	p_structCommon->iCurrentUserColor = enumRouge; /* Main user, or server always red. If multiplayer and client, it receive another color suring connection  */
    p_structCommon->cUserMove = 0;

	/* Init the game, screen stuff etc... */
	gameInit(p_structCommon);

	do
	{
        snprintf(   l_sTopText,
                    p_structCommon->iCol,
                    "Your turn to play [ ] | Connected [ ] | Current port [%d] | Nickname %s",
                    p_structCommon->iTcpPort,
                    p_structCommon->sUserName);
        if(p_structCommon->bMyTurnToPlay == TRUE)
        {
            l_sTopText[19] = 'X';
        }
        else
        {
            l_sTopText[19] = ' ';
        }

        if(p_structCommon->bMutexInitialized == TRUE)
        {
            l_sTopText[35] = 'X';
        }
        else
        {
            l_sTopText[35] = ' ';
        }

        if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_lock(p_structCommon->pthreadMutex);}
        usleep(TIME_BETWEEN_TWO_REQUEST);
        initBar();
        topText(l_sTopText);

		/* Display wursor each time */
		displayCursor(l_iCursorX, l_iCursorY, p_structCommon->iOffsetX, p_structCommon->iOffsetY, FALSE, p_structCommon->cGrid);
        pointCounting(p_structCommon->cGrid, p_structCommon->iPoints, p_structCommon->iSizeX, p_structCommon->iSizeY);
        displayRanking(p_structCommon->iPoints, p_structCommon->iCol, p_structCommon->iRow);
        topText(l_sTopText);
		refresh();
        usleep(TIME_BETWEEN_TWO_REQUEST);
        if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_unlock(p_structCommon->pthreadMutex);}

		l_cKey = getch();

        /* In order to allow an alone player to play alone */
        if(p_structCommon->bMutexInitialized == FALSE)
        {
            p_structCommon->bMyTurnToPlay = TRUE;
        }

		switch(l_cKey)
		{

			case 'D':
			{
				/* LEFT */
				l_iCursorX = (l_iCursorX < 1) ? p_structCommon->iSizeX - 1 : l_iCursorX - 1;
                p_structCommon->cUserMove = 'd';
				l_iMovement = DIRECTION_LEFT;
				break;
			}
			case 'C':
			{
				/* RIGHT */
				l_iCursorX = (l_iCursorX > p_structCommon->iSizeX - 2) ?
                    0 : l_iCursorX + 1;
                p_structCommon->cUserMove = 'c';
				l_iMovement = DIRECTION_RIGHT;
				break;
			}
			case 'A':
			{
				/* UP */
				l_iCursorY = (l_iCursorY < 1) ? p_structCommon->iSizeY - 1 : l_iCursorY - 1;
                p_structCommon->cUserMove = 'a';
				l_iMovement = DIRECTION_UP;
				break;
			}
			case 'B':
			{
				/* DOWN */
				l_iCursorY = (l_iCursorY > p_structCommon->iSizeY - 2) ?
                    0 : l_iCursorY + 1;
                p_structCommon->cUserMove = 'b';
				l_iMovement = DIRECTION_DOWN;
				break;
			}
            case ':':
            {
                /* Command mode */
                l_bForceRedraw = TRUE;
                logBar(p_structCommon, CLEAN_L2, "");
                if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_lock(p_structCommon->pthreadMutex);}
                logBar(p_structCommon, DISPLAY, "");
                if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_unlock(p_structCommon->pthreadMutex);}

                /* Get command from the user, the command set by the user will be saved in p_structCommon->sUserCommand */
                userCommandGetter(p_structCommon);
                /* Analyse user command */
                l_iNewCoordinates = userCommandExecute(p_structCommon);
                if(l_iNewCoordinates > - 1)
                {
                    if(l_iNewCoordinates > - 1 && l_iNewCoordinates < (signed)p_structCommon->iSizeX)
                    {
                        /* belongs to the interval [0 ; p_structCommon->iSizeX[ ==> redefine X coordinate */
                        l_iCursorX = l_iNewCoordinates;
                        l_bForceRedraw = FALSE;
                    }
                    else if(l_iNewCoordinates >= (signed)p_structCommon->iSizeX &&
                            l_iNewCoordinates < (signed)p_structCommon->iSizeX + (signed)p_structCommon->iSizeY)
                    {
                        /* belongs to the interval [p_structCommon->iSizeX ; p_structCommon->iSizeX + p_structCommon->iSizeY[ ==> redefine Y coordinate */
                        l_iCursorY = l_iNewCoordinates - (p_structCommon->iSizeX);
                        l_bForceRedraw = FALSE;
                    }
                }

                if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_lock(p_structCommon->pthreadMutex);}
                displayCursor(l_iCursorX, l_iCursorY, p_structCommon->iOffsetX, p_structCommon->iOffsetY, l_bForceRedraw, p_structCommon->cGrid);
                refresh();

                /* Clean the screen */
                logBar(p_structCommon, DISPLAY, "");
                if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_unlock(p_structCommon->pthreadMutex);}
                break;
            }
            case 'q':
            case 'Q':
            {
                p_structCommon->bNetworkDisconnectionRequiered = TRUE;

                /* Started threads have to down this flag -- bMutexInitialized means we have at least one thread started */
                while(p_structCommon->bNetworkDisconnectionRequiered == TRUE &&
                      p_structCommon->bMutexInitialized == TRUE)
                {
                    usleep(TIME_BETWEEN_TWO_REQUEST);
                    for(l_iCurrentSocketIndex = 0; l_iCurrentSocketIndex < MAX_CONNECTED_CLIENTS ; l_iCurrentSocketIndex++)
                    {
                        if(p_structCommon->iClientsSockets[l_iCurrentSocketIndex] != 0)
                        {
                            break;
                        }
                    }
                    if(l_iCurrentSocketIndex >= MAX_CONNECTED_CLIENTS - 1)
                    {
                        break;
                    }
                }   
                break;

                /* Normally, network.c have clean the mutex at the end of all connexions */
                if(p_structCommon->bMutexInitialized == TRUE)
                {
                    pthread_mutex_destroy(p_structCommon->pthreadMutex);
                    p_structCommon->bMutexInitialized = FALSE;
                }
            }
			case ' ':
			{
                if(p_structCommon->bMyTurnToPlay != TRUE)
                {
                    break;
                }

				/* When the user drop a rock */
                p_structCommon->cUserMove = 'r';
                p_structCommon->iLastXUsed = l_iCursorX;
                p_structCommon->iLastYUsed = l_iCursorY;

				/* Put the color information in the matrix */
				p_structCommon->cGrid[COLOR_MATRIX][l_iCursorY][l_iCursorX] =
					p_structCommon->iCurrentUserColor;

				/* Put the text information in the matrix */
				p_structCommon->cGrid[TEXT_MATRIX][l_iCursorY][l_iCursorX] =
					' ';

                /* declare this point to be synchronized with all clients */
                p_structCommon->cGrid[SYNC_MATRIX][l_iCursorY][l_iCursorX] = POINT_TO_SYNC;

                /* Draw the block of the current user (the other blocks are draw by
                    another function) */
                if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_lock(p_structCommon->pthreadMutex);}
				drawElement(l_iCursorX + p_structCommon->iOffsetX, l_iCursorY + p_structCommon->iOffsetY,
					p_structCommon->cGrid[TEXT_MATRIX][l_iCursorY][l_iCursorX],
					p_structCommon->iCurrentUserColor);
                if(p_structCommon->bMutexInitialized != TRUE) {pthread_mutex_unlock(p_structCommon->pthreadMutex);}

                /* Check neighborhood - If there is two contigous blocks of the player's
                   color that means there is maybee a loop */
                loopCompletion(l_iCursorX, l_iCursorY, p_structCommon->iCurrentUserColor, p_structCommon);

                /* Reset this player turn */
                p_structCommon->bMyTurnToPlay = FALSE;
                break;
			}

			default:
			{
				/* Else, do nothing */
				break;
			}
		}

		/* Check code, in order to forbid access to already reserved boxes */
		if((unsigned int)p_structCommon->cGrid[COLOR_MATRIX][l_iCursorY][l_iCursorX] != enumNoir)
		{
			/* So there is something here and it is not me */
			switch(l_iMovement)
			{
				case DIRECTION_UP:
				l_iCursorY++;
				break;
				case DIRECTION_DOWN:
				l_iCursorY--;
				break;
				case DIRECTION_LEFT:
				l_iCursorX++;
				break;
				case DIRECTION_RIGHT:
				l_iCursorX--;
				break;
				default:
				/* Who, error ! */
				perror("Unknown code");
				break;
			}

			/* If we go out of the screen by the upper or wester side put it in 0:0 and
			let the next block check if this block is empty or not */
			if(l_iCursorY >= p_structCommon->iSizeY || l_iCursorX >= p_structCommon->iSizeX)
			{
				l_iCursorX = 0;
				l_iCursorY = 0;
			}

			/* If with bad luck you go over the grid */
            l_iWatchdog = 0;
			while((unsigned int)p_structCommon->cGrid[COLOR_MATRIX][l_iCursorY][l_iCursorX] != enumNoir)
			{
				/* Find random coordinate with the simplest way */
				l_iCursorX = rand() % p_structCommon->iSizeX;
				l_iCursorY = rand() % p_structCommon->iSizeY;

                l_iWatchdog++;
                if(l_iWatchdog > (p_structCommon->iSizeX * p_structCommon->iSizeY) / 2)
                {
                    if(isTheGridFull(p_structCommon) == TRUE)
                    {
                        endOfTheGame(p_structCommon);
                        return;
                    }
                }
			}
		}
	}while((l_cKey != 'q') && (l_cKey != 'Q'));		/* until q/Q pressed */

    free(l_sTopText);

}
Ejemplo n.º 21
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();
					}
				}
			}
Ejemplo n.º 22
0
void gameStart(int mode)
{

    bool success;//是否下落成功;若失败,则说明沉底
    int i, j, k, t = 0;
    int cmd = 0;
    int timeLeft[TOTAL_PLAYER+1] = {0, 1000, 1000};
    Block tpBlk[TOTAL_PLAYER+1];

    gameInit();//初始化游戏

    while(1)
    {

        for(i = 1; i <= TOTAL_PLAYER; i++)
        {
            t++;//计时器增加
            setorigin(0, 0); //设置原点
            recoverBk(0, g_player[i].preview.y + 4 * BLOCK_SIZE, 160, 30);
            recoverBk(0, 480 - 30, 160, 30); //重绘预览区
            printScore(t);//显示得分
            drawStageLine();//绘制边界线
            FlushBatchDraw();//执行绘图


            if(g_player[i].dropped == true)
            {

                saveState(i, g_player[i].nowBlk);//保存方块的存在状态


                if(mode == CLEAR && g_player[1+(i==1)].score >= 100)gameOver(i);
                if(reachTop(i))
                {
                    gameOver(i);
                    continue;
                }//判断游戏结束

                k = fullColumn(i);
                if(k > 0)
                {
                    g_player[i].score += k * k;
                    if(mode == NORMAL && g_player[i].score % 10 == 0)newColumn(1 + (i == 1));
                }//计分与消行

                tpBlk[i] = g_player[i].preBlk; //备份预览方块
                g_player[i].nowBlk = preToNow(g_player[i].preBlk);//previewBlock变为player[1].nowBlk
                g_player[i].preBlk = createBlk(); //产生新的预览方块
                refreshBlk(i, tpBlk[i], g_player[i].preBlk, PREVIEW); //绘制新的previewBlock

                g_player[i].dropped = false;


            }


            getCmd(&cmd);//获得命令
            timeLeft[i] -= 10;
            for  (j = 1; j <= TOTAL_PLAYER; j++)
            {

                tpBlk[j] = g_player[j].nowBlk;

                success = DispatchCommand(j, cmd);
                if(success)refreshBlk(j, tpBlk[j], g_player[j].nowBlk);
                else continue;

            }//在一个玩家的循环中要同时处理两个玩家

            if(timeLeft[i] <= 0)
            {
                if(mode == NORMAL)timeLeft[i] = INIT_DELAY - (int)(2.5 * g_player[1+(i==1)].score);
                else timeLeft[i] = (int)(INIT_DELAY - (t / 1000.0)); //速度规则
                if(timeLeft[i] < MIN_DELAY)timeLeft[i] = 3 * MIN_DELAY;

                tpBlk[i] = g_player[i].nowBlk;
                if(i == 1)
                    success = DispatchCommand(1, CMD_DOWN);
                else
                    success = DispatchCommand(2, CMD_DOWN2);
                if(success)refreshBlk(i, tpBlk[i], g_player[i].nowBlk);

            }

        }


    }
    getch();
    closegraph();
}
Ejemplo n.º 23
0
int main(void){
	int i = 0;
	//Score set
	score = 0;
	PLL_Init();
	//Sound init
	DAC_Init();
	Timer0A_Init(Sound_Update, 1000000/11025);
//	Timer0B_Init(updateXAxis, 1000000/11025);
//	Timer1B_Init(updateYAxis, 1000000/11025);
	//Input
	ADC_Init();
	portD_Init();
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
												GPIOPinTypeGPIOInput(GPIO_PORTG_BASE,
												(GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7));
												GPIOPinTypeGPIOOutput(GPIO_PORTG_BASE, GPIO_PIN_2);
												GPIOPadConfigSet(GPIO_PORTG_BASE,
												(GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7),
												GPIO_STRENGTH_2MA,
												GPIO_PIN_TYPE_STD_WPU);
	SysTick_Init(50000000/400);
	Output_Init();
	Output_Color(15);
	SysTick_IntEnable();
	EnableInterrupts();
	//Set flags
	gFlags = 0;
	HWREGBITW(&gFlags, TITLE_SCREEN) = True;	
	//Math rand set seed
	while(HWREGBITW(&gFlags, SELECT_DOWN) == 0 &&
				((GPIO_PORTG_DATA_R & 0x80) != 0)) { }
	while(HWREGBITW(&gFlags, SELECT_DOWN) == 1 ||
				((GPIO_PORTG_DATA_R & 0x80) == 0)) { }
	setSeed(NVIC_ST_CURRENT_R);
	//Game set
	setGraphics(1);//the lm3s can't handle more than 2 rocks at graphics level 3.
	gameInit();
	gameSet(0);
	while(1) {
		//Only draw to buffer when it has been output to the screen
		if(HWREGBITW(&gFlags, FRAME_BUFFER_READY) == False) {
			/*if(gameLevel == -2) {
				drawString(myMsgs[1], makePoint(50, 40));
				while ((GPIO_PORTG_DATA_R & 0x80) != 0 &&
							 HWREGBITW(&gFlags, SELECT_DOWN) == False) { }
				while ((GPIO_PORTG_DATA_R & 0x80) == 0 &&
							 HWREGBITW(&gFlags, SELECT_DOWN) == True) { }
				//Reset game
			*/
			//Check for level completion, aka all rocks and enemies are 
			//TODO: enemies
			if(HWREGBITW(&gFlags, LEVEL_COMPLETE) == True) { gameSet(++gameLevel); }
			//Redraw the screen from scratch.
			clearBuffer();
			//Draw the player.
			if(gPlayer.status == ALIVE) {
				drawPlayer(makePoint((int)gPlayer.x, (int)gPlayer.y),
									 gPlayer.angle, gPlayer.exhaustOn);
			}
			for(i = 0; i < MAX_ROCKS; i++) {
				if(gRocks[i].status == ALIVE) {
					drawRock(makePoint(gRocks[i].x, gRocks[i].y),
									 gRocks[i].rockType, gRocks[i].rockSize);
				}
			}
			//Draw allied bullets.
			for(i = 0; i < MAX_PLAYER_BULLETS; i++) {
				if(gPlayerBullets[i].status == ALIVE) {
					drawBullet(makePoint(gPlayerBullets[i].x, gPlayerBullets[i].y));
				}
			}
			//Draw enemy bullets.
			for(i = 0; i < MAX_ENEMY_BULLETS; i++) {
				if(gEnemyBullets[i].status == ALIVE) {
					drawBullet(makePoint(gEnemyBullets[i].x, gEnemyBullets[i].y));
				}
			}
			//Draw explosions.
			for(i = 0; i < MAX_EXPLOSIONS; i++) {
				if(gExplosions[i].status == ALIVE) {
					drawExplosion(gExplosions[i].pos, gExplosions[i].current);
				}
			}
			
			//
			drawNumber(score, makePoint(2,2));
			drawNumber(gameLevel, makePoint(128/2-6,2));
			
			if(HWREGBITW(&gFlags, GAME_OVER) == True) {
				drawString("GAME OVER", makePoint(40, 38));
				if((GPIO_PORTG_DATA_R & 0x80)) {
					//reset game
				}
				gameUpdate();
			} else if(HWREGBITW(&gFlags, TITLE_SCREEN) == True) {
				drawString("ASTEROIDS", makePoint(40, 38));
				gameLevel = 0;
			}
			updateXAxis();
			gameUpdate();
			HWREGBITW(&gFlags, FRAME_BUFFER_READY) = True;
		}
	}
}
Ejemplo n.º 24
0
Archivo: game.c Proyecto: hk0i/annoi
/* gameReset: resets the game (same as gameInit()) */
void gameReset(int max)
{
    gameInit(max);
}