Ejemplo n.º 1
0
/***********************************************************
synopsis: a big while loop that runs the full length of the
	  game, checks the game events and responds
	  accordingly

	  event		action
	  -------------------------------------------------
	  winGame	stop the clock and solve puzzle
	  timeRemaining update the clock tick
	  timeUp	stop the clock and solve puzzle
	  solvePuzzle	trigger solve puzzle and stop clock
	  updateAnswers trigger update answers
	  startNew      trigger start new
	  updateScore	trigger update score
	  shuffle	trigger shuffle
	  clear		trigger clear answer
	  quit		end loop
	  poll events   check for keyboard/mouse and quit

	  finally, move the sprites -this is always called
	  so the sprites are always considered to be moving
	  no "move sprites" event exists - sprites x&y just
	  needs to be updated and they will always be moved

inputs: head - first node in the answers list (in/out)
        dblHead - first node in the dictionary list
	screen - the SDL_Surface to display the image
	letters - first node in the letter sprites (in/out)

outputs: n/a
***********************************************************/
static void
gameLoop(struct node **head, struct dlb_node *dlbHead, 
         SDL_Surface *screen, struct sprite **letters)
{
	int j,k;
    int done=0;
	int numofwords=1;
    SDL_Event event;
    time_t timeNow;
    SDL_TimerID timer;
    int timer_delay = 20;
    char buffer[512];

	#ifdef demo
	
	if (conf.totalgames < 0){
		conf.totalgames=8;
	}
	conf.totalgames +=1;//demo tags
	sprintf(buffer,"globaldata/agdemo.cfg");
	saveCFG(buffer,&conf);
	#endif

    timer = SDL_AddTimer(timer_delay, TimerCallback, NULL);
	/* main game loop */
	while (!done) {

		if (winGame) {
			stopTheClock = 1;
			solvePuzzle = 1;
		}

		if ((gameTime < AVAILABLE_TIME) && !stopTheClock) {
			timeNow = time(0) - gameStart;
			if (timeNow != gameTime){
				gameTime = timeNow;
				updateTime(screen);
			}
		} else {
			if (!stopTheClock){
				stopTheClock = 1;
				solvePuzzle = 1;
			}
		}

		/* check messages */
		if (solvePuzzle) {
			/* walk the list, setting everything to found */
			solveIt(*head);
			clearWord(letters);
			strcpy(shuffle, SPACE_FILLED_STRING);
			strcpy(answer, rootWord);
			/*displayLetters(screen);*/
			displayAnswerBoxes(*head, screen);
			gamePaused = 1;
			if (!stopTheClock){
				stopTheClock = 1;
			}
			solvePuzzle = 0;
		}

		if (updateAnswers){
			/* move letters back down again */
			clearWord(letters);
			/* displayLetters(screen);*/
			displayAnswerBoxes(*head, screen);

			updateAnswers = 0;
		}


		if ((stopTheClock && !gotBigWord && !checkScore)||(startNewGame&&!gotBigWord& !checkScore)){
			//Error("inside highscore\n");
			for(j=9;j>=0 && hiscore[j].score<totalScore;j--);
				//Error("score position: %i\n",j);
			/* the player will be in the hall of fame? */
			if(j<9) {
				for(k=8;k>j;k--)
					hiscore[k+1]=hiscore[k];

				/* put the new score */
				hiscore[j+1].score=totalScore;
				hiscore[j+1].stage=numofwords;
				
				 //hiscore[j+1].name[0]=0;
				//if(!getName(hiscore[j+1].name, j+2,i+1))
				//	break; /* probably a problem if the user closes the window */

				/* show the hall of fame */
				//hiscores();

				/* save hi-scores */
				#ifdef demo
				sprintf(buffer,"/media/internal/appdata/com.cribme.aghddemo/ag-hiscore");
				#else
				sprintf(buffer,"/media/internal/appdata/com.cribme.aghd/ag-hiscore");
				#endif
				//sprintf(buffer,"globaldata/ag-hiscore");
				if(!saveScore(buffer,hiscore))
				fprintf(stderr,"unable to save hi-scores\ndo you have permissions to write into %s?\n" ,buffer);
				
			}
			checkScore=1;
		}

		if (startNewGame) {
			/* move letters back down again */
			if (!gotBigWord){
				totalScore = 0;
				numofwords=0;
			}
			newGame(head, dlbHead, screen, letters);

			#ifdef demo
			conf.totalgames +=1;//demo tags
			char buffer[512];
			sprintf(buffer,"globaldata/agdemo.cfg");
			//Error("Buffer :%s\n",buffer);
			//Error("TotalGames Written to file :%i\n",conf.totalgames);
			saveCFG(buffer,&conf);
			#endif

			numofwords+=1;
			checkScore = 0;
			startNewGame = 0;
		}

		if (updateTheScore) {
			updateScore(screen);
			updateTheScore = 0;
		}

		if (shuffleRemaining) {
			/* shuffle up the shuffle box */
			char shuffler[8];
			strcpy(shuffler, shuffle);
			shuffleAvailableLetters(shuffler, letters);
			strcpy(shuffle, shuffler);
			shuffleRemaining = 0;
		}

		if (clearGuess) {
			/* clear the guess; */
			if (clearWord(letters) > 0) {
				Mix_PlayChannel(-1, getSound("clear"),0);
            }
			clearGuess = 0;
		}
		#ifdef demo
		//Error("TotalGames:%i\n",conf.totalgames);//conf.totalgames
		if (conf.totalgames > 8){//conf.totalgames
		    destroyLetters(letters);
			strcpy(txt, language);
			ShowBMP(strcat(txt,"images/demo.bmp"),screen, 100,75);
			done=1;
		}

		#endif

		if (quitGame) {
			done = 1;
		}
		if (inactive){
			SDL_WaitEvent(&event);
				if (event.type == SDL_ACTIVEEVENT && event.active.gain == 1) {
				inactive = 0;
				timer = SDL_AddTimer(timer_delay, TimerCallback, NULL);
				}
		}
		else {
		while (SDL_WaitEvent(&event)) {
			if (event.type == SDL_ACTIVEEVENT && event.active.gain == 0) {
				inactive = 1;
				break;
			}
			if (event.type == SDL_USEREVENT) {
                timer_delay = anySpritesMoving(letters) ? 10 : 100;
                moveSprites(&screen, letters, letterSpeed);
                timer = SDL_AddTimer(timer_delay, TimerCallback, NULL);
                break;
            } else if (event.type == SDL_MOUSEBUTTONDOWN) {
                clickDetect(event.button.button, event.button.x,
                            event.button.y, screen, *head, letters);
				moveSprites(&screen, letters, letterSpeed);//added by me
            } else if (event.type == SDL_KEYUP) {
                handleKeyboardEvent(&event, *head, letters);
            } else if (event.type == SDL_QUIT) {
                done = 1;
                break;	
			} 
				
		}
		}
    }
	#ifdef demo
	while(conf.totalgames > 8){//conf.totalgames
		while(SDL_WaitEvent(&event)){
				if (event.type == SDL_MOUSEBUTTONDOWN) {
				PDL_ServiceCall("palm://com.palm.applicationManager/open", "{\"target\":\"http://developer.palm.com/appredirect/?packageid=com.cribme.aghd\"}");
					//PDL_LaunchBrowser("http://developer.palm.com/appredirect/?packageid=com.cribme.aghd");
				}
		}
	}
	#endif

	
}
Ejemplo n.º 2
0
char *Sys_GetClipboardData( clipboard_t clip )
{
#ifndef DEDICATED
	// derived from SDL clipboard code (http://hg.assembla.com/SDL_Clipboard)
	Window        owner;
	Atom          selection;
	Atom          converted;
	Atom          selectionType;
	int           selectionFormat;
	unsigned long nbytes;
	unsigned long overflow;
	char          *src;

	if ( x11.display == NULL )
	{
		SDL_SysWMinfo info;

		SDL_VERSION( &info.version );
		if ( SDL_GetWMInfo( &info ) != 1 || info.subsystem != SDL_SYSWM_X11 )
		{
			Com_Printf("Not on X11? (%d)\n",info.subsystem);
			return NULL;
		}

		x11.display = info.info.x11.display;
		x11.window = info.info.x11.window;
		x11.lockDisplay = info.info.x11.lock_func;
		x11.unlockDisplay = info.info.x11.unlock_func;
		x11.utf8 = XInternAtom( x11.display, "UTF8_STRING", False );

		SDL_EventState( SDL_SYSWMEVENT, SDL_ENABLE );
		//SDL_SetEventFilter( Sys_ClipboardFilter );
	}

	x11.lockDisplay();

	switch ( clip )
	{
	// preference order; we use fall-through
	default: // SELECTION_CLIPBOARD
		selection = XInternAtom( x11.display, "CLIPBOARD", False );
		owner = XGetSelectionOwner( x11.display, selection );
		if ( owner != None && owner != x11.window )
		{
			break;
		}

	case SELECTION_PRIMARY:
		selection = XA_PRIMARY;
		owner = XGetSelectionOwner( x11.display, selection );
		if ( owner != None && owner != x11.window )
		{
			break;
		}

	case SELECTION_SECONDARY:
		selection = XA_SECONDARY;
		owner = XGetSelectionOwner( x11.display, selection );
	}

	converted = XInternAtom( x11.display, "UNVANQUISHED_SELECTION", False );
	x11.unlockDisplay();

	if ( owner == None || owner == x11.window )
	{
		selection = XA_CUT_BUFFER0;
		owner = RootWindow( x11.display, DefaultScreen( x11.display ) );
	}
	else
	{
		SDL_Event event;

		x11.lockDisplay();
		owner = x11.window;
		//FIXME: when we can respond to clipboard requests, don't alter selection
		XConvertSelection( x11.display, selection, x11.utf8, converted, owner, CurrentTime );
		x11.unlockDisplay();

		for (;;)
		{
			SDL_WaitEvent( &event );

			if ( event.type == SDL_SYSWMEVENT )
			{
				XEvent xevent = event.syswm.msg->event.xevent;

				if ( xevent.type == SelectionNotify &&
				     xevent.xselection.requestor == owner )
				{
					break;
				}
			}
		}
	}

	x11.lockDisplay ();

	if ( XGetWindowProperty( x11.display, owner, converted, 0, INT_MAX / 4,
	                         False, x11.utf8, &selectionType, &selectionFormat,
	                         &nbytes, &overflow, (unsigned char **) &src ) == Success )
	{
		char *dest = NULL;

		if ( selectionType == x11.utf8 )
		{
			dest = Z_Malloc( nbytes + 1 );
			memcpy( dest, src, nbytes );
			dest[ nbytes ] = 0;
		}
		XFree( src );

		x11.unlockDisplay();
		return dest;
	}

	x11.unlockDisplay();
#endif // !DEDICATED
	return NULL;
}
Ejemplo n.º 3
0
int
main(int argc, char *argv[])
{
    const char *name;
    int i;
    SDL_Joystick *joystick;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);	

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }

    /* Print information about the joysticks */
    SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks());
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        name = SDL_JoystickNameForIndex(i);
        SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
        joystick = SDL_JoystickOpen(i);
        if (joystick == NULL) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i,
                    SDL_GetError());
        } else {
            char guid[64];
            SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
                                      guid, sizeof (guid));
            SDL_Log("       axes: %d\n", SDL_JoystickNumAxes(joystick));
            SDL_Log("      balls: %d\n", SDL_JoystickNumBalls(joystick));
            SDL_Log("       hats: %d\n", SDL_JoystickNumHats(joystick));
            SDL_Log("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
            SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
            SDL_Log("       guid: %s\n", guid);
            SDL_JoystickClose(joystick);
        }
    }

#ifdef ANDROID
    if (SDL_NumJoysticks() > 0) {
#else
    if (argv[1]) {
#endif
        SDL_bool reportederror = SDL_FALSE;
        SDL_bool keepGoing = SDL_TRUE;
        SDL_Event event;
        int device;
#ifdef ANDROID
        device = 0;
#else
        device = atoi(argv[1]);
#endif
        joystick = SDL_JoystickOpen(device);

        while ( keepGoing ) {
            if (joystick == NULL) {
                if ( !reportederror ) {
                    SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError());
                    keepGoing = SDL_FALSE;
                    reportederror = SDL_TRUE;
                }
            } else {
                reportederror = SDL_FALSE;
                keepGoing = WatchJoystick(joystick);
                SDL_JoystickClose(joystick);
            }

            joystick = NULL;
            if (keepGoing) {
                SDL_Log("Waiting for attach\n");
            }
            while (keepGoing) {
                SDL_WaitEvent(&event);
                if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
                    || (event.type == SDL_MOUSEBUTTONDOWN)) {
                    keepGoing = SDL_FALSE;
                } else if (event.type == SDL_JOYDEVICEADDED) {
                    joystick = SDL_JoystickOpen(device);
                    break;
                }
            }
        }
    }
    else {
        SDL_Log("\n\nUsage: ./controllermap number\nFor example: ./controllermap 0\nOr: ./controllermap 0 >> gamecontrollerdb.txt");
    }
    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);

    return 0;
}

#else

int
main(int argc, char *argv[])
{
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
    exit(1);
}
Ejemplo n.º 4
0
void jouerUnJoueur(int **plateau, int taillePlateau, int nbrAtomes)
{
	SDL_Surface *ecran = NULL;
	SDL_Event event;
	
	SDL_Init(SDL_INIT_VIDEO);
	SDL_WM_SetCaption("Black Box Game", NULL);
	ecran = SDL_SetVideoMode(TAILLE_CASE * taillePlateau, TAILLE_CASE * (taillePlateau+1), 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
	SDL_Surface *win = SDL_LoadBMP("/img/win.bmp"), *lost = SDL_LoadBMP("/img/gameover.bmp");
	SDL_Rect positionJeu;
	positionJeu.x = ecran->w/2 - win->w/2;
	positionJeu.y = ecran->h/2 - win->h/2;
	int continuer = 1;
	int status = ENCOURS;
	int score = 100;
	//printf("atomes %d",nbrAtomes);
	int nombreAtomeRestantATrouver = nbrAtomes;
	
	while (continuer)
	{
		SDL_WaitEvent(&event);
		switch(event.type)
		{
			case SDL_QUIT:
				continuer = 0;
				break;
			case SDL_KEYDOWN:
				if(event.key.keysym.sym == SDLK_ESCAPE)  // Veut arrêter le jeu
				{
					continuer = 0;
				}
				break;
			case SDL_MOUSEBUTTONDOWN:
				if(event.button.button == SDL_BUTTON_LEFT)
				{
					status = ENCOURS;
					gestionClic(event.button.x / TAILLE_CASE, event.button.y / TAILLE_CASE, plateau, taillePlateau, &status);
				}
				break;
			default:
				status = ENCOURS;
				break;
				
		}
		drawBoard(ecran, taillePlateau, plateau, nombreAtomeRestantATrouver, score);
		int etat = verifierFin(&score, status,taillePlateau, &nombreAtomeRestantATrouver);
		if (etat == PERDU) {
			// afficher ecran perte
			SDL_BlitSurface(lost, NULL, ecran, &positionJeu);
			SDL_Flip(ecran);
			SDL_Delay(2000);
			continuer = 0;
		} else if (etat == GAGNE) {
			SDL_BlitSurface(win,NULL,ecran,&positionJeu);
			SDL_Flip(ecran);
			SDL_Delay(2000);
			// afficher ecran winner
			continuer = 0;
		}
		status = ENCOURS;
		
	}
}
Ejemplo n.º 5
0
int
main(int argc, char *argv[])
{
    const char *name, *type;
    int i;
    SDL_Joystick *joystick;

    SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }

    /* Print information about the joysticks */
    SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks());
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        name = SDL_JoystickNameForIndex(i);
        SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
        joystick = SDL_JoystickOpen(i);
        if (joystick == NULL) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i,
                    SDL_GetError());
        } else {
            char guid[64];
            SDL_assert(SDL_JoystickFromInstanceID(SDL_JoystickInstanceID(joystick)) == joystick);
            SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
                                      guid, sizeof (guid));
            switch (SDL_JoystickGetType(joystick)) {
            case SDL_JOYSTICK_TYPE_GAMECONTROLLER:
                type = "Game Controller";
                break;
            case SDL_JOYSTICK_TYPE_WHEEL:
                type = "Wheel";
                break;
            case SDL_JOYSTICK_TYPE_ARCADE_STICK:
                type = "Arcade Stick";
                break;
            case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
                type = "Flight Stick";
                break;
            case SDL_JOYSTICK_TYPE_DANCE_PAD:
                type = "Dance Pad";
                break;
            case SDL_JOYSTICK_TYPE_GUITAR:
                type = "Guitar";
                break;
            case SDL_JOYSTICK_TYPE_DRUM_KIT:
                type = "Drum Kit";
                break;
            case SDL_JOYSTICK_TYPE_ARCADE_PAD:
                type = "Arcade Pad";
                break;
            case SDL_JOYSTICK_TYPE_THROTTLE:
                type = "Throttle";
                break;
            default:
                type = "Unknown";
                break;
            }
            SDL_Log("       type: %s\n", type);
            SDL_Log("       axes: %d\n", SDL_JoystickNumAxes(joystick));
            SDL_Log("      balls: %d\n", SDL_JoystickNumBalls(joystick));
            SDL_Log("       hats: %d\n", SDL_JoystickNumHats(joystick));
            SDL_Log("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
            SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
            SDL_Log("       guid: %s\n", guid);
            SDL_Log("    VID/PID: 0x%.4x/0x%.4x\n", SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick));
            SDL_JoystickClose(joystick);
        }
    }

#if defined(__ANDROID__) || defined(__IPHONEOS__)
    if (SDL_NumJoysticks() > 0) {
#else
    if (argv[1]) {
#endif
        SDL_bool reportederror = SDL_FALSE;
        SDL_bool keepGoing = SDL_TRUE;
        SDL_Event event;
        int device;
#if defined(__ANDROID__) || defined(__IPHONEOS__)
        device = 0;
#else
        device = atoi(argv[1]);
#endif
        joystick = SDL_JoystickOpen(device);
        if (joystick != NULL) {
            SDL_assert(SDL_JoystickFromInstanceID(SDL_JoystickInstanceID(joystick)) == joystick);
        }

        while ( keepGoing ) {
            if (joystick == NULL) {
                if ( !reportederror ) {
                    SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError());
                    keepGoing = SDL_FALSE;
                    reportederror = SDL_TRUE;
                }
            } else {
                reportederror = SDL_FALSE;
                keepGoing = WatchJoystick(joystick);
                SDL_JoystickClose(joystick);
            }

            joystick = NULL;
            if (keepGoing) {
                SDL_Log("Waiting for attach\n");
            }
            while (keepGoing) {
                SDL_WaitEvent(&event);
                if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
                    || (event.type == SDL_MOUSEBUTTONDOWN)) {
                    keepGoing = SDL_FALSE;
                } else if (event.type == SDL_JOYDEVICEADDED) {
                    device = event.jdevice.which;
                    joystick = SDL_JoystickOpen(device);
                    if (joystick != NULL) {
                        SDL_assert(SDL_JoystickFromInstanceID(SDL_JoystickInstanceID(joystick)) == joystick);
                    }
                    break;
                }
            }
        }
    }
    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);

    return 0;
}

#else

int
main(int argc, char *argv[])
{
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
    exit(1);
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
    SDL_Surface *ecran = NULL, *zozor = NULL;
    SDL_Rect positionZozor;
    SDL_Event event; /* La variable contenant l'événement */
    int continuer = 1; /* Notre booléen pour la boucle */

    SDL_Init(SDL_INIT_VIDEO);

    SDL_WM_SetCaption("Gestion des événements en SDL", NULL);

    ecran = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE);
    zozor = SDL_LoadBMP("zozor.bmp");
    SDL_SetColorKey(zozor, SDL_SRCCOLORKEY, SDL_MapRGB(zozor->format, 0, 0, 255));

    /* On centre Zozor à l'écran */
    positionZozor.x = ecran->w / 2 - zozor->w / 2;
    positionZozor.y = ecran->h / 2 - zozor->h / 2;


    SDL_EnableKeyRepeat(10, 10); // repetition des touche 10ms
    SDL_ShowCursor(SDL_DISABLE); // Masquer curseur de la souris
    SDL_WarpMouse(ecran->w / 2, ecran->h / 2); //place le curseur au centre de l'ecran

    while (continuer) /* TANT QUE la variable ne vaut pas 0 */
    {
        SDL_WaitEvent(&event); /* On attend un événement qu'on récupère dans event */
        switch(event.type) /* On teste le type d'événement */
        {
            case SDL_QUIT: /* Si c'est un événement QUITTER */
                continuer = 0; /* On met le booléen à 0, donc la boucle va s'arrêter */
                break;
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym)
                {
                    case SDLK_ESCAPE: /* Appui sur la touche Echap, on arrête le programme */
                        continuer = 0;
                        break;
                    case SDLK_UP:
                        positionZozor.y--;
                        break;
                    case SDLK_DOWN: // Flèche bas
                        positionZozor.y++;
                        break;
                    case SDLK_RIGHT: // Flèche droite
                        positionZozor.x++;
                        break;
                    case SDLK_LEFT: // Flèche gauche
                        positionZozor.x--;
                        break;
                }
                break;
                case SDL_MOUSEBUTTONUP: /* Clic de la souris */
                    switch(event.button.button)
                    {
                        /* case SDL_BUTTON_LEFT:
                            positionZozor.x = event.button.x;
                            positionZozor.y = event.button.y;
                            break; */
                        case SDL_BUTTON_RIGHT:
                            continuer = 0;
                            break;
                    }
                    break;
                case SDL_MOUSEMOTION:
                    positionZozor.x = event.motion.x;
                    positionZozor.y = event.motion.y;
                    break;
                case SDL_VIDEORESIZE:
                    positionZozor.x = event.resize.w / 2 - zozor->w / 2;
                    positionZozor.y = event.resize.h / 2 - zozor->h / 2;
                    break;
        }
        /* On efface l'écran (ici fond blanc) : */
        SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));

        /* On fait tous les SDL_BlitSurface nécessaires pour coller les surfaces à l'écran */
        SDL_BlitSurface(zozor, NULL, ecran, &positionZozor);

        /* On met à jour l'affichage : */
        SDL_Flip(ecran);
    }

    SDL_FreeSurface(zozor);
    SDL_Quit();

    return EXIT_SUCCESS;
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    char *argv0 = argv[0];
    SDL_Window *window;
    SDL_Renderer *renderer;
    TTF_Font *font;
    SDL_Surface *text;
    Scene scene;
    int ptsize;
    int i, done;
    SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 };
    SDL_Color black = { 0x00, 0x00, 0x00, 0 };
    SDL_Color *forecol;
    SDL_Color *backcol;
    SDL_Event event;
    int rendersolid;
    int renderstyle;
    int outline;
    int hinting;
    int kerning;
    int dump;
    enum {
        RENDER_LATIN1,
        RENDER_UTF8,
        RENDER_UNICODE
    } rendertype;
    char *message, string[128];

    /* Look for special execution mode */
    dump = 0;
    /* Look for special rendering types */
    rendersolid = 0;
    renderstyle = TTF_STYLE_NORMAL;
    rendertype = RENDER_LATIN1;
    outline = 0;
    hinting = TTF_HINTING_NORMAL;
    kerning = 1;
    /* Default is black and white */
    forecol = &black;
    backcol = &white;
    for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) {
        if ( strcmp(argv[i], "-solid") == 0 ) {
            rendersolid = 1;
        } else
        if ( strcmp(argv[i], "-utf8") == 0 ) {
            rendertype = RENDER_UTF8;
        } else
        if ( strcmp(argv[i], "-unicode") == 0 ) {
            rendertype = RENDER_UNICODE;
        } else
        if ( strcmp(argv[i], "-b") == 0 ) {
            renderstyle |= TTF_STYLE_BOLD;
        } else
        if ( strcmp(argv[i], "-i") == 0 ) {
            renderstyle |= TTF_STYLE_ITALIC;
        } else
        if ( strcmp(argv[i], "-u") == 0 ) {
            renderstyle |= TTF_STYLE_UNDERLINE;
        } else
        if ( strcmp(argv[i], "-s") == 0 ) {
            renderstyle |= TTF_STYLE_STRIKETHROUGH;
        } else
        if ( strcmp(argv[i], "-outline") == 0 ) {
            if ( sscanf (argv[++i], "%d", &outline) != 1 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
        } else
        if ( strcmp(argv[i], "-hintlight") == 0 ) {
            hinting = TTF_HINTING_LIGHT;
        } else
        if ( strcmp(argv[i], "-hintmono") == 0 ) {
            hinting = TTF_HINTING_MONO;
        } else
        if ( strcmp(argv[i], "-hintnone") == 0 ) {
            hinting = TTF_HINTING_NONE;
        } else
        if ( strcmp(argv[i], "-nokerning") == 0 ) {
            kerning = 0;
        } else
        if ( strcmp(argv[i], "-dump") == 0 ) {
            dump = 1;
        } else
        if ( strcmp(argv[i], "-fgcol") == 0 ) {
            int r, g, b;
            if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
            forecol->r = (Uint8)r;
            forecol->g = (Uint8)g;
            forecol->b = (Uint8)b;
        } else
        if ( strcmp(argv[i], "-bgcol") == 0 ) {
            int r, g, b;
            if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
            backcol->r = (Uint8)r;
            backcol->g = (Uint8)g;
            backcol->b = (Uint8)b;
        } else {
            fprintf(stderr, Usage, argv0);
            return(1);
        }
    }
    argv += i;
    argc -= i;

    /* Check usage */
    if ( ! argv[0] ) {
        fprintf(stderr, Usage, argv0);
        return(1);
    }

    /* Initialize the TTF library */
    if ( TTF_Init() < 0 ) {
        fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError());
        SDL_Quit();
        return(2);
    }

    /* Open the font file with the requested point size */
    ptsize = 0;
    if ( argc > 1 ) {
        ptsize = atoi(argv[1]);
    }
    if ( ptsize == 0 ) {
        i = 2;
        ptsize = DEFAULT_PTSIZE;
    } else {
        i = 3;
    }
    font = TTF_OpenFont(argv[0], ptsize);
    if ( font == NULL ) {
        fprintf(stderr, "Couldn't load %d pt font from %s: %s\n",
                    ptsize, argv[0], SDL_GetError());
        cleanup(2);
    }
    TTF_SetFontStyle(font, renderstyle);
    TTF_SetFontOutline(font, outline);
    TTF_SetFontKerning(font, kerning);
    TTF_SetFontHinting(font, hinting);

    if( dump ) {
        for( i = 48; i < 123; i++ ) {
            SDL_Surface* glyph = NULL;

            glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol );

            if( glyph ) {
                char outname[64];
                sprintf( outname, "glyph-%d.bmp", i );
                SDL_SaveBMP( glyph, outname );
            }

        }
        cleanup(0);
    }

    /* Create a window */
    if (SDL_CreateWindowAndRenderer(WIDTH, HEIGHT, 0, &window, &renderer) < 0) {
        fprintf(stderr, "SDL_CreateWindowAndRenderer() failed: %s\n", SDL_GetError());
        cleanup(2);
    }

    /* Show which font file we're looking at */
    sprintf(string, "Font file: %s", argv[0]);  /* possible overflow */
    if ( rendersolid ) {
        text = TTF_RenderText_Solid(font, string, *forecol);
    } else {
        text = TTF_RenderText_Shaded(font, string, *forecol, *backcol);
    }
    if ( text != NULL ) {
        scene.captionRect.x = 4;
        scene.captionRect.y = 4;
        scene.captionRect.w = text->w;
        scene.captionRect.h = text->h;
        scene.caption = SDL_CreateTextureFromSurface(renderer, text);
        SDL_FreeSurface(text);
    }

    /* Render and center the message */
    if ( argc > 2 ) {
        message = argv[2];
    } else {
        message = DEFAULT_TEXT;
    }
    switch (rendertype) {
        case RENDER_LATIN1:
        if ( rendersolid ) {
            text = TTF_RenderText_Solid(font,message,*forecol);
        } else {
            text = TTF_RenderText_Shaded(font,message,*forecol,*backcol);
        }
        break;

        case RENDER_UTF8:
        if ( rendersolid ) {
            text = TTF_RenderUTF8_Solid(font,message,*forecol);
        } else {
            text = TTF_RenderUTF8_Shaded(font,message,*forecol,*backcol);
        }
        break;

        case RENDER_UNICODE:
        {
            Uint16 *unicode_text = SDL_iconv_utf8_ucs2(message);
            if ( rendersolid ) {
                text = TTF_RenderUNICODE_Solid(font,
                    unicode_text, *forecol);
            } else {
                text = TTF_RenderUNICODE_Shaded(font,
                    unicode_text, *forecol, *backcol);
            }
            SDL_free(unicode_text);
        }
        break;
        default:
        text = NULL; /* This shouldn't happen */
        break;
    }
    if ( text == NULL ) {
        fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError());
        TTF_CloseFont(font);
        cleanup(2);
    }
    scene.messageRect.x = (WIDTH - text->w)/2;
    scene.messageRect.y = (HEIGHT - text->h)/2;
    scene.messageRect.w = text->w;
    scene.messageRect.h = text->h;
    scene.message = SDL_CreateTextureFromSurface(renderer, text);
    printf("Font is generally %d big, and string is %d big\n",
                        TTF_FontHeight(font), text->h);

    draw_scene(renderer, &scene);

    /* Wait for a keystroke, and blit text on mouse press */
    done = 0;
    while ( ! done ) {
        if ( SDL_WaitEvent(&event) < 0 ) {
            fprintf(stderr, "SDL_PullEvent() error: %s\n",
                                SDL_GetError());
            done = 1;
            continue;
        }
        switch (event.type) {
            case SDL_MOUSEBUTTONDOWN:
                scene.messageRect.x = event.button.x - text->w/2;
                scene.messageRect.y = event.button.y - text->h/2;
                scene.messageRect.w = text->w;
                scene.messageRect.h = text->h;
                draw_scene(renderer, &scene);
                break;

            case SDL_KEYDOWN:
            case SDL_QUIT:
                done = 1;
                break;
            default:
                break;
        }
    }
    SDL_FreeSurface(text);
    TTF_CloseFont(font);
    SDL_DestroyTexture(scene.caption);
    SDL_DestroyTexture(scene.message);
    cleanup(0);

    /* Not reached, but fixes compiler warnings */
    return 0;
}
Ejemplo n.º 8
0
int main(int argc, char *argv[]) {

    SDL_Event event;

    VideoState *is;

    is = av_mallocz(sizeof(VideoState));

    if (argc < 2) {
        fprintf(stderr, "Usage: test <file>\n");
        exit(1);
    }
    // Register all formats and codecs
    av_register_all();

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
        exit(1);
    }

    // Make a screen to put our video
#ifndef __DARWIN__
    screen = SDL_SetVideoMode(640, 480, 0, 0);
#else
        screen = SDL_SetVideoMode(640, 480, 24, 0);
#endif
    if (!screen) {
        fprintf(stderr, "SDL: could not set video mode - exiting\n");
        exit(1);
    }

    av_strlcpy(is->filename, argv[1], 1024);

    is->pictq_mutex = SDL_CreateMutex();
    is->pictq_cond = SDL_CreateCond();

    schedule_refresh(is, 40);

    is->av_sync_type = DEFAULT_AV_SYNC_TYPE;
    is->parse_tid = SDL_CreateThread(decode_thread, is);
    if (!is->parse_tid) {
        av_free(is);
        return -1;
    }
    for (; ;) {

        SDL_WaitEvent(&event);
        switch (event.type) {
            case FF_QUIT_EVENT:
            case SDL_QUIT:
                is->quit = 1;
                /*
                 * If the video has finished playing, then both the picture and
                 * audio queues are waiting for more data.  Make them stop
                 * waiting and terminate normally.
                 */
                SDL_CondSignal(is->audioq.cond);
                SDL_CondSignal(is->videoq.cond);
                SDL_Quit();
                exit(0);
                break;
            case FF_ALLOC_EVENT:
                alloc_picture(event.user.data1);
                break;
            case FF_REFRESH_EVENT:
                video_refresh_timer(event.user.data1);
                break;
            default:
                break;
        }
    }
    return 0;

}
Ejemplo n.º 9
0
Archivo: main.c Proyecto: MarcelHB/c37
int main(int argc, char *argv[]){
	Spawn *player;
	InterfaceData idata = {0, NULL, -1, NULL, 1};
	SDL_Event event;
	int num_tiles = OUTPUT_IN_GLYPHS_X * OUTPUT_IN_GLYPHS_Y, i;
	
	/*SDL anmachen*/
    if(SDL_Init(SDL_INIT_VIDEO))
        return EXIT_FAILURE;
    SDL_EnableKeyRepeat(200, 50);
    
    /*Karte laden*/
    if(argc==2)
        map=load_map(argv[1]);
    else{
        fprintf(stderr,"Kartennamen angeben\n");
        return EXIT_FAILURE;
    }
    if(map == NULL) {
        fprintf(stderr,"Fehler beim Laden der Karte\n");
        return EXIT_FAILURE;
    }
    
    player = get_player_spawn(map);
    if(player==NULL){
        fprintf(stderr, "Kein Spieler auf der Karte\n");
        return EXIT_FAILURE;
    }
    
    /*Map zeichnen*/
    
    /* Ausgabepuffer initialisieren */
    buf = (BufferTile*)ex_malloc(sizeof(BufferTile) * num_tiles);
    for(i = 0; i < num_tiles; ++i) {
        BufferTile bt = {' ', 0x00000000};
        buf[i] = bt;
    }
    
    output_init(OUTPUT_IN_GLYPHS_X, OUTPUT_IN_GLYPHS_Y, map->name);
    
    explore_area(player, map);
    create_output_buffer(map, buf, num_tiles);
    get_interface_data(map, &idata);
    output_draw(buf, num_tiles, &idata);
    
    /*Eingabeloop*/
    int quit=0;
    KeyAction current_action = INVALID;
    while(SDL_WaitEvent(&event)){
        if(event.type == SDL_KEYDOWN) {
            current_action = get_action(event.key.keysym.sym);
            /*bei Escape beenden*/
            if(event.key.keysym.sym == SDLK_ESCAPE){
                quit=1;
                break;
            }
            if(current_action != INVALID) {
                process_event(current_action, map);
            }
            create_output_buffer(map, buf, num_tiles);
            get_interface_data(map, &idata);
            output_draw(buf, num_tiles, &idata);
        } else if(event.type == SDL_QUIT) {
            quit=1;
            break;
        }
        SDL_Delay(1);
        /*Affe tot => Klappe zu*/
        if(player->hp<=0){
            game_over(0);
            break;
        }
        /* Ende erreicht */
        if(map->finished) {
            game_over(1);
            break;
        }
    }
    if(!quit){
        while(SDL_WaitEvent(&event)){
            /*bei Escape beenden*/
            if(event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {
                break;
            }
            SDL_Delay(1);
        }
    }
    free(buf);
    flush_map(map);
    free(idata.message); free(idata.item_name);
    
    output_close();
    SDL_Quit();
    return EXIT_SUCCESS;
}
Ejemplo n.º 10
0
/* Procedure de gestion des evenements du menu
 * @param SDL_Event* event
 *     Evenements de la fenetre
 * @param S_GameConfig gameConfig
 *     Structure de configuration du jeu
 * @param E_MenuSelected selected
 *     Selection du menu
 * @return E_MenuSelected
 *     Eventuel bouton clique
 */
E_MenuSelected EventsMenu(SDL_Event* event, S_GameConfig* gameConfig, E_MenuSelected* selected)
{
    E_MenuSelected clicked = NONE;

    SDL_WaitEvent(event);
    switch(event->type)
    {
        case SDL_QUIT:
            clicked = QUIT;
            break;
        case SDL_MOUSEBUTTONDOWN:
            if (ClickRect(event, 450, 446, 150, 45))
                    *selected = QUIT;

            if (ClickRect(event, 158, 446, 150, 45))
                    *selected = START;

            break;
        case SDL_MOUSEBUTTONUP:
            if (event->button.button == SDL_BUTTON_LEFT)
            {
                // Boutons
                if (ClickRect(event, 450, 446, 150, 45))
                    clicked = QUIT;

                if (ClickRect(event, 158, 446, 150, 45))
                {
                    if (strlen(gameConfig->namePlayer1) > 0 && strlen(gameConfig->namePlayer2) > 0)
                        clicked = START;
                }

                // Selection des zones de texte
                if (ClickRect(event, 379, 126, 300, 40))
                    *selected = PLAYER1;
                else if (ClickRect(event, 379, 186, 300, 40))
                    *selected = PLAYER2;
                else
                    *selected = NONE;

                // Clic sur les boutons
                if (ClickRect(event, 379, 246, 40, 40))
                    gameConfig->player1Color = BLACK;

                if (ClickRect(event, 568, 246, 40, 40))
                    gameConfig->player1Color = WHITE;

                if (ClickRect(event, 41, 306, 40, 40))
                    gameConfig->option = 1;

                if (ClickRect(event, 420, 306, 40, 40))
                    gameConfig->option = 0;

                // Clic sur les fleches
                if (ClickRect(event, 444, 366, 30, 40))
                {
                    if (gameConfig->points > MIN_POINTS)
                        gameConfig->points -= 2;
                }

                if (ClickRect(event, 584, 366, 30, 40))
                {
                    if (gameConfig->points < MAX_POINTS)
                        gameConfig->points += 2;
                }
            }
            break;
        case SDL_KEYUP:
            if (*selected == PLAYER1)
                TextInput(gameConfig->namePlayer1, event->key.keysym);
            else if (*selected == PLAYER2)
                TextInput(gameConfig->namePlayer2, event->key.keysym);

            break;
    }

    return clicked;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[]) {

	SDL_Event event;
	VideoState *is;
	int i;
	puts("start");
	global_mutex_lock = SDL_CreateMutex();

	is = av_mallocz(sizeof(VideoState));
	if (argc < 2){
		fprintf(stderr, "Usage: test <file>\n");
		exit(1);
	}
		
	av_register_all();		// Register all formats and codecs
	puts("avregister");
	//if (av_register_protocol(&e2URLProtocol) < 0){
	//	printf("Error - URL protocol \n");
	//	exit(-1)
	//}
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)){
		fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
		exit(1);
	}
	for(i=0; i<MAX_CHANNELS;i++){
		// Make a screen to put our video
		#ifndef __DARWIN__
		screen[i] = SDL_SetVideoMode(640, 480, 0, 0);
		#else
		screen[i] = SDL_SetVideoMode(640, 480, 24, 0);
		#endif
		if (!screen[i]){
			fprintf(stderr, "SDL: could not set video mode - exiting\n");
			exit(1);
		}
	}
	for(i=0; i<MAX_CHANNELS;i++){
		global_video_state[i] = av_mallocz(sizeof(VideoState));
		global_video_state[i]->videoIndex = i;
		puts("screen created");
		printf("i is: %d\n",i);
		av_strlcpy(global_video_state[i]->filename, argv[i+1], sizeof(global_video_state[i]->filename));
		puts("avstrlcpy");	
		global_video_state[i]->pictq_mutex = SDL_CreateMutex();
		global_video_state[i]->pictq_cond = SDL_CreateCond();
		schedule_refresh(global_video_state[i], 40);
		global_video_state[i]->av_sync_type = DEFAULT_AV_SYNC_TYPE;
		global_video_state[i]->parse_tid = SDL_CreateThread(decode_thread, global_video_state[i]);
		puts("main var created");
		if (!global_video_state[i]->parse_tid) {
			av_free(global_video_state[i]);
			return -1;
		}
	}
	av_init_packet(&f_pkt);
	puts("av_init_packet");
	f_pkt.data = (unsigned char*)"FLUSH";

	for (;;) {
		double inc , pos;
		SDL_WaitEvent(&event);
		switch (event.type) {
			case SDL_KEYDOWN:
				switch (event.key.keysym.sym) {
					case SDLK_LEFT:
						inc = -10.0;
						goto do_seek;
					case SDLK_RIGHT:
						inc = 10.0;
						goto do_seek;
					case SDLK_UP:
						inc = 60.0;
						goto do_seek;
					case SDLK_DOWN:
						inc = -60.0;
						goto do_seek;
					do_seek:
						SDL_LockMutex(global_mutex_lock);
						if (global_video_state[global_videoIndex]){
							pos = get_master_clock(global_video_state[global_videoIndex]);
							pos += inc;
							stream_seek(global_video_state[global_videoIndex],(int64_t)(pos *AV_TIME_BASE),inc);
						}
						SDL_UnlockMutex(global_mutex_lock);
						break;
					case SDLK_b:
						global_video_state[global_videoIndex]->color_req = 'b';
						break;
					case SDLK_r:
						global_video_state[global_videoIndex]->color_req = 'r';
						break;
					case SDLK_g:
						global_video_state[global_videoIndex]->color_req = 'g';
						break;
					case SDLK_w:
						global_video_state[global_videoIndex]->color_req = 'w';
						break;
					case SDLK_n:
						global_video_state[global_videoIndex]->color_req = 'n';
						break;
					case SDLK_1:
						change_channel(1);
						break;
					case SDLK_2:
						change_channel(2);
						break;
					case SDLK_3:
						change_channel(3);
						break;
					case SDLK_4:
						change_vidchannel(1);
						break;
					case SDLK_5:
						change_vidchannel(2);
						break;
					case SDLK_6:
						change_vidchannel(3);
						break;
					case SDLK_7:
						change_audchannel(1);
						break;
					case SDLK_8:
						change_audchannel(2);
						break;
					case SDLK_9:
						change_audchannel(3);
						break;
				default:
					break;
				}
				break;
			case FF_QUIT_EVENT:
				case SDL_QUIT:
					for(i=0; i<MAX_CHANNELS; i++){
						global_video_state[i]->quit = 1;
						SDL_CondSignal(global_video_state[i]->audioq.cond);
						SDL_CondSignal(global_video_state[i]->videoq.cond);
					}
					SDL_Quit();
					exit(0);
					break;
				case FF_ALLOC_EVENT:
					alloc_picture(event.user.data1);
					break;
				case FF_REFRESH_EVENT:
					video_refresh_timer(event.user.data1);
					break;
			default:
				break;
		}
	}
	return 0;

}
Ejemplo n.º 12
0
/* Fonction de gestion des evenements du plateau
 * @param SDL_Event* event
 *     Evenements de la fenetre
 * @param S_GameState* gameState
 *     Etat du jeu
 * @return E_BoardSelected
 *     Eventuel bouton clique
 */
E_BoardSelected EventsBoard(SDL_Event* event, S_GameState* gameState)
{
    E_BoardSelected clicked = NONE_BOARD;

    if (gameState->gameConfig.mode == HUMAN_HUMAN)
        SDL_WaitEvent(event); // On attend l'evenement
    else
        SDL_PollEvent(event); // Defilement automatique

    int zone = -1;
    int bx;

    if (event->type == SDL_QUIT)
        clicked = QUIT_BOARD;

    switch (gameState->currentStage)
    {
        case WAITING_FIRST_ROLL:
            switch(event->type)
            {
                case SDL_MOUSEBUTTONDOWN:
                    // Bouton "Lancer"
                    if (ClickRect(event, 293, 230, 100, 30))
                        gameState->selected = BUTTON1;
                    break;
                case SDL_MOUSEBUTTONUP:
                    gameState->selected = NONE_BOARD;

                    // Bouton "Lancer"
                    if (ClickRect(event, 293, 230, 100, 30))
                        RollDice(gameState);
                    break;
            }
            break;
        case WAITING_ROLL_DBL:
            // On gere les boutons que si le joueur est humain
            if (IsHuman(gameState, 1))
            {
                bx = (gameState->currentPlayer == EPlayer1) ? 122 : 464;

                switch(event->type)
                {
                    case SDL_MOUSEBUTTONDOWN:
                        // Bouton "Doubler"
                        if (ClickRect(event, bx, 210, 100, 30))
                            gameState->selected = BUTTON1;

                        // Bouton "Lancer"
                        if (ClickRect(event, bx, 250, 100, 30))
                            gameState->selected = BUTTON2;
                        break;
                    case SDL_MOUSEBUTTONUP:
                        gameState->selected = NONE_BOARD;

                        // Bouton "Doubler"
                        if (ClickRect(event, bx, 210, 100, 30))
                            gameState->currentStage = DOUBLE_POPUP;

                        // Bouton "Lancer"
                        if (ClickRect(event, bx, 250, 100, 30))
                        {
                            RollDice(gameState);

                            if (IsPossibleMove(gameState))
                                gameState->currentStage = SELECT_ZONE_SRC;
                            else
                                gameState->currentStage = PASS_POPUP;
                        }
                        break;
                }
            }
            break;
        case WAITING_ROLL:
            // On gere le bouton que si le joueur est humain
            if (IsHuman(gameState, 1))
            {
                bx = (gameState->currentPlayer == EPlayer1) ? 122 : 464;

                switch(event->type)
                {
                    case SDL_MOUSEBUTTONDOWN:
                        // Bouton "Lancer"
                        if (ClickRect(event, bx, 230, 100, 30))
                            gameState->selected = BUTTON1;
                        break;
                    case SDL_MOUSEBUTTONUP:
                        gameState->selected = NONE_BOARD;

                        // Bouton "Lancer"
                        if (ClickRect(event, bx, 230, 100, 30))
                        {
                            RollDice(gameState);

                            if (IsPossibleMove(gameState))
                                gameState->currentStage = SELECT_ZONE_SRC;
                            else
                                gameState->currentStage = PASS_POPUP;
                        }
                        break;
                }
            }
            break;
        case DOUBLE_POPUP:
            // On gere la popup que si l'adversaire est humain
            if (IsHuman(gameState, 0))
            {
                switch(event->type)
                {
                    case SDL_MOUSEBUTTONDOWN:
                        // Bouton "Accepter"
                        if (ClickRect(event, 234, 305, 100, 30))
                            gameState->selected = BUTTON1;

                        // Bouton "Refuser"
                        if (ClickRect(event, 354, 305, 100, 30))
                            gameState->selected = BUTTON2;
                        break;

                    case SDL_MOUSEBUTTONUP:
                        gameState->selected = NONE_BOARD;

                        // Bouton "Accepter"
                        if (ClickRect(event, 234, 305, 100, 30))
                        {
                            gameState->stake *= 2;

                            if (gameState->currentPlayer == EPlayer1)
                                gameState->cubeOwner = EPlayer2;
                            else
                                gameState->cubeOwner = EPlayer1;

                            gameState->currentStage = WAITING_ROLL;
                        }

                        // Bouton "Refuser"
                        if (ClickRect(event, 354, 305, 100, 30))
                        {
                            // Le joueur courant gagne la partie
                            if (gameState->currentPlayer == EPlayer1)
                                gameState->scoreP1 += gameState->stake;
                            else
                                gameState->scoreP2 += gameState->stake;

                            gameState->currentStage = FINISH_GAME_POPUP;
                        }
                        break;
                }
            }
            break;
        case FIRST_ROLL_POPUP:
            // On gere la popup que si un humain joue
            if (gameState->gameConfig.mode != AI_AI)
            {
                switch(event->type)
                {
                    case SDL_MOUSEBUTTONDOWN:
                        // Bouton "OK"
                        if (ClickRect(event, 293, 305, 100, 30))
                            gameState->selected = BUTTON1;
                        break;
                    case SDL_MOUSEBUTTONUP:
                        gameState->selected = NONE_BOARD;

                        // Bouton "OK"
                        if (ClickRect(event, 293, 305, 100, 30))
                        {
                            if (IsPossibleMove(gameState))
                                gameState->currentStage = SELECT_ZONE_SRC;
                            else
                                gameState->currentStage = PASS_POPUP;
                        }
                        break;
                }
            }
            break;
        case PASS_POPUP:
            // On gere la popup que si le joueur courant est humain
            if (IsHuman(gameState, 1))
            {
                switch(event->type)
                {
                    case SDL_MOUSEBUTTONDOWN:
                        // Bouton "OK"
                        if (ClickRect(event, 293, 305, 100, 30))
                            gameState->selected = BUTTON1;
                        break;
                    case SDL_MOUSEBUTTONUP:
                        gameState->selected = NONE_BOARD;

                        // Bouton "OK"
                        if (ClickRect(event, 293, 305, 100, 30))
                        {
                            if (gameState->currentPlayer == EPlayer1)
                                gameState->currentPlayer = EPlayer2;
                            else
                                gameState->currentPlayer = EPlayer1;

                            if (gameState->cubeOwner == gameState->currentPlayer || gameState->stake == 1)
                                gameState->currentStage = WAITING_ROLL_DBL;
                            else
                                gameState->currentStage = WAITING_ROLL;
                        }
                        break;
                }
            }
            break;
        case FINISH_GAME_POPUP:
            // On gere la popup que si un joueur est humain
            if (gameState->gameConfig.mode != AI_AI)
            {
                switch(event->type)
                {
                    case SDL_MOUSEBUTTONDOWN:
                        // Bouton "OK"
                        if (ClickRect(event, 293, 305, 100, 30))
                            gameState->selected = BUTTON1;
                        break;
                    case SDL_MOUSEBUTTONUP:
                        gameState->selected = NONE_BOARD;

                        // Bouton "OK"
                        if (ClickRect(event, 293, 305, 100, 30))
                        {
                            // On desalloue les IA
                            if (gameState->gameConfig.mode == HUMAN_AI)
                                gameState->gameConfig.aiFunctions[1].AI_EndGame();

                            // Fin du match
                            if ((gameState->currentPlayer == EPlayer1 && gameState->scoreP1 >= gameState->gameConfig.points) ||
                                (gameState->currentPlayer == EPlayer2 && gameState->scoreP2 >= gameState->gameConfig.points))
                                gameState->currentStage = FINISH_MATCH_POPUP;
                            else
                            {
                                // On reinitialise les IA pour une nouvelle manche
                                if (gameState->gameConfig.mode == HUMAN_AI)
                                    gameState->gameConfig.aiFunctions[1].AI_StartGame();

                                // Remise a zero du plateau
                                InitGameState(gameState, gameState->gameConfig);
                            }
                        }
                        break;
                }
            }
            break;
        case FINISH_MATCH_POPUP:
            switch(event->type)
            {
                case SDL_MOUSEBUTTONDOWN:
                    // Bouton "OK"
                    if (ClickRect(event, 293, 305, 100, 30))
                        gameState->selected = BUTTON1;
                    break;
                case SDL_MOUSEBUTTONUP:
                    gameState->selected = NONE_BOARD;

                    // Bouton "OK"
                    if (ClickRect(event, 293, 305, 100, 30))
                    {
                        // On ecrit dans le fichier des scores
                        FILE* file = fopen("score.txt", "a");

                        fprintf(file, "%s : %d\n", gameState->gameConfig.namePlayer1, gameState->scoreP1);
                        fprintf(file, "%s : %d\n", gameState->gameConfig.namePlayer2, gameState->scoreP2);
                        fprintf(file, "--------------------\n");

                        fclose(file);

                        // On revient au menu
                        clicked = MENU_BOARD;
                    }
                    break;
            }
            break;

        case SELECT_ZONE_SRC:
            // On gere le deplacement que si le joueur courant est humain
            if (IsHuman(gameState, 1))
            {
                switch(event->type)
                {
                    case SDL_MOUSEBUTTONUP:
                        // Selection d'une zone source
                        zone = ClickZone(event);
                        if (IsValidSrc(zone, gameState))
                        {
                            gameState->currentZone = zone;
                            gameState->currentStage = SELECT_ZONE_DST;
                        }
                        break;
                }
            }
            break;
        case SELECT_ZONE_DST:
            // On gere le deplacement que si le joueur courant est humain
            if (IsHuman(gameState, 1))
            {
                switch(event->type)
                {
                    case SDL_MOUSEBUTTONUP:
                        // Selection d'une zone source
                        zone = ClickZone(event);

                        if (IsValidDst(zone, gameState))
                            DoMove(zone, gameState);
                        else if (IsValidSrc(zone, gameState))
                            gameState->currentZone = zone;
                        else
                        {
                            gameState->currentZone = -1;
                            gameState->currentStage = SELECT_ZONE_SRC;
                        }
                        break;
                }
            }
            break;
        default:
            break;
    }

    return clicked;
}
Ejemplo n.º 13
0
void ONScripter::runEventLoop()
{
    SDL_Event event, tmp_event;

    while ( SDL_WaitEvent(&event) ) {
        bool ret = false;
        // ignore continous SDL_MOUSEMOTION
        while (event.type == SDL_MOUSEMOTION){
#if SDL_VERSION_ATLEAST(1, 3, 0)
            if ( SDL_PeepEvents( &tmp_event, 1, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT ) == 0 ) break;
            if (tmp_event.type != SDL_MOUSEMOTION) break;
            SDL_PeepEvents( &tmp_event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT );
#else
            if ( SDL_PeepEvents( &tmp_event, 1, SDL_PEEKEVENT, SDL_ALLEVENTS ) == 0 ) break;
            if (tmp_event.type != SDL_MOUSEMOTION) break;
            SDL_PeepEvents( &tmp_event, 1, SDL_GETEVENT, SDL_ALLEVENTS );
#endif
            event = tmp_event;
        }

        switch (event.type) {
#if defined(IOS) // || defined(ANDROID)
          case SDL_FINGERMOTION:
            {
                SDL_Touch *touch = SDL_GetTouch(event.tfinger.touchId);
                tmp_event.motion.x = device_width *event.tfinger.x/touch->xres - (device_width -screen_device_width)/2;
                tmp_event.motion.y = device_height*event.tfinger.y/touch->yres - (device_height-screen_device_height)/2;
                if (mouseMoveEvent( &tmp_event.motion )) return;
                if (btndown_flag){
                    event.button.type = SDL_MOUSEBUTTONDOWN;
                    event.button.button = SDL_BUTTON_LEFT;
                    if (touch->num_fingers >= 2)
                        event.button.button = SDL_BUTTON_RIGHT;
                    event.button.x = tmp_event.motion.x;
                    event.button.y = tmp_event.motion.y;
                    ret = mousePressEvent( &event.button );
                    if (ret) return;
                }
            }
            break;
          case SDL_FINGERDOWN:
          {
                SDL_Touch *touch = SDL_GetTouch(event.tfinger.touchId);
                tmp_event.motion.x = device_width *event.tfinger.x/touch->xres - (device_width -screen_device_width)/2;
                tmp_event.motion.y = device_height*event.tfinger.y/touch->yres - (device_height-screen_device_height)/2;
                if (mouseMoveEvent( &tmp_event.motion )) return;
          }
            if ( btndown_flag ){
                SDL_Touch *touch = SDL_GetTouch(event.tfinger.touchId);
                tmp_event.button.type = SDL_MOUSEBUTTONDOWN;
                tmp_event.button.button = SDL_BUTTON_LEFT;
                if (touch->num_fingers >= 2)
                    tmp_event.button.button = SDL_BUTTON_RIGHT;
                tmp_event.button.x = device_width *event.tfinger.x/touch->xres - (device_width -screen_device_width)/2;
                tmp_event.button.y = device_height*event.tfinger.y/touch->yres - (device_height-screen_device_height)/2;
                ret = mousePressEvent( &tmp_event.button );
            }
            {
                SDL_Touch *touch = SDL_GetTouch(event.tfinger.touchId);
                num_fingers = touch->num_fingers;
                if (num_fingers >= 3){
                    tmp_event.key.keysym.sym = SDLK_LCTRL;
                    ret |= keyDownEvent( &tmp_event.key );
                }
            }
            if (ret) return;
            break;
          case SDL_FINGERUP:
            if (num_fingers == 0) break;
            {
                SDL_Touch *touch = SDL_GetTouch(event.tfinger.touchId);
                tmp_event.button.type = SDL_MOUSEBUTTONUP;
                tmp_event.button.button = SDL_BUTTON_LEFT;
                if (touch->num_fingers >= 1)
                    tmp_event.button.button = SDL_BUTTON_RIGHT;
                tmp_event.button.x = device_width *event.tfinger.x/touch->xres - (device_width -screen_device_width)/2;
                tmp_event.button.y = device_height*event.tfinger.y/touch->yres - (device_height-screen_device_height)/2;
                ret = mousePressEvent( &tmp_event.button );
            }
            tmp_event.key.keysym.sym = SDLK_LCTRL;
            keyUpEvent( &tmp_event.key );
            num_fingers = 0;
            if (ret) return;
            break;
#else
          case SDL_MOUSEMOTION:
            if (mouseMoveEvent( &event.motion )) return;
            if (btndown_flag){
                if (event.motion.state & SDL_BUTTON(SDL_BUTTON_LEFT))
                    tmp_event.button.button = SDL_BUTTON_LEFT;
                else if (event.motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT))
                    tmp_event.button.button = SDL_BUTTON_RIGHT;
                else
                    break;

                tmp_event.button.type = SDL_MOUSEBUTTONDOWN;
                tmp_event.button.x = event.motion.x;
                tmp_event.button.y = event.motion.y;
                ret = mousePressEvent( &tmp_event.button );
                if (ret) return;
            }
            break;
            
          case SDL_MOUSEBUTTONDOWN:
            current_button_state.event_type = event.type;
            current_button_state.event_button = event.button.button;
            if ( !btndown_flag ) break;
          case SDL_MOUSEBUTTONUP:
            current_button_state.event_type = event.type;
            current_button_state.event_button = event.button.button;
            ret = mousePressEvent( &event.button );
            if (ret) return;
            break;
#endif
          case SDL_JOYBUTTONDOWN:
            event.key.type = SDL_KEYDOWN;
            event.key.keysym.sym = transJoystickButton(event.jbutton.button);
            if(event.key.keysym.sym == SDLK_UNKNOWN)
                break;
            
          case SDL_KEYDOWN:
            event.key.keysym.sym = transKey(event.key.keysym.sym);
            ret = keyDownEvent( &event.key );
            if ( btndown_flag )
                ret |= keyPressEvent( &event.key );
            if (ret) return;
            break;

          case SDL_JOYBUTTONUP:
            event.key.type = SDL_KEYUP;
            event.key.keysym.sym = transJoystickButton(event.jbutton.button);
            if(event.key.keysym.sym == SDLK_UNKNOWN)
                break;
            
          case SDL_KEYUP:
            event.key.keysym.sym = transKey(event.key.keysym.sym);
            keyUpEvent( &event.key );
            ret = keyPressEvent( &event.key );
            if (ret) return;
            break;

          case SDL_JOYAXISMOTION:
          {
              SDL_KeyboardEvent ke = transJoystickAxis(event.jaxis);
              if (ke.keysym.sym != SDLK_UNKNOWN){
                  if (ke.type == SDL_KEYDOWN){
                      keyDownEvent( &ke );
                      if (btndown_flag)
                          keyPressEvent( &ke );
                  }
                  else if (ke.type == SDL_KEYUP){
                      keyUpEvent( &ke );
                      keyPressEvent( &ke );
                  }
              }
              break;
          }

          case ONS_TIMER_EVENT:
            timerEvent();
            break;

          case ONS_MUSIC_EVENT:
          case ONS_BGMFADE_EVENT:
          case ONS_CDAUDIO_EVENT:
          case ONS_MIDI_EVENT:
            flushEventSub( event );
            break;

          case ONS_CHUNK_EVENT:
            flushEventSub( event );
            //printf("ONS_CHUNK_EVENT %d: %x %d %x\n", event.user.code, wave_sample[0], automode_flag, event_mode);
            if ( event.user.code != 0 ||
                 !(event_mode & WAIT_VOICE_MODE) ) break;

            event_mode &= ~WAIT_VOICE_MODE;

          case ONS_BREAK_EVENT:
            if (event_mode & WAIT_VOICE_MODE && wave_sample[0]){
                remaining_time = -1;
                timerEvent();
                break;
            }

            if (automode_flag || autoclick_time > 0)
                current_button_state.button = 0;
            else if ( usewheel_flag ){
                current_button_state.button = -5;
                sprintf(current_button_state.str, "TIMEOUT");
            }
            else{
                current_button_state.button = -2;
                sprintf(current_button_state.str, "TIMEOUT");
            }

            if (event_mode & (WAIT_INPUT_MODE | WAIT_BUTTON_MODE) && 
                ( clickstr_state == CLICK_WAIT || 
                  clickstr_state == CLICK_NEWPAGE ) ){
                playClickVoice(); 
                stopAnimation( clickstr_state ); 
            }

            return;
            
          case SDL_ACTIVEEVENT:
            if ( !event.active.gain ){
                // the mouse cursor leaves the window
                SDL_MouseMotionEvent mevent;
                mevent.x = screen_device_width;
                mevent.y = screen_device_height;
                mouseMoveEvent( &mevent );
                break;
            }
#ifdef ANDROID
            if (event.active.state == SDL_APPACTIVE){
                screen_surface = SDL_SetVideoMode( screen_width, screen_height, screen_bpp, DEFAULT_VIDEO_SURFACE_FLAG );
                repaintCommand();
                break;
            }
#endif
          case SDL_VIDEOEXPOSE:
#ifdef USE_SDL_RENDERER
            SDL_RenderPresent(renderer);
#else
            SDL_UpdateRect( screen_surface, 0, 0, screen_width, screen_height );
#endif
            break;

          case SDL_QUIT:
            endCommand();
            break;
            
          default:
            break;
        }
    }
}
Ejemplo n.º 14
0
	bool SDLApplication::Update () {
		
		SDL_Event event;
		event.type = -1;
		
		#if (!defined (IPHONE) && !defined (EMSCRIPTEN))
		
		if (active && (firstTime || SDL_WaitEvent (&event))) {
			
			firstTime = false;
			
			HandleEvent (&event);
			event.type = -1;
			if (!active)
				return active;
			
		#endif
			
			while (SDL_PollEvent (&event)) {
				
				HandleEvent (&event);
				event.type = -1;
				if (!active)
					return active;
				
			}
			
			currentUpdate = SDL_GetTicks ();
			
		#if defined (IPHONE)
			
			if (currentUpdate >= nextUpdate) {
				
				event.type = SDL_USEREVENT;
				HandleEvent (&event);
				event.type = -1;
				
			}
		
		#elif defined (EMSCRIPTEN)
			
			event.type = SDL_USEREVENT;
			HandleEvent (&event);
			event.type = -1;
		
		#else
			
			if (currentUpdate >= nextUpdate) {
				
				SDL_RemoveTimer (timerID);
				OnTimer (0, 0);
				
			} else if (!timerActive) {
				
				timerActive = true;
				timerID = SDL_AddTimer (nextUpdate - currentUpdate, OnTimer, 0);
				
			}
			
		}
		
		#endif
		
		return active;
		
	}
Ejemplo n.º 15
0
Archivo: io.c Proyecto: taiyu-len/chip8
int io_input (
    struct chip8 *chip8
) {
    SDL_Event event;

//GET INPUT
retry_input:
    if(chip8->waiting)
        SDL_WaitEvent(&event);
    else if(!SDL_PollEvent(&event))
        goto done_input;
    //Complete all input
    do
    {
        //123C
        //456D
        //789E
        //A0BF
        if (event.type == SDL_KEYDOWN)
            switch(event.key.keysym.sym)
            {
            case SDLK_COMMA    :
                chip8->key |= 1 << 0;
                break;
            case SDLK_7        :
                chip8->key |= 1 << 1;
                break;
            case SDLK_8        :
                chip8->key |= 1 << 2;
                break;
            case SDLK_9        :
                chip8->key |= 1 << 3;
                break;
            case SDLK_u        :
                chip8->key |= 1 << 4;
                break;
            case SDLK_i        :
                chip8->key |= 1 << 5;
                break;
            case SDLK_o        :
                chip8->key |= 1 << 6;
                break;
            case SDLK_j        :
                chip8->key |= 1 << 7;
                break;
            case SDLK_k        :
                chip8->key |= 1 << 8;
                break;
            case SDLK_l        :
                chip8->key |= 1 << 9;
                break;
            case SDLK_m        :
                chip8->key |= 1 << 10;
                break;
            case SDLK_PERIOD   :
                chip8->key |= 1 << 11;
                break;
            case SDLK_0        :
                chip8->key |= 1 << 12;
                break;
            case SDLK_p        :
                chip8->key |= 1 << 13;
                break;
            case SDLK_SEMICOLON:
                chip8->key |= 1 << 14;
                break;
            case SDLK_SLASH    :
                chip8->key |= 1 << 15;
                break;
            case SDLK_q:
                exit(0);
            case SDLK_w:
                chip8->waiting = 1;
                goto done_input;
            }
        else if (event.type == SDL_KEYUP)
            switch(event.key.keysym.sym)
            {
            case SDLK_COMMA    :
                chip8->key &= ~(1 << 0);
                break;
            case SDLK_7        :
                chip8->key &= ~(1 << 1);
                break;
            case SDLK_8        :
                chip8->key &= ~(1 << 2);
                break;
            case SDLK_9        :
                chip8->key &= ~(1 << 3);
                break;
            case SDLK_u        :
                chip8->key &= ~(1 << 4);
                break;
            case SDLK_i        :
                chip8->key &= ~(1 << 5);
                break;
            case SDLK_o        :
                chip8->key &= ~(1 << 6);
                break;
            case SDLK_j        :
                chip8->key &= ~(1 << 7);
                break;
            case SDLK_k        :
                chip8->key &= ~(1 << 8);
                break;
            case SDLK_l        :
                chip8->key &= ~(1 << 9);
                break;
            case SDLK_m        :
                chip8->key &= ~(1 << 10);
                break;
            case SDLK_PERIOD   :
                chip8->key &= ~(1 << 11);
                break;
            case SDLK_0        :
                chip8->key &= ~(1 << 12);
                break;
            case SDLK_p        :
                chip8->key &= ~(1 << 13);
                break;
            case SDLK_SEMICOLON:
                chip8->key &= ~(1 << 14);
                break;
            case SDLK_SLASH    :
                chip8->key &= ~(1 << 15);
                break;
            case SDLK_q:
                exit(0);
            default:
                goto retry_input;
            }
        else if (event.type == SDL_QUIT)
        {
            exit(0);
        }
    } while(SDL_PollEvent(&event));
    chip8->waiting = 0;
done_input:
    return 0;
}
Ejemplo n.º 16
0
int CApplication::Run()
{
    m_active = true;

    GetSystemUtils()->GetCurrentTimeStamp(m_baseTimeStamp);
    GetSystemUtils()->GetCurrentTimeStamp(m_lastTimeStamp);
    GetSystemUtils()->GetCurrentTimeStamp(m_curTimeStamp);

    MoveMouse(Math::Point(0.5f, 0.5f)); // center mouse on start

    while (true)
    {
        ResetPerformanceCounters();

        if (m_active)
        {
            StartPerformanceCounter(PCNT_ALL);
            StartPerformanceCounter(PCNT_EVENT_PROCESSING);
        }

        // To be sure no old event remains
        m_private->currentEvent.type = SDL_NOEVENT;

        // Call SDL_PumpEvents() only once here
        // (SDL_PeepEvents() doesn't call it)
        if (m_active)
            SDL_PumpEvents();

        m_private->lastMouseMotionEvent.type = SDL_NOEVENT;

        bool haveEvent = true;
        while (haveEvent)
        {
            haveEvent = false;

            int count = 0;
            // Use SDL_PeepEvents() if the app is active, so we can use idle time to
            // render the scene. Else, use SDL_WaitEvent() to avoid eating CPU time.
            if (m_active)
                count = SDL_PeepEvents(&m_private->currentEvent, 1, SDL_GETEVENT, SDL_ALLEVENTS);
            else
                count = SDL_WaitEvent(&m_private->currentEvent);

            // If received an event
            if (count > 0)
            {
                haveEvent = true;

                // Skip mouse motion events, for now
                if (m_private->currentEvent.type == SDL_MOUSEMOTION)
                {
                    m_private->lastMouseMotionEvent = m_private->currentEvent;
                    continue;
                }

                Event event = ProcessSystemEvent();

                if (event.type == EVENT_QUIT)
                    goto end; // exit the loop

                if (event.type != EVENT_NULL)
                {
                    bool passOn = ProcessEvent(event);

                    if (m_engine != nullptr && passOn)
                        passOn = m_engine->ProcessEvent(event);

                    if (passOn)
                        m_eventQueue->AddEvent(event);
                }

                Event virtualEvent = CreateVirtualEvent(event);
                if (virtualEvent.type != EVENT_NULL)
                {
                    bool passOn = ProcessEvent(virtualEvent);

                    if (m_engine != nullptr && passOn)
                        passOn = m_engine->ProcessEvent(virtualEvent);

                    if (passOn)
                        m_eventQueue->AddEvent(virtualEvent);
                }
            }
        }

        // Now, process the last received mouse motion
        if (m_private->lastMouseMotionEvent.type != SDL_NOEVENT)
        {
            m_private->currentEvent = m_private->lastMouseMotionEvent;

            Event event = ProcessSystemEvent();

            if (event.type == EVENT_QUIT)
                goto end; // exit the loop

            if (event.type != EVENT_NULL)
            {
                bool passOn = ProcessEvent(event);

                if (m_engine != nullptr && passOn)
                    passOn = m_engine->ProcessEvent(event);

                if (passOn)
                    m_eventQueue->AddEvent(event);
            }
        }

        // Enter game update & frame rendering only if active
        if (m_active)
        {
            Event event;
            while (m_eventQueue->GetEvent(event))
            {
                if (event.type == EVENT_QUIT)
                    goto end; // exit both loops

                bool passOn = true;

                // Skip system events (they have been processed earlier)
                if (! event.systemEvent)
                {
                    passOn = ProcessEvent(event);

                    if (passOn && m_engine != nullptr)
                        passOn = m_engine->ProcessEvent(event);
                }

                if (passOn && m_robotMain != nullptr)
                    m_robotMain->EventProcess(event);
            }

            StopPerformanceCounter(PCNT_EVENT_PROCESSING);

            StartPerformanceCounter(PCNT_UPDATE_ALL);

            // Prepare and process step simulation event
            event = CreateUpdateEvent();
            if (event.type != EVENT_NULL && m_robotMain != nullptr)
            {
                StartPerformanceCounter(PCNT_UPDATE_ENGINE);
                m_engine->FrameUpdate();
                StopPerformanceCounter(PCNT_UPDATE_ENGINE);

                m_sound->FrameMove(m_relTime);

                StartPerformanceCounter(PCNT_UPDATE_GAME);
                m_robotMain->EventProcess(event);
                StopPerformanceCounter(PCNT_UPDATE_GAME);
            }

            StopPerformanceCounter(PCNT_UPDATE_ALL);

            /* Update mouse position explicitly right before rendering
             * because mouse events are usually way behind */
            UpdateMouse();

            StartPerformanceCounter(PCNT_RENDER_ALL);
            Render();
            StopPerformanceCounter(PCNT_RENDER_ALL);

            StopPerformanceCounter(PCNT_ALL);

            UpdatePerformanceCountersData();

            if (m_lowCPU)
            {
                usleep(20000); // should still give plenty of fps
            }
        }
    }

end:
    Destroy();

    return m_exitCode;
}
Ejemplo n.º 17
0
int main()
{
    puts("KPSpamRunner");

    SDL_Event event; //event catcher
    
    SDL_Rect root;//root pixel coord
    root.x = 0;
    root.y = 0;

    
    const int windowSizeX=1024;
    const int windowSizeY=768;

    SDL_Init(SDL_INIT_VIDEO); //initialize SDL with video module
    TTF_Init(); //initialize the true type font library
    
    TTF_Font *font = NULL;
    font = TTF_OpenFont("./bolonium.ttf", 70);
    
    TTF_font_color blackFont = {0, 0, 0};
    
    if (font == NULL)
    {
        puts("Font not found");
        return -1;
    }



    //create a 32bit color window with bouble buffering and put it into the graphic card memory
    SDL_Surface *screen = SDL_SetVideoMode(
            windowSizeX, windowSizeY, 32, SDL_HWSURFACE| SDL_DOUBLEBUF); 
    

    SDL_WM_SetCaption("KPSpamRunner", NULL); //set the window title
    
    //background
    SDL_FillRect(screen, NULL,SDL_MapRGB(screen->format,  0, 128, 255));
    SDL_Surface *background  = IMG_Load("./Background.png");
    SDL_BlitSurface(background, NULL, screen, &root);

    //refresh window 
    SDL_Flip(screen);



    //GAME object
    
    Pikatux player; //create the player. he's a Pikatux ! =D

    int score = 0;

    SDL_Surface *pressEnter = TTF_RenderUTF8_Blended(font, "Appuyez sur Entrée !",blackFont);

    SDL_Surface* walkCycle[5]; //5 step of annimation
    
    //load it from files
    walkCycle[0] = IMG_Load("./walk-0.png");
    walkCycle[1] = IMG_Load("./walk-1.png");
    walkCycle[2] = IMG_Load("./walk-2.png");
    walkCycle[3] = IMG_Load("./walk-3.png");
    walkCycle[4] = IMG_Load("./walk-4.png");
    
    initPikatux_sprite(&player,walkCycle);
    initPikatux_Pos(&player); 
    char name[128];
    SDL_Surface *dispName = NULL;
    SDL_Surface *dispTime = NULL;
    SDL_Surface *dispScore = NULL;
    char dispScoreString[40];
    char dispTimeString[12]; 
    /////////////////////// GAME RUNNING
    int run = 1;
    int stage = TITLE; //will start on the title screen    

    SDL_Rect blitCursor;
    char input[2];
    input[1] = '\0';
    int curTime = SDL_GetTicks();
    int oldTime = curTime;
    int startTime = 0;
    int oldPressTime = 0;    
    int pikatuxRunning = 0;

    while(run) //render loop
    {
        //GRAPHIC RENDERING
        oldTime = curTime;
        curTime = SDL_GetTicks();
        SDL_FillRect(screen, NULL,SDL_MapRGB(screen->format,  0, 128, 255));
        SDL_BlitSurface(background, NULL, screen, &root);
        printf("curTime = %d\n", curTime);
        switch(stage)
        {
            default:
            case TITLE:
                blitCursor.x=768/2 -150;
                blitCursor.y=1024/2 + 20;
                SDL_BlitSurface(pressEnter, NULL, screen, &blitCursor);
                break;
            case SCORE:
                pikatuxRunning = 0;
                printf("SCORE = %d\n", score);
                sprintf(dispScoreString,"SCORE : %d",score);
                dispScore = TTF_RenderUTF8_Blended(font,dispScoreString,blackFont);
                blitCursor.y = 1074/2 + 20;
                blitCursor.x = 768/2 -30;

                SDL_BlitSurface(dispScore,NULL,screen,&blitCursor);
                break;
            case RUN:
                SDL_BlitSurface(player.sprite[player.step], NULL, screen, &player.coord);
                if (pikatuxRunning == 0)
                {
                    startTime = SDL_GetTicks();
                    pikatuxRunning = 1;
                }
                if (curTime - startTime >= 30000)
                {
                    pikatuxRunning = 0;
                    stage = SCORE;
                }

                sprintf(dispTimeString,"Time : %d", 30 - (curTime - startTime)/1000);
                blitCursor.x = root.x + 10;
                blitCursor.y = root.x + 10;
                dispTime =  TTF_RenderUTF8_Blended(font,dispTimeString,blackFont);
                SDL_BlitSurface(dispTime,NULL,screen,&blitCursor);
                
                break;
            case NAME_INPUT:
                dispName = TTF_RenderText_Blended(font, name, blackFont);
                SDL_BlitSurface(dispName, NULL ,screen, &root); 
                break;
        }
    
        //EVENT Processing
        SDL_WaitEvent(&event); //do NOT pause the program
        switch (event.type)
        {   
            case SDL_QUIT:
            run = 0;
            break;
        
            case SDL_KEYDOWN:
            switch (event.key.keysym.sym)
            {
                case SDLK_ESCAPE:
                    run = 0;
                    break;
                case SDLK_RETURN:
                if (stage == TITLE)
                    //stage = NAME_INPUT;
                    stage = RUN;
                if(stage == SCORE)
                {
                        score = 0;
                        stage = TITLE;
                }
                break;

                case SDLK_SPACE:
                if(pikatuxRunning)
                {
                    puts("space down");
                    score ++;
                    pikatux_step(&player);
                    pikatux_showSpeed(&player,SDL_GetTicks()-oldPressTime);
                    oldPressTime=SDL_GetTicks();
                }
                break;
            }
            
            if (stage == NAME_INPUT) //type text with the keyboard
            {
                if(SDL_KEYDOWN)
                {

                    if (event.key.keysym.sym >= 97 || event.key.keysym.sym <= 122)
                    {
                        if(strlen(input) < 126)
                        {
                            input[0] = (char) event.key.keysym.sym;
                            strcat(name,input);
                        }
                    }

                    if (event.key.keysym.sym == SDLK_BACKSPACE)
                        if(strlen(name) >= 1)
                            name[strlen(name) - 1] = '\0'; 
                }
            }

            break;
        }


        SDL_Flip(screen);
    }

    TTF_Quit();
    SDL_Quit();
    return 0;
}
Ejemplo n.º 18
0
static void
mainloop(void)
{
	SDL_Event		 event;
	int			 Px;
	int			 Py;
	double			 x0;
	double			 y0;
	double			 x;
	double			 y;
	const double		 ratio = (double) WINDOW_WIDTH / (double) WINDOW_HEIGHT;
	const double		 baserange = 3.0;
	double			 step = 0.1;
	bool			 output_params = false;

	if (ishift == 0.0) {
		xrange = ratio * baserange;
		yrange = baserange;
	}

	goto start;
	while (SDL_WaitEvent(&event)) {
		switch (event.type) {
		case SDL_QUIT:
			return;
		case SDL_WINDOWEVENT:
			if (event.window.type == SDL_WINDOWEVENT_EXPOSED)
				break;
			continue;
		case SDL_KEYDOWN:
			switch (event.key.keysym.sym) {
			case SDLK_LEFT:
				output_params = true;
				ishift -= step;
				break;
			case SDLK_RIGHT:
				output_params = true;
				ishift += step;
				break;
			case SDLK_UP:
				output_params = true;
				jshift -= step;
				break;
			case SDLK_DOWN:
				output_params = true;
				jshift += step;
				break;
			case SDLK_EQUALS:
			case SDLK_PLUS:
				output_params = true;
				xrange /= 2.0;
				yrange /= 2.0;
				step /= 2.0;
				break;
			case SDLK_MINUS:
				output_params = true;
				xrange *= 2.0;
				yrange *= 2.0;
				step *= 2.0;
				break;
			case SDLK_8:
				iterations = min_iterations;
				genpalette();
				printf("%d iterations\n", iterations);
				break;
			case SDLK_0:
				iterations *= 2;
				genpalette();
				printf("%d iterations\n", iterations);
				break;
			case SDLK_9:
				if (iterations > min_iterations) {
					iterations /= 2;
					genpalette();
					printf("%d iterations\n", iterations);
				}
				break;
			}
			if (output_params)
				printf("%lf %lf %lf %lf\n", ishift, jshift, xrange, yrange);
			output_params = false;
			break;
		default:
			continue;
		}

start:
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
		SDL_RenderClear(renderer);
		for (Py = 0; Py < WINDOW_HEIGHT; ++Py) {
			for (Px = 0; Px < WINDOW_WIDTH; ++Px) {
				x0 = (double) Px * xrange / (double) WINDOW_WIDTH - (xrange / 2.0) + ishift;
				y0 = (double) Py * yrange / (double) WINDOW_HEIGHT - (yrange / 2.0) + jshift;

				x = 0.0;
				y = 0.0;

				double iter = 0.0;

				while ((x*x + y*y) < (2 << 16) && iter < iterations) {
					double xtemp = x*x - y*y + x0;
					y = 2*x*y + y0;
					x = xtemp;
					iter = iter + 1;
				}

				if (iter < iterations) {
					double zn = sqrt(x*x + y*y);
					double nu = log(log(zn) / log(2)) / log(2);
					iter = iter + 1 - nu;
				}

				SDL_Color col1 = palette[(int) iter];
				SDL_Color col2 = palette[(int) (iter + 1.0)];
				double rem = fmod(iter, 1.0);
				SDL_Color col = lerp_color(&col1, &col2, rem);

				SDL_SetRenderDrawColor(renderer, col.r, col.g, col.b, col.a);
				SDL_RenderDrawPoint(renderer, Px, Py);
			}
		}
		SDL_RenderPresent(renderer);
	}
	errx(EXIT_FAILURE, "SDL_WaitEvent: %s", SDL_GetError());
}